Say I have the following HTML:
<head>
<style>
#container {
border: 1px red solid;
}
.floaty {
width: 200px;
float: left;
border: 1px green solid;
}
</style>
</head>
<body>
<div id='container'>
Text inside the container
<div class='floaty'>
Floaty block 1<br/>
Floaty block 1<br/>
Floaty block 1<br/>
</div>
<div class='floaty'>
Floaty block 2<br/>
Floaty block 2<br/>
Floaty block 2<br/>
</div>
<div class='floaty'>
Floaty block 3<br/>
Floaty block 3<br/>
Floaty block 3<br/>
</div>
</div>
</body>
This renders as:
What's the proper CSS way to have the container (red-bordered box) completely surround the floaty green-bordered boxes?
Floating the container A good way to contain floated elements is to float the container as well. This will always work to contain the floats; but it is not always appropriate, such as when the container is a horizontally centered page wrapper. (The wrapper would no longer be centered on the page.)
The short answer: clear: both. Floats work really well in small cases like when there's an element, such as a button, that you'd like to move to the right of a paragraph. But the real issue arises when you start using floats to lay out entire web pages. And the reason for that is: floats are not meant for layouts!
The syntax for the float CSS property is: float: value; CSS float property can have the following values: None: There will be no effect on the position of the element i.e., the element will not float.
Add an overflow: auto
to the container, like this:
#container {
border: 1px red solid;
overflow: auto;
}
You can test the effect here, and find a very good description of how it works here.
add overflow: auto
to the container or apply a clearfix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With