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

后端 未结 3 1730
孤城傲影
孤城傲影 2021-01-31 09:24

I have a container box1 that has a certain width (which might change depending on its content). That box contains box2 which has a fixed width (it coul

3条回答
  •  误落风尘
    2021-01-31 09:47

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

    ...
    

    Another way is to use overflow: hidden like so:

    ...
    

    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;
    }
    

提交回复
热议问题