How to do a `float: left` with no wrapping?

家住魔仙堡 提交于 2019-12-02 17:07:38

You need box 3 to be a block level element, so use display:block and then toss in an overflow:hidden in conjunction with float-ing box 2:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <style type="text/css">
            #box1 {  }
            #box2 { float:left; }
            #box3 { display:block;overflow:hidden; }

            /* Styling */
            #box1 { background: #ddd; padding: 1em 0.5em; width: 20em }
            #box2 { background: #999; padding: .5em; }
            #box3 { background: #bbb; padding: .5em; }
            body  { font-family: sans-serif }

        </style>
        <script type="text/javascript">
        </script>
        <title>How to do a `float: left` with no wrapping?</title>
    </head>
    <body>
        <div id="box1">
            <span id="box2">2</span>
            <span id="box3">3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br />3<br /></span>
        </div>
    </body>
</html>

Amazing all the things overflow:hidden can do :D

There are a couple of ways to achieve this. Two common ones is either to have an empty element right after with a clear: both like so (inline css just for demo):

<span class="box1">...</span>
<br style="clear:both"/>

Another way is to use overflow: hidden like so:

<span class="box1" style="overflow: hidden">...</span>

However, there are problems with both of these solutions. With the first one you add unnecessary and ugly markup. And with the second if you want something to be positioned outside of your box (like a position: absolute) it won't be visible.

A more common, modern solution is to use the ::after pseudo-element and clear that like so:

.box1::after {
    content: '';
    display: table;
    clear: both;
}

I'd recommend the following:

#box1
{
    position: relative; /* or some other positioned value */
}

#box2
{
    width: 10px;
    height: 10px;
    position: absolute;
    top: 0;
    left: 0;
}

#box3
{
    margin-left: 10px;
}

If #box2 is of a fixed size, you can simply use a margin for #box3 to prevent its overlapping of #box2, and since it's not positioned, #box1 will grow as #box3 grows.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!