CSS居中总结(只列出关键代码)
一、设置text-align:center;
p{ text-align: center; } /*水平居中,适用于文本(<p>、<h1>..)或图片(<img>)*/
二、设置vertical-align:middle
th,td{ vertical-align: middle;} /*垂直居中,适用于表格内容*/
二、设置line-height值等于父容器高度
line-height: height_father; /*容器内文本垂直居中*/
三、利用margin的auto
margin-left:auto;
margin-right:auto;
或
margin:0 auto;
注:设置的是水平居中,且position:fixed状态下这两种方式无效。
在兼容性方面,除非已经声明了 !DOCTYPE,否则使用 margin:auto 在 IE8 以及更早的版本中无效。
四、利用先50%后-50%居中
父容器:
width: xx px;
height: yy px;
position: relative;
子元素:
position: absolute;
left: 50%;
top: 50%;
margin-left: -xx/2 px;
margin-top: -yy/2 px;
或
父容器:
width:xx px;
height:yy px;
position:relative;
子元素:
position:absolute;
left:50%; /*使子元素左上角移到父元素中心*/
top:50%; /*使子元素左上角移到父元素中心*/
transform:translate(-P,-P); /*回退自身大小的50%距离,使子元素中心与父元素中心对齐*/
注:translate(-50%,-50%)比较奇特,其百分比计算是以自己为基准而不是父元素,也适用于没固定大小的内容。
补充:
在position:relative情况下设置left、top…会改变offsetLeft、offsetTop…的值
通过translate(200px,100px)位移不会改变offsetLeft、offsetTop…的值
五、利用绝对定位居中
父容器:
width: xx px;
height: yy px;
position: relative;
子元素:
position: absolute;
margin: auto;
top: 0; right: 0; bottom: 0; left: 0;
overflow: auto; /*防止内容溢出*/
六、相对于视口居中
父容器:
width: xx px;
height: yy px;
position: relative;
子元素:
position: fixed;margin:auto;
top: 0; right: 0; bottom: 0; left: 0;
z-index: 999;
overflow: auto;
七、模块响应式居中
代码示例:
#div1{
width: 60%;
height: 60%;
max-width: 1000px;
min-width: 40px;
margin: auto;
top: 0; right: 0; bottom: 0; left: 0;
overflow: auto;
}
参考资料:http://www.5icool.org/a/201309/a2516.html
参考资料: http://www.5icool.org/a/201309/a2516.html