3

回到基础,我有一个情况,我有一个图像需要出现在它正下方的元素的背景上。但是,我不希望图像超出该元素内容的顶部,只希望元素(和背景属性)本身:

http://jsfiddle.net/chricholson/4twr5/1/

HTML:

<img src="https://www.google.com/images/srpr/logo3w.png" />

<div>
    <a href="#">Hello World</a>
</div>
​

CSS:

img { position: absolute; z-index: 20; }

div { position: relative; top: 45px; z-index: 10; padding: 30px; background: red; }

a { position: relative; z-index: 30; padding: 10px; background: yellow; display: block; }

预期的行为将是图像出现在 div 背景[check]的顶部,但随后出现在黄色链接后面,但事实并非如此。

4

5 回答 5

5

Found my "answer" (more confirming my doubts) here Can't get z-index to work for div inside of another div. The key sentence being "Once you set position:relative on test_1 you are causing its z-index to be in a different world than the z-index of test_2."

It seems the reason I have a problem is because once I have set the image higher than the div, no matter what z-index value I set to the contents of the div it will always be covered. I didn't think z-indexes worked like this, I thought everything was "separate" and so long as a value was higher than a value elsewhere (regardless of parent containers) things would be fine.

于 2012-08-30T15:52:01.163 回答
0
img { position: absolute; z-index: 15; }

div { position: relative; top: 45px; z-index: 20; padding: 30px; background: red; }

a {z-index: 30; padding: 10px; background: yellow; display: block; }
​

你可以试试这段代码。顺便说一句,a 是 div 的孩子。你不需要输入 position: relative; 因为你是为 div 写的。

于 2012-08-30T15:20:11.983 回答
0

http://jsfiddle.net/4twr5/21/看看这个 jsfiddle

根据评论更新http://jsfiddle.net/4twr5/22/

于 2012-08-30T15:26:41.877 回答
0

将图像放入 div 中,如下所示:

<div>
    <img src="https://www.google.com/images/srpr/logo3w.png" />
    <a href="#">Hello World</a>
</div>
于 2012-08-30T15:27:35.867 回答
0
于 2012-08-30T15:38:04.403 回答