【问题标题】:How to push two <div> blocks closer to each other in HTML? [duplicate]如何在 HTML 中将两个 <div> 块彼此靠近? [复制]
【发布时间】:2021-08-06 12:32:55
【问题描述】:

我编写了以下代码,但是两个 DIV 块之间有一个空格。

<!DOCTYPE html>
<html>
    <body>
        <div style="background:blue; width: 200px; height: 200px">
        <p>123</p>
        </div>

        <div style="background: yellow; width: 200px; height: 200px">
        <p>456</p>
    </div>
    </body>
</html>





我想要两个块之间没有空格的代码。我该怎么做?

【问题讨论】:

  • 浏览器对所有内容都有默认样式。你应该添加一个CSS reset

标签: html css


【解决方案1】:

<html>
    <body style="display:flex; flex-direction: column">
        <div style="background:blue; width: 200px; height: 200px">
        <p>123</p>
        </div>

        <div style="background: yellow; width: 200px; height: 200px">
        <p>456</p>
    </div>
    </body>
</html>

【讨论】:

    【解决方案2】:

    您可以规范化 CSS 并定义 margin: 0:

    * {
      margin: 0;
    }
    <!DOCTYPE html>
    <html>
        <body>
            <div style="background:blue; width: 200px; height: 200px">
            <p>123</p>
            </div>
    
            <div style="background: yellow; width: 200px; height: 200px">
            <p>456</p>
        </div>
        </body>
    </html>

    【讨论】:

    • 成功了。谢谢!
    【解决方案3】:

    由于为p 标签应用了默认边距,因此出现了间隙问题。 * 选择器将针对所有元素。所以最好你可以为p 标签添加类并应用你的样式。

    p.no-margin {
      margin: 0px;
    }
    <div style="background:blue; width: 200px; height: 200px">
      <p class="no-margin">123</p>
    </div>
    
    <div style="background: yellow; width: 200px; height: 200px">
      <p class="no-margin">456</p>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      相关资源
      最近更新 更多