Supernohva Supernohva -3 years ago 93
CSS Question

Overlay div that snaps on overflow with parent

Problem:

Essentially I have a row of in-line containers with images inside them, and an overlapping div with text at the bottom of the div/image. When the window is resized horizontally, the image and div snap to the row below it and stay inline. However, the overlay does not snap with them until it is completely covered by the horizontal resize of the window, which only then it will snap below the row and appear with the rest of the container.

If you keep resizing the window horizontally, eventually the overlay div will snap down and appear in its correct position.

Question:

How can I make it, via CSS, JS or jQuery, so that the overlay div follows the container it's in when the overflow forces the containers into the next row?



#container {
position: relative;
display: inline;
}

#overlay {
position: absolute;
display: inline;
text-align: center;
height: 20px;
background-color: gray;
width: 304px;
bottom: 0;
}

<div id="container">
<div id="overlay">
Test
</div>
<img src="http://www.navipedia.net/images/a/a9/Example.jpg" alt="Mountain View" style="width:304px;height:228px;">
</div>

<div id="container">
<div id="overlay">
Test
</div>
<img src="http://www.navipedia.net/images/a/a9/Example.jpg" alt="Mountain View" style="width:304px;height:228px;">
</div>





Example Fiddle: https://jsfiddle.net/buqbxgzz/2/

Answer Source

There are several issues with your code:

  1. You are recycling IDs in your markup. IDs must be unique in a document. For example, use .container instead of #container.

  2. Using position: absolute and display: inline on the overlay doesn't make a lot of sense, because it will be set to block level automatically (i.e. display: block).

  3. Also, as long as you switch to display: inline-block on the container elements, the positioning will work. The reason is a bit convoluted, but if you look at the elaborate description of stacking contexts by W3C, you can see that inline level elements have a very different (and probably counterintuitive) characteristics described, compared to inline-block or block elements.

.container {
  position: relative;
  display: inline-block;
}

.overlay {
  position: absolute;
  text-align: center;
  height: 20px;
  background-color: gray;
  width: 304px;
  bottom: 0;
}
<div class="container">
  <div class="overlay">
    Test
  </div>
  <img src="http://www.navipedia.net/images/a/a9/Example.jpg" alt="Mountain View" style="width:304px;height:228px;">
</div>

<div class="container">
  <div class="overlay">
    Test
  </div>
  <img src="http://www.navipedia.net/images/a/a9/Example.jpg" alt="Mountain View" style="width:304px;height:228px;">
</div>

See fixed fiddle: https://jsfiddle.net/buqbxgzz/4/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download