Search code examples
htmlcsssemanticssemantic-markup

Semantic HTML and clear: both


We are trying to get our HTML much more semantic and the one thing that seems to linger in our HTML that has to do with presentation is

<div class="clear"></div>

For example, if we have the following semantic html:

<div class="widgetRow">
    <div class="headerInfo">My header info</div>
    <div class="widgetPricing">$20 to $30</div>
    <div class="footerInfo">My footer info</div>
</div>

And I have headerInfo and footerInfo both floated left in the CSS and widgetPricing floated right (just as an example).

The Question:

My widgetRow div doesn't have any height or width. Is it wrong to add <div class="clear"></div> right after .footerInfo ? It seems that I'm not being semantic at that point.

The More Generic Question

When writing semantic HTML, is it ok to put a div in your HTML whose only job is to clear the floats?


Solution

  • There are several ways to clear floats:

    1 . Use CSS pseudo :after class

    .container:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }
    

    Apply the container class to your "widgetRow" div. This approach is probably the most semantic, but it is not supported on all browsers, specifically IE7 and below. browser support for :after

    2 . Use overflow:auto or overflow:hidden

    .container { overflow:auto; }
    .container { overflow:hidden; }
    

    Again, apply the container class to your "widgetRow" div. This approach may be a little more semantic, but it could also come back to bite you especially when viewed on smaller displays. overflow:auto could trigger a horizontal scrollbar while overflow:hidden could hide the element all together. problems using oveflow to clear floats

    3 . Use clear:both

    .clear { clear:both; }
    

    This is the approach you are using assuming your clear class is like the one above. This is the only approach I know of that is compatible in all browsers and won't give you undesirable side effects. So, depending on what browsers you support, I would probably stick with what you have.