Search code examples
htmlcsscss-positionz-index

Absolute position for child when parent uses float


I am doing a setup where two images and a text container are side by side using float left, however I also need to use an overlay div with some text when the user hovers over, but this breaks the display.

Here is my HTML code:

<div class="container">
  <div class="parent-container">
    <div class="child-container">
      <img src="http://blog.hdwallsource.com/wp-content/uploads/2016/02/solid-color-wallpaper-21953-22506-hd-wallpapers.jpg" alt="" />
      <div class="overlay">
        <p>Some text</p>
      </div>
    </div>
    <div class="child-container">
      <img src="http://www.pixelstalk.net/wp-content/uploads/2016/06/Solid-Color-HD-Wallpapers-For-Desktop-768x432.jpg" alt="" />
    </div>
    <div class="child-container-text">
      <p>hhohdoioadoasabs</p>
    </div>
  </div>
</div>

And here is my CSS:

.parent-container {
  position: relative;
  width: 100%;
}

.child-container {
  float: left;
  position: relative;
  width: 30%;
}

.child-container img {
  position: absolute;
  height: 100px;
  width: 100%;
}

.child-container-text {
  background-color: #000;
  float: left;
  height: 100px;
  position: absolute;
  width: 40%;
}

.overlay {
  background-color: #FFF;
  opacity: 0.3;
  position: absolute;
  z-index: 999;
}

And here is a CodePen with it: https://codepen.io/leofontes/pen/ORPJWd?editors=1100

Any idea why they are getting stacked? I had used the same trick of absolute positioning for overlays before and it worked, why is the float breaking it?

Thank you


Solution

  • https://jsfiddle.net/37LsfmLa/ See the fiddle for a working example. (Sorry, I have no clue how codepen works!)

    Your question is vague, but I believe this is what you're looking for. The problem with your code is that you gave the images an absolute position, while having them in a floated div. Standard float behaviour will collapse any empty div. It will shrink any element to its contents size. Your elements have their width set, which should fix that problem, but there's another: they have no height. The result: They collapse. -- note that an elements with position:absolute do not count as content that stretch their parents.

    That's where your problem was. You need to give your divs a static height in order to make something like this work, though I'm wondering why your images even have position:absolute? But, whatever floats your boat. (I wouldn't use position:absolute on any image that should fill an element, but that's just my preference)

    .child-container {
      float: left;
      position: relative;
      width: 30%;
      display: block;
      height: 100px;
    }
    

    ^ the above is what fixed it. A simple height property.