为什么"margin: 0 auto"删除了我div中的白色space?如何让 div 的白色 space 居中?

Why does "margin: 0 auto" delete the white space in my div? How can I center a div with its white space?

我已经在这个问题上坐了很长时间了,不知道该怎么做。

这是我在 Stack Overflow 上的第一个问题,温柔一点,哈哈。

我想做一些非常基本的事情 - 只是将 div(标有红色边框)居中,使其与 header div(也标有红色边框),请参见下面的屏幕截图:

https://i.stack.imgur.com/TvPOF.jpg

如果我给 div 一个“0 auto”的边距,它将删除 div 右侧的白色 space,为什么会这样?结果如下:

https://i.imgur.com/5lOc4Oq.png

我应该如何居中 div,我是不是从错误的角度来处理问题?

相关代码如下:

HTML:

<div class="header-bg">
    <div class="width">
        <div class="width2">
            <p class="header-title"><span class="gold-text">CAN’T HURT ME:</span> MASTER YOUR MIND AND DEFY THE ODDS</p>
            <p class="header-text">Can’t Hurt Me: Master Your Mind and Defy the Odds chronicles David Goggins’ incredible life from perpetual victim to active duty Navy SEAL to world class ultra athlete and world record holder. <a href="http://geni.us/canthurtme" target="_blank">Now available at these fine retailers</a>.<p>
        </div>
                
        <div class="buttons width2">
            <div class="button-1">
                <p>Buy the Book</p>
            </div>
            <div class="button-2">
                <p>About David</p>
        </div>
    </div>
</div>

CSS:

.width {
    max-width: 1000px;
}

.width2 {
    max-width: 500px;
}

.header-bg {
    background: black url('../img/header.jpg') no-repeat center / cover;
    height: 700px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.buttons {
    margin-top: 50px;
    display: inline-flex;
}

您要应用什么元素 margin: 0 auto

我认为您在 div 上的 max-width 是导致您出现问题的原因。添加一个 min-width 或只设置 width - MAX-WIDTH 意味着它可以是从 0px 到 1000px 的任何地方(例如),具体取决于屏幕大小......所以如果你的屏幕只有 400px宽,它将是 400px 宽。如果您的屏幕是 1200 像素,div 将锁定在 1000 像素 - 所以基本上当您应用边距时;边距正在缩小您的框,从而删除白色 space(因为它没有违反 max-width 规则,因为没有设置 min-width 规则)。

TLDR;将那些 div 上的 max-width 更改为 width,您可能会发现它会更好地满足您的需求。