CSS:如何防止div的背景色位于其上方的图像后面? [英] CSS: How do I prevent the background color of div from going behind the image it is sitting above?
问题描述
我有一个div,向其应用了负边距,使其位于图像顶部.我还为该div设置了背景色.发生的是(div的文本)出现在div上方,这与我期望的一样,但是该div的背景色在图像后面,这是我所不希望的.如何使div的背景色位于图片上方? * *:before *:after
规则来自引导程序.我知道我本可以使用绝对定位,但我内心深处知道负边距是完全合法的.
I have a div that I applied negative margins to so that it sits on top of an image. I also gave that div a background color. What happens is the text (of the div) is appearing above the div as I would expect but the background color of that div is going behind the image, which I do not expect. How I can get the background color of the div to sit above the image? The * *:before *:after
rule is from bootstrap. I am aware that I could have used absolute positioning but I know deep in my heart that negative margins are completely legit.
这是我的证明:
http://jsfiddle.net/BB4d2/1/
HTML:
<ul class="profile-kids">
<li class="profile-kid">
<img class="f" src="http://lorempixel.com/g/300/300/people/" height="150" width="150">
<div class="kid-text">Girl</div>
</li>
<li class="profile-kid">
<img class="f" src="http://lorempixel.com/g/300/300/people/" height="150" width="150">
<div class="kid-text">Girl</div>
</li>
<li class="profile-kid">
<img class="m" src="http://lorempixel.com/g/300/300/people/" height="150" width="150">
<div class="kid-text">Boy</div>
</li>
</ul>
CSS:
*, *:before, *:after {
-moz-box-sizing: border-box;
box-sizing: border-box;
}
ul.profile-kids {
list-style-type: none;
padding-left: 0px;
}
li.profile-kid {
display: inline-block;
margin-bottom: 20px;
margin-right: 10px;
cursor: pointer;
}
img.f {
z-index: 0;
border: 10px solid rgb(254, 134, 164);
border-radius: 75px;
display: inline-block;
}
img.m {
border: 10px solid rgb(120, 192, 249);
border-radius: 75px;
display: inline-block;
}
div.kid-text {
background: #FFFFFF;
text-align: center;
width: 150px;
font-size: 20px;
margin-top: -100px;
}
推荐答案
只需将 position:relative;
分配给 div.kid-text
div.kid-text {
background: #FFFFFF;
text-align: center;
width: 150px;
font-size: 20px;
margin-top: -100px;
position: relative;
z-index: 999; /* Optional */
}
此外,您可以使用 z-index:999;
以确保安全...
Also, you can use z-index: 999;
to be safe...
这篇关于CSS:如何防止div的背景色位于其上方的图像后面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!