无敌居中!!!!

不需要知道宽高:

CSS transform

<div 'style='position:relative;' >

  <div style='position:absolute;top:50%;left:50%; transform: translate(-50%, -50%);'></div>

</div>

 

使用display:table-cell来居中

对于那些不是表格的元素,我们可以通过display:table-cell 来把它模拟成一个表格单元格,这样就可以利用表格那很方便的居中特性了。
<div style='display: table-cell; vertical-align: middle; text-align: center;' >

  <div style='display: inline-block;'></div>

</div>

 

flex布局

<div style='display: flex;justify-content:center;align-items:center;' >

  <div></div>

</div>

 

需要知道宽高:

使用绝对定位来居中(IE6.7无效)

通过把这个绝对定位元素的left或top的属性设为50%,这个时候元素并不是居中的,而是比居中的位置向右或向左偏了这个元素宽度或高度的一半的距离,所以需要使用一个负的margin-left或margin-top的值来把它拉回到居中的位置,这个负的margin值就取元素宽度或高度的一半.
<div style='width:200px;height:200px;position:relative' >

  <div style='width:100px;height:100px;position:absolute; left:50%;top:50%;margin-left:-50px;margin-top:-50px;'></div>

</div>

 

posted @ 2016-12-19 11:40  大猫一只  阅读(123)  评论(0编辑  收藏  举报