Search code examples
htmlcsscss-position

how can I move div with position:relative above div with position:absolute?


At my site I have a block with image as background and title above the image:

html

<div class="block">
    <img src="someimage.png" />
    <div class="title">Some title</div>
</div>

css

.block {
    position:relative;
}
.block img {
    position:absolute;
    top:0;
    left:0;
}
.block .title {
    margin-top:100px;
    text-align:center;
}

Requirements for the .block:

  • I cannot change <img> with <div style='background-image:url(someimage.png)'> - it must be <img>
  • .title must be relative

But the problem - absolute div hides the title. . Playing with z-index do nothing just because z-index does not work with relative elements. So my question - how can I organize this block. Any advices will be very apprecated!


Solution

  • z-index does work with relative positioning. Just set the .title to relative (or inherit since its parent is relative) and add a z-index

    Per http://www.w3.org/wiki/CSS/Properties/z-index

    Only works on positioned elements(position: absolute;, position: relative; or position: fixed;)

    CSS

    .block {
      position:relative;
      width: 100px;
     }
    
     .block img {
      position:absolute;
      top:0;
      left:0;
    }
    
    .block .title {
      margin-top:100px;
      text-align:center;
      color: #FFF;
      position: relative;
      z-index: 1
    }
    

    FIDDLE