我有两个 div,一个在另一个里面。我已经为两个 div 设置了一些边框,并且我希望两个 div 在水平和垂直方向上都位于页面的中心。我已经看到类似问题的解决方案,但无法解决我的问题。也请分享我可以从中了解定位的好资源,即相对绝对深度。
下面是我的 HTML 代码:
<!DOCTYPE html>
<style type="text/css">
.outer {
color:black;
width: 400px;
height:400px;
border: 100px solid;
border-radius:100%;
border-color: red blue green yellow;
position: static;
margin: auto auto auto auto;
top:50%;
}
.inner{
color:black;
width: 100px;
height:100px;
border: 50px solid;
border-radius:100%;
border-color: red transparent green transparent;
position: relative;
top:50%;
margin: -50px auto auto auto;
}
</style>
<html>
<body>
<div class="outer">
<div class="inner">
</div>
</div>
</body>
</html>
最佳答案
如果您知道两个框的大小,并且它们不会改变,您可以使用这个:
.outer {
color:black;
width: 400px;
height:400px;
border: 10px solid;
border-color: red blue green yellow;
position: absolute;
margin: -200px auto auto -200px;
top:50%;
left: 50%;
}
.inner{
color:black;
width: 100px;
height:100px;
border: 5px solid;
border-color: red transparent green transparent;
position: absolute;
top:50%;
left: 50%;
margin: -50px auto auto -50px;
}
注意我去掉了边框半径,缩小了边框尺寸,让点更清晰。
基本上,您可以使用相对单位 (%) 的绝对定位,但使用固定的负边距,即框大小的一半。
关于css - div 在垂直和水平方向上居中对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11208690/