简体   繁体   中英

CSS: How do I prevent the background color of div from going behind the image it is sitting above?

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.

Here's my proof:
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;
}

Just assign position: relative; to the div.kid-text

Demo

div.kid-text {
    background: #FFFFFF;
    text-align: center;
    width: 150px;
    font-size: 20px;
    margin-top: -100px;
    position: relative;
    z-index: 999; /* Optional */
}

Also, you can use z-index: 999; to be safe...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM