简体   繁体   中英

Proper way to contain floating elements using 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: 浮动的divs

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

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 .

添加overflow: auto到容器或应用clearfix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM