- css实现居中
需要提前知道元素的宽度和高度:width: 600px;height: 400px;
left: 50%;
top: 50%;
margin-top: -200px; /* 高度的一半 */
margin-left: -300px; /* 宽度的一半 */
- css3实现水平垂直居中
此时不需要提前知道元素的宽度和高度.
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* 50%为自身尺寸的一半 */
不过IE8以上才兼容这种写法,移动端可忽略。
- 利用绝对定位元素的自动伸缩的特性
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto; /* 有了这个就自动居中了 */








网友评论