css - 关于居中的3个问题
本文介绍了css - 关于居中的3个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
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>
<div class="Center-Container">
<div class="Absolute-Center">居中
</div>
</div>
</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>
<div class="Center-Container">
<div class="Absolute-Center">居中
</div>
</div>
</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>
<div class="Center-Container">
<div class="Absolute-Center">居中
</div>
</div>
</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>
<div class="Center-Container">
<div class="Absolute-Center">居中
</div>
</div>
</body>
</html>
解决方案
绝对定位元素有一个高级特性就是其具有自动伸缩功能,当把width
或者是height
设置成auto
,绝对定位元素会根据你设置的 top/bottom/left/right
值进行自动伸缩,也就是说当你设置left:50px;right:70px
,假设你的父元素宽度大于120px
,其绝对定位元素就会自动伸到你所设置的位置。而当我们把高和宽设置成固定值的时候,由于元素无法拉伸,所以就呈现了居中的状态。
详情请见我的博客:CSS position: absolute 绝对定位精讲
这篇关于css - 关于居中的3个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文