浮动(float)块元素水平居中

2018-11-30  本文已影响0人  Whisper_X

设置float属性的div,会脱离正常文档流,自身变成block,易造成“父元素高度坍塌”,因此父元素必须设置height属性,且height属性值应大于子元素的height

.container{

    width:400px;

    height:110px;

    margin:0 auto;

    border:dashed #26c7be;

}

.content{

    width:300px;

    margin:0 auto;

}

.floatBox{

    width:100px;                                      /* 宽度一定要设置,否则无法实现自动水平居中*/ 

    text-align:center;

    float:left;

}

HTML如下:

<div class="container">

    <div class="content">

        <div class="floatBox"><input type="checkbox" title="This is first choice" checked/>Item1</div>

        <div class="floatBox"><input type="checkbox" title="This is second choice"/>Item2</div>

        <div class="floatBox"><input type="checkbox" title="This is third choice"/>Item3</div>

</div>

若某一类下全浮动,可以写成如下形式,令包含在content类下的所有div拥有浮动属性即可:

.content div{

    width:100px;

    text-align:center;

    float:left;

}

这样就省去了定义floatBox类的麻烦,HTML如下:

<div class="container">

    <div class="content">

        <div><input type="checkbox" title="This is first choice" checked/>Item1</div>

        <div><input type="checkbox" title="This is second choice"/>Item2</div>

        <div><input type="checkbox" title="This is third choice"/>Item3</div>

    </div>

</div>
上一篇下一篇

猜你喜欢

热点阅读