I have a div with some inline elements inside it. I want to put one of the elements on the left and the rest over on the right:
+---------------------------+
Currently floats are probably the only way to get the desired result. You can also float the parent container, but then you'll then have to give it a width. This method can quickly lead to a 'float everything' layout, but it works. http://jsfiddle.net/mjzNP/
When you float elements the parent's height is not calculated. Either you can use the clearfix class, or you can clear floats using the overflow property.
You can also add <div style="clear:both;"></div>
at the end of your parent div, however this is less semantic the the above solutions.
However, what you choose to use is really a personal preference.
Also you might want to try using a grid system. You can try 960 or Bootstrap.
For the record, there is a better (at least in my eyes) way of doing this than float-happy clearfixing. Use display: inline-block
. The downside? IE7 doesn't support it (of course). The below works, though, in IE8 and above and Chrome, Firefox and Opera.
NOTE: I've simplified the demo's CSS in an attempt to dispel perceptions this is complicated. It's not. The display: inline-block
is the only part you need; the rest is part of the attempt to match what the OP described in the question's depiction.
<div id="container">
<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>
</div>
#container {
background: #ffffd;
text-align: center;
}
#container > div {
background: #cff;
display: inline-block;
padding: 2%;
height: 100px;
width: 25%;
}
#container #a {
height: 30px;
margin: 0 10% 0 0;
}
http://jsfiddle.net/AZJzz/4
You need to clear out your floating elements like this :
<div style="clear: both;"></div>
My Fiddle
If you dont-clear it'll be like this : My Fiddle (Floats not cleared)
Place this line after it:
<div style="clear:both;"></div>
This should extend the div they are in to fit around them.
Here's a live demo, to illustrate how to do it.
One simple solution is to add overflow:auto
to the container in order to solve this. This will cause the container to expand to contain its floats but will make scrollbars appear if for some reason someone additionally sets a small height for the container.
There are also other alternatives that also work and might be better in other cases. See this question and its second answer for a good overview on the problem.