Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid empty clear divs?

I have been using a lot of floats recently like this:

<div id="buttons">
  <input type="button" id="btn1" value="Button One">
  <input type="button" id="btn2" value="Button Two">
  <input type="button" id="btn3" value="Button Three">
</div>

Sometimes I'll float a button to the right. Sometimes I'll float all of them to the right. This is where the problem starts. It really throws the flow off if I do that so I have to keep putting in these:

<div style="clear:both;"></div>

at the end. That throws off the layout if I'm not floating them all.

Is there a good solution to this?

like image 870
Jordie Avatar asked Nov 29 '22 20:11

Jordie


2 Answers

Yes, use overflow: hidden on the container ie:

<style type="text/css">
#buttons { overflow: hidden; }
</style>
like image 171
cletus Avatar answered Dec 09 '22 17:12

cletus


This is a big part of the CSS learning curve. When you float items, their containing element no longer takes the vertical height of the floated elements into account. There are a couple of solutions you could use to get around your dilemma.

Simply specify a hight for your #button container to the hight of your buttons:

#button { height: 30px; }

A fancier solution would be the clearfix hack. It's pretty bullet proof and will also do the trick without the need to add the extra markup and inline CSS.

#buttons:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

#buttons {
    display: inline-block;
}

html[xmlns] #buttons {
    display: block;
}

* html #buttons {
    height: 1%;
}
like image 20
Mark Eagleton Avatar answered Dec 09 '22 19:12

Mark Eagleton