#CSS 元素水平居中
元素居中的问题我们也会经常遇到,在这里总结一下经常用的几种居中方法。
1:水平居中
div{
width: 200px;
height: 200px;
background-color: red;
margin: 0 auto;
}
运行结果如下:
2:水平垂直居中
实现如下效果,即图片是水平和垂直方向都居中,有三种经常使用的方法:
①:水平垂直居中一
position: absolute;
width: 90px;
height: 80px;
margin:auto;
left:0;
top: 0;
right: 0;
bottom: 0;
这种方法经常使用,也不会出现什么大的问题。
②:利用负边距
position: absolute;
width: 90px;
height: 80px;
top: 50%;
left: 50%;
margin: -40px 0 0 -45px;//margin-top是高度的一半,margin-left是宽度的一半,都是负边距
这种方法兼容性不错,但是需要提前知道此元素的尺寸
③:使用transform
position: absolute;
width: 90px;
height: 80px;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
不需要提前知道元素的尺寸,支持IE 10+以上的浏览器。
以上便是经常用到的用于居中元素的方法。