CSS如何居中div??

水平居中:给div设置一个宽度,然后添加 margin:0 auto; 使绝对定位的div居中: div {position:absolute;300px;height:300px;margin:auto;top:0;left:0;bottom:0;right:0; background:ping /* 加颜色方便看效果*/} 水平垂直居中1: 确定容器宽高 设置外边距 div{position:relative/absolute;width:500px;height:500px;top:50%;left:50%;margin:-250px 0;} 水平垂直居中2: 未知容器的宽高,利用transform属性 div{position:relative/absolute;width:500px;height:500px;top:50%;left:50%;transform:translate(-50%,-50 %)} 水平垂直居中3: 利用flex布局,实际使用是考虑兼容: .container {display:flex;align-items:center;justify-content:center;} .container{width:500px;height:500px;}
原文地址:https://www.cnblogs.com/yi-515/p/8761051.html