Force Margin/Space Between List and Floated Image
If you’re displaying floated images in your posts, you may notice that margins of lists and other block-level elements seem to “collapse”, as shown in this screenshot from the 2013 redesign:
And here is what is happening behind the scenes (Chrome browser):
As you can see, the list is simply ignoring the floated item and stretching across the entire width of the content area. Depending on the design, this may not be a huge deal, but there is an easy way to prevent it from happening. Just apply a width
and overflow
property to the list element:
.content ul, .content ol { width: auto; overflow: hidden; }
Applying that code, the margin kicks in and we get this:
..which looks like this under the hood:
This trick also works on other block-level elements, such as <div>
s. Here is another example from the recent redesign, which shows a <div>
stretching full-width behind the floated element, again in Chrome:
To get the popout <div>
to sit next to the floated image — without floating it — we apply the simple fix:
.popout { width: auto; overflow: hidden; }
..which gives us this:
..and via Inspect Element:
That’s pretty much it, although for this design I opted to let the popout divs stretch behind the floated images, just seems like a nice effect :)
This technique tested on latest Chrome 67+, Firefox 60+, and Opera 53+.
39 responses to “Force Margin/Space Between List and Floated Image”
the keyword is: “Block formating context”. It’s very important to known.
A new block formatting context can be created not only by the
overflow
property. There are other methods too. All of them won’t hide the overflowing content :)I also have an additional remark :)
This method is good when a list content shouldn’t be under the floated image. Because it will never be under it.
Great fix, thanks for sharing.
Excellent! Tripped onto this only to find it’s exactly what I’ve been needing. Thanks!
…you can set list-style-position: inside; to “li” element and… ready.
Thank you very much!
Can anyone briefly explain why this works for the newbies?
Over the years, looking for a solution. Sir, you are just darling!
been waiting for this for way too long…
I really like this, but i don’t like this nature of hacking css, look we don’t have any clear reason why this is happening. When ever you ask such you get answers like “according to w3c this property supposed to work that way”. CSS you are to young as far as layout is concerned.
I spent so long trying to figure out how to do this, and eventually gave up. Thank you! You’re awesome. Bookmarked!