Search code examples
csscss-floatclearfix

CSS clear float with :after element not working


I can't seem to get this right. It's quite simple, clear the float after the h4 element (widget-title), so that the text box aligns left on a new line.

The HTML cannot be changed.

Here is the fiddle: http://jsfiddle.net/j29ubvjw/

.widget-wrap {
    padding:15px;
    background-color: #EEE;
}

.widget-title {
    font-size: 18px;
    margin:-15px 0 15px -15px;
    background-color: #CCC;
    padding: 15px;
    float:left;
}

.widget-title:after {
    content: "";
    display: block;
    clear: both;
}


<div class="widget-wrap">
    <h4 class="widget-title">My Title</h4>
    <div>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper</p>
    </div>
</div>

What am I doing wrong?


Solution

  • Note that ::after pseudo-element doesn't create content after the element itself, but appends a pseudo-child-element into the element.

    In other words, by using .widget-title::after, a pseudo-element is appended after the contents of the elements matching .widget-title selector.

    <h4 class="widget-title">
        ::before <!--appended pseudo-element -->
        My Title
        ::after  <!--appended pseudo-element -->
    </h4>
    

    In order to clear the floats after the heading, you could select the next adjacent sibling element and set clear: both; declaration to it:

    Example Here

    .widget-title + * { clear: both; }
    

    Or in this case:

    .widget-title + div { clear: both; }