css - 带有额外空间的 auto 边距

标签 css margin centering

有没有一种方法可以让元素在页面中水平居中,边距自动,但如果视口(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/

相关文章:

css - 边距高度占容器的百分比

css - 为什么这些 div 之间有垂直间隙?

css - 如何减少主页画廊上方和下方的空白?

css - 表单输入元素不居中

html - CSS3 : translateX to center element horizontally

html - CSS 转换在 Edge 中不起作用

javascript - 单击 float div 中的链接不起作用

css - 如何从中心的 navbar-nav 反转设置 Bootstrap 菜单项?

javascript - 在选中和取消选中复选框时显示和隐藏 div

jquery - 在具有精确坐标的 Click Canvas 上获取图像数据