2012-09-25 47 views
3

我在想这是不可能的,但我不是CSS专家,所以我想我会检查。我有一个绝对定位在图像上的半透明div。目前为止还不错,但我想强制我的半透明div尊重它和图像所包含的方框。尊重父箱子覆盖兄弟箱

<div class="parent"> 
    <div class="title-bar"> /* prolly not important */ 
    <h2>Title</h2> 
    </div> 
    <img src="whatever"/> 
    <div class="overlay"> 
    A few lines of txt 
    </div> 
</div> 

我越去想它,我越觉得我可能会问的太多了 - 我希望父与IMG扩大,但覆盖由母的限制。这可以做到吗?

回答

5

要强制容器与儿童img一起展开,请将其制作成float
要强制覆盖层与容器的位置和大小相关,请使容器relative

.parent { 
    float: left; 
    position: relative; 
} 

要强制覆盖尊重容器的边界,请使用百分比。

.overlay { 
    position: absolute; 
    max-width: 100%; 
    /* And then, position it at will */ 
    top: 0; 
    left: 0; 
} 

我准备了一个例子:http://jsfiddle.net/rYnVL/

1

这是doable, but not quite beautiful

<div id="parent"> 
    <div id="abs">stuff fadsfasd fsad fasdsdaf </div> 
    <img src="/img/logo.png" /> 
</div> 

#parent {width:auto; height:auto; border:1px solid blue; background-color:grey;position:relative; display:block;float:left;} 

#abs {position:absolute;width:100%;height:100%;background:#ff0000;opacity:0.4;} 

主要一点要注意:
parent浮没有100%的宽度。职位是相对的。
abs是绝对的,具有100%的尺寸。

另外,如果abs内容比图像大,就会溢出。如果你不喜欢这个,只需加上overflow:hidden即可。