Floats push elements out of the flow, which is why the header overlaps with them. To prevent this, creating a block formatting context is necessary.
An effective method is to set overflow
to anything other than visible
, for example:
h2 {
overflow: hidden;
}
As stated in CSS 2.1 Floats,
Since a float is not in the flow, non-positioned block boxes created
before and after the float box flow vertically as if the float did not
exist.
The border box of a table, a block-level replaced element, or an
element in the normal flow that establishes a new block formatting
context (like an element with overflow
other than visible
)
should not overlap the margin box of any floats within the same block
formatting context
body {
max-width: 300px;
}
.right {
width: 100px;
height: 100px;
background: #eee;
float: right;
margin: 0 0 0 20px;
}
.clear {
clear: both;
}
.left {
width: 100px;
height: 100px;
background: #eee;
float: left;
margin: 0 20px 0 0;
}
h2 {
overflow: hidden;
}
h2:after {
content: '';
position: relative;
max-width: 100px;
display: block;
height: 4px;
background: #0073ae;
}
<h2>Good heading here</h2>
<div class="right"></div>
<h2>Another good heading here</h2>
<p>anything here</p>
<br class="clear">
<div class="left"></div>
<h2>Bad heading here</h2>
<p>anything here</p>