有没有一种方法可以让元素在页面中水平居中,边距自动,但如果视口(viewport)变小,左右也有 100px,所以它会像这样一起:
margin: 0 auto;
margin-left:100px;
margin-right:100px;
或者我需要为此有父容器吗?
最佳答案
auto
的问题是你甚至不能将它与 calc(auto + 100px)
一起使用
最好和最准确的方法是使用flex
justify-content
属性将使您的元素像 margin: 0 auto;
一样居中,您仍然可以使用 margin
.parent{
height: 200px;
background: gray;
display:flex;
justify-content:center; /*center element*/
}
.child{
height: 100px;
width: 200px;
background: yellow;
margin: 0 100px; /*adding margin*/
}
<div class='parent'>
<div class="child"></div>
</div>
关于css - 带有额外空间的 auto 边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59653814/