【问题标题】:Why does "margin: 0 auto" delete the white space in my div? How can I center a div with its white space?为什么“margin:0 auto”会删除我的div中的空白?如何将 div 与空白居中?
【发布时间】:2020-08-26 16:25:49
【问题描述】:

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

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

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

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

如果我给 div 的边距“0 auto”,它会删除 div 右侧的空白,为什么要这样做?结果如下:

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;
}

【问题讨论】:

  • @Dexterians 太棒了,这行得通!感谢您的回答,最重要的是,您的解释!
  • 嘿@ffrg - 我已将其翻译成答案。如果您满意,请将我的回复标记为答案:)

标签: html css flexbox margin


【解决方案1】:

你在应用margin: 0 auto什么元素?

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

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

【讨论】:

    猜你喜欢
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2012-09-25
    • 2013-12-11
    • 2020-11-11
    • 2010-11-01
    相关资源
    最近更新 更多