Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to contain floating elements using HTML/CSS?

Tags:

html

css

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: floaty divs

What's the proper CSS way to have the container (red-bordered box) completely surround the floaty green-bordered boxes?

like image 454
Roy Tang Avatar asked Jul 22 '10 12:07

Roy Tang


People also ask

How do you contain floats?

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.)

Is it good practice to use float in CSS?

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!

What is the correct syntax for float property?

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.


2 Answers

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.

like image 141
Nick Craver Avatar answered Oct 12 '22 07:10

Nick Craver


add overflow: auto to the container or apply a clearfix.

like image 34
Pekka Avatar answered Oct 12 '22 06:10

Pekka