Charles Ingalls
Charles Ingalls

Reputation: 4561

How to float two elements in li element without clearing each time

I am having a stacked list where I want to float an img (icon) and the text. However, I feel its a pain to clear after each list item. What's the solution here? Any tips how to make it more clean?

<ul>
  <li><img src="#" /> <a href="#">Home</a></li>
  <div class="clear"></div>
  <li><img src="#" /> <a href="#">About</a></li>
  <div class="clear"></div>
</ul>

Upvotes: 0

Views: 140

Answers (3)

Michael Unterthurner
Michael Unterthurner

Reputation: 941

You need the clear only one time and that is after the ul.

<ul>
   <li><img src="#" /> <a href="#">Home</a></li>
   <li><img src="#" /> <a href="#">About</a></li>
</ul>
<div class="clear"></div>

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

You could make the li elements to clear..

<ul>
  <li class="clear"><img src="#" /> <a href="#">Home</a></li>
  <li class="clear"><img src="#" /> <a href="#">About</a></li>
</ul>

If you only float the contents of the li (the img and the a) then you can just set the overflow of the li to auto or hidden and it will work as expected.

li{overflow:auto;}

Demo at http://jsfiddle.net/SqWHB/

Upvotes: 1

Chris Koster
Chris Koster

Reputation: 403

Yes, use a class for the clearfix:

and add this css:

.clearfix:before, .clearfix:after {
    display: table;
    line-height: 0;
    content: "";
}

.clearfix:after {
      clear: both;
}

Upvotes: 0

Related Questions