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>
demo:https://jsfiddle.net/skura23/0123wmsg/
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;
}
demo: http://jsfiddle.net/skura23/6xo11zwv/210/
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; /* 要设定宽度 */
}
demo:https://jsfiddle.net/skura23/rk3qfvv2/1/
--------------------------------------------------
后面有其他的方法的话,会继续添加
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>
demo:https://jsfiddle.net/skura23/0123wmsg/
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;
}
demo: http://jsfiddle.net/skura23/6xo11zwv/210/
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; /* 要设定宽度 */
}
demo:https://jsfiddle.net/skura23/rk3qfvv2/1/
--------------------------------------------------
后面有其他的方法的话,会继续添加