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

设置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如下:

Item1
Item2
Item3

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

.content div{

    width:100px;

    text-align:center;

    float:left;

}

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

Item1
Item2
Item3

你可能感兴趣的:(浮动(float)块元素水平居中)