Why does CSS float not change the width of the following div?

后端 未结 3 1603
时光取名叫无心
时光取名叫无心 2020-11-27 08:07

As I understand float:left, it will push the subsequent element to its left rather than on a new line.

In the following example I would expect that the

3条回答
  •  眼角桃花
    2020-11-27 08:40

    You need to float the yellow div as well, then it will work;

    .inline {
        float:left;
    }
    
    .yellow {
        background-color:yellow;
        float: left;
    }
    

    However, just floating elements doesn't put it on the left of the next element automatically, so you need display: inline-block; to show the next div on the same line and display: block; to show underneath.

    You should also give a width (in percent if you want) for both divs that add up to 100% or less including any left and right margins and padding if displaying inline.

    The other thing you could do is set a width for .inline and float it, then give .yellow the same value as its left margin and don't float it.

    .inline {
        float:left;
        width:50px;
    }
    
    .yellow {
        background-color:yellow;
        margin-left:50px;
    }
    

    This will allow the .yellow div to fill the remaining width.

    Hope this helps.

提交回复
热议问题