代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>定位的盒子居中完美的写法</title>
<style>
.box {
width: 500px;
height: 500px;
background-color: #800080;
color: #fff;
text-align: center;
line-height: 500px;
font-size: 30px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="box">定位的盒子居中完美的写法</div>
</body>
</html>
效果图

网友评论
水平居中:
1.对于inline元素:为父元素设置text-align: center;即可(子元素所有内容都会居中,所以最好在子元素中使用text-align:left;归位)。
2.对于block元素:为元素设置宽度,再设置margin: 0 auto;(IE6还是需要在父元素设置text-align: center;)
3.对于float元素:为元素设置宽度,再设置position:relative;,再设置left:50%;,最后margin-left设置为该元素宽度的一半乘以-1。
.content { height: 30px;background-color: rgb(89, 157, 197); /* 无关紧要的代码 */ float: left; width: 300px; position: relative; left: 50%; margin-left: -150px; }
4.对于position:absolute元素:
法一:为元素设置宽度,再设置left:50%;,最后margin-left设置为该元素宽度的一半乘以-1。
法二:为元素设置宽度,再设置左右偏移为0(left: 0;和right: 0;),最后设置左右外边距为margin: 0 auto;。
垂直居中:
1.对于单行文本垂直居中:设置高度,再设置line-height值等于设置的高度值。
2.父容器高度不知,两种方法:
法一:父容器设置position:relative;,子容器设置position: absolute; top: 50%; transform: translateY(-50%);。
.main { position: relative; width:100%;height: 500px;background-color: rgb(199, 196, 43); /* 无关紧要的代码 */ } .content { background-color: rgb(89, 157, 197); /* 无关紧要的代码 */ position: absolute; top: 50%; transform: translateY(-50%); }
法二:(父容器下只有这个子元素时使用)子容器设置position: relative; top: 50%; transform: translateY(-50%);。
.main { width:100%;height: 500px;background-color: rgb(199, 196, 43); /* 无关紧要的代码 */ } .content { background-color: rgb(89, 157, 197); /* 无关紧要的代码 */ position: relative;top: 50%; transform: translateY(-50%); }
注:transform: translate中的translate是根据自身百分比宽高在X/Y轴上移动。所以如果在子元素使用position: absolute;left:50%; transform:translate(-50%,0);则可以实现水平居中。
▲ 3.flex简单粗暴:
.main{ width: 100%; height: 400px; background-color: aqua; /* 无关紧要的代码 */ display:flex;/*Flex布局*/ display: -webkit-flex; /* Safari */ align-items:center;/*指定垂直居中*/ // justify-content:center; /*指定水平居中*/ } .content { width: 200px;height: 200px;background-color: rgb(89, 157, 197); /* 无关紧要的代码 */ }
【个人笔记,只作分享讨论】