摘要: flexbox是个很强大的布局模块,三个属性就搞定居中,而且不论父容器还是居中元素都可以不定宽高
水平居中
align="center"
直接在标签对象内加align="center"
即可让对象内图片横向水平居中显示
<div align="center">aaa</div>
text-align:center
<style>
.divcss5{text-align:center}
</style>
<div class="divcss5">aaa</div>
把margin设为auto
具体来说就是把要居中的元素的margin-left和margin-right都设为auto,此方法只能进行水平的居中,且对浮动元素或绝对定位元素无效
<style>
body{ text-align:center}
.div{ margin:0 auto;}
</style>
<div class="div">aaa</div>
使用display:table-cell来居中
对于不是表格的元素,可以通过display:table-cell 来模拟成一个表格单元格,这样就可以利用表格很方便的居中特性了
<div style="display:table-cell;width:200px;height:200px;border:1px solid #ccc;">
<div>aaa</div>
</div>
使用绝对定位来进行居中
使用这个方法的好处在于无论你是什么形式的内容都可以马上居中,而缺点就是必须对元素有确定的宽高值,否则的话可能就需要通过javascript来进行一些小计算了
<style>
.child{width:100px;height:100px;position:absolute;left:50%;margin-left:-50px;}
</style>
<div class="parent">
<div class="child">aaa</div>
</div>
利用盒模型实现水平居中--padding填充
margin
绝对居中
<style>
.Center {width:100px; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
</style>
<div class="Center">aaa</div>
缺点:必须声明宽度。建议设置overflow:auto来防止内容越界溢出。在Windows Phone设备上不起作用。
使用浮动配合相对定位来进行水平居中
<style>
.parent{width:300px;height:200px;border:1px solid red;}
.wraper{float:left;position:relative;left:50%;clear:both;}
.child{border:1px solid blue;position:relative;left:-50%;white-spave:nowrap;}
</style>
<div class="parent">
<div class="wraper">
<div class="child">aaa</div>
</div>
</div>
这个是浮动元素水平居中的解决方法,且我们不需要知道元素的宽度