CSS绝对定位元素居中的几种方法
1,div宽度未知1
<body>
<div style="position: absolute; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
没有宽度<br />
照样居中,嘿嘿嘿
</div>
</div>
</body>
2,div宽度未知2
<div class="outer">
<div class="inner">居中<br/>蓄力中</div>
</div>
.outer {
position: relative; /* or absolute */
/* unnecessary styling properties */
margin: 5%;
width: 80%;
height: 500px;
border: 1px solid red;
}
.inner {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
/* unnecessary styling properties */
max-width: 50%;
text-align: center;
border: 1px solid blue;
}
ps:此方法适合ie8以上的浏览器
3,div宽度已知
<body>
<div>
<div id="content">
居中蓄力中
</div>
</div>
</body>
#content {
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
width: 100px; /* 要设定宽度 */
}
转载自-CSS居中绝对https://www.cnblogs.com/skura23/p/6530556.html
作者:PajamaCat