The best way to “clear: both” [closed]
Question
For long now, I've been using a CSS class called clear
, which only has the rule clear: both
. I use it in the following way (shown in Django-syntax, but it is unimportant):
{% for item in collection %}
<ul class="horiz"><!-- horizontal list -->
<li>{{ item }}</li>
<li>{{ item }}</li>
</ul>
<div class="clear"></div>
{% endfor %}
As you can see, I'm doing a bunch of horizontal lists, to make it look just like a table. Imagine that the CSS rule .horiz li
implies float: left
. Note that I'm using <div class="clear"></div>
after each row in this "table", a lot of HTML for something so simple.
Is this really the way to go? Isn't there anything simpler that I just haven't thought about?
Solution
Is there a reason you can't use...
<ul class="horiz clear">
... for every list except the first?
OTHER TIPS
There's way to do it in CSS
http://www.positioniseverything.net/easyclearing.html
#pages ul li { display: block; float: left; ....... } #pages ul:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
If you want each of the lists to show whatever is in them, without having to add a filler DIV
tag, you can adjust the overflow
property of the list with this:
.horiz
{
overflow:hidden;
}
Now, even if the list-items themselves are floated, the contents of the list should show without collapsing the area as they maybe doing now because they are shifted out of flow.
You can have your ul
with overflow: hidden;
. This establishes a new block formatting context for each ul
which is exactly what you want.
I used to clear: both;
like you, but once I discovered this weird little quirk, I've begun using this almost exclusively. It seems semantically superior and works in 99% of cases.
Why not give your UL and your LI fixed widths, where the width of the UL is at least twice the width of the LI, but less than 3 times the width of an LI.
Then you can put all of your LI's in one UL and put a float: left
on the LI.
This will cause each list item to appear next to each other, but they will wrap onto the following line when they run out of room (due to the width of the UL).
Another one advice. You can use clear:both in "break(<br/>
)" tag. No need to code in div. See the below
Coding in CSS:
.clear {
clear:both;
height:0;
font-size: 1px;
line-height: 0px;
}
Using is HTML:
<br class="clear" />
Try!!!
The most obvious solution is to move the clear: both
to the next element in your layout. If this ul
is being followed by a div
, give that div
a class="clear"
, etc.
Put the clear on the ul
.
I'm agree with Logesh Paul, Its become more simple to use br instead of div.
but i think you should put the clear element outside the looping.