margin:0 auto;可以水平居中。
1。为何这里的margin:0 auto;失效了?
<html>
<meta charset="utf8">
<style>
.Center-Container {
width: 300px;
height:300px;
border:1px solid red;
position:relative;
}
.Absolute-Center {
width: 50%;
height: 50%;
margin: 0 auto;
border:1px solid red;
position:absolute;
}
</style>
<body>
<p class="Center-Container">
<p class="Absolute-Center">居中
</p>
</p>
</body>
</html>
效果如下

去掉position就没有问题。
<html>
<meta charset="utf8">
<style>
.Center-Container {
width: 300px;
height:300px;
border:1px solid red;
}
.Absolute-Center {
width: 50%;
height: 50%;
margin: auto;
top:0;
right:0;
bottom:0;
left:0;
border:1px solid red;
}
</style>
<body>
<p class="Center-Container">
<p class="Absolute-Center">居中
</p>
</p>
</body>
</html>
效果如下
2。为何top/right/bottom/left:0;margin:0 auto; 产生水平垂直居中了?
我看了文献,https://segmentfault.com/a/11...
讲了一堆,也没有看懂。
<html>
<meta charset="utf8">
<style>
.Center-Container {
width: 300px;
height:300px;
border:1px solid red;
position:relative;
}
.Absolute-Center {
width: 50%;
height: 50%;
margin: 0 auto;
top:0;
right:0;
bottom:0;
left:0;
border:1px solid red;
position:absolute;
}
</style>
<body>
<p class="Center-Container">
<p class="Absolute-Center">居中
</p>
</p>
</body>
</html>

3。为何何top/right/bottom/left:0;margin:auto;就垂直居中了?
我看了文献,https://segmentfault.com/a/11...
讲了一堆,也没有看懂。
<html>
<meta charset="utf8">
<style>
.Center-Container {
width: 300px;
height:300px;
border:1px solid red;
position:relative;
}
.Absolute-Center {
width: 50%;
height: 50%;
margin: auto;
top:0;
right:0;
bottom:0;
left:0;
border:1px solid red;
position:absolute;
}
</style>
<body>
<p class="Center-Container">
<p class="Absolute-Center">居中
</p>
</p>
</body>
</html>

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
绝对定位元素有一个高级特性就是其具有自动伸缩功能,当把
width或者是height设置成auto,绝对定位元素会根据你设置的top/bottom/left/right值进行自动伸缩,也就是说当你设置left:50px;right:70px,假设你的父元素宽度大于120px,其绝对定位元素就会自动伸到你所设置的位置。而当我们把高和宽设置成固定值的时候,由于元素无法拉伸,所以就呈现了居中的状态。详情请见我的博客:CSS position: absolute 绝对定位精讲
使用绝对或者固定定位,margin的居中都会失效的,因为定位之后就不在文档流中了
我认为这是水平垂直居中里面最简单的方法,还有其他许多方法,去http://blog.sina.com.cn/s/blo...博客有
.Center-Container {