I need to find a way to clearfix a set of floated elements without extra markup.
For example, I have a 2 columns grid in section#main_features
. Each div.feature
has width: 50%
and is float: left
. What I want is to find a way to clearfix the rows without extra html markup (since I want to make a simple semantic grid).
<section id="main_features">
<div class="feature">
...
</div>
<div class="feature">
...
</div>
<div class="feature">
...
</div>
<div class="feature">
...
</div>
</section>
Note that the rows here are just a "concept" (each row is two .feature
). I'm using a semantic approach to build this grid, therefore I don't want to need to wrap the columns of each row and then clearfix this wrapper. I'm looking for some trick to clearfix and break the row using only css - or scss, less, etc.
This problem seems to be more complex than it looks.
Thanks in advance.
I have been using the semantic group
'micro clearfix' which I found on CSS Tricks.
.group:after {
content: "";
display: table;
clear: both;
}
The CSS is similar to the above solutions, however the concept is that you can add it to any element which you wish to 'group' together and be followed by a clear. Eg:
<header id="masthead" class="group">
//content
</header>
The above link also has sub-IE8 rules.
EDIT My apologies, I just answered the title of the question, without properly reading your scenario. I would not use floats in this case. Instead, I like to use display: inline-block
like so:
#main_features {
font-size: 0; /* this resets the default padding created by the inline-block rule below */
margin: -2%; /* offsets the positive margin below */
}
.feature {
display: inline-block;
vertical-align: top;
width: 46%;
margin: 2%; /* width + (2x margin) = 50%*/
font-size: 12px; /* because it is reset to 0 by parent */
}
The font is set to zero on the parent element because some browsers add padding to an inline-block
element. The parent element also has a negative margin to offset that of its children. This allows the content to align with the rest of your page.
I have made a basic demo of this here.