【问题标题】:How do I set the top margin on a nested div? [duplicate]如何设置嵌套 div 的上边距? [复制]
【发布时间】:2016-03-14 17:48:51
【问题描述】:

我试图嵌套一个 div 标签并设置 margin-top 以便它设置从内部 div 顶部到外部元素顶部的距离。但是,当尝试下面的代码时,嵌套元素的顶部之间没有边距,而是将边距应用于外部元素的顶部。

<style>
  .header {
    width: 100%;
    height: 110px;
    text-align: center;
  }
  .title {
    margin-top: 25px;
    font-size: 30px;
  }
</style>

<div class="header">
  <div class="title">Title</div>
</div>

【问题讨论】:

  • 添加溢出:隐藏;到.header

标签: html css


【解决方案1】:

display: inline-block 添加到.header 将使其环绕.title,并且边距将相对于父div。

.header {
  width: 100%;
  height: 110px;
  text-align: center;
  background-color: yellow;
  display: inline-block;
}
.title {
  margin-top: 25px;
  font-size: 30px;
}
<div class="header">
  <div class="title">Title</div>
</div>

【讨论】:

    【解决方案2】:

    你可以试试这个:

    .header {
        width: 100%;
        height: 110px;
        text-align: center;
         background-color:gray;
         display: inline-block;
         clear:both;
         }
      .title {
        margin-top: 25px;
        font-size: 30px;
    
      }
    

    .header {
        width: 100%;
        height: 110px;
        text-align: center;
         background-color:gray;
         overflow: hidden;
         }
      .title {
        margin-top: 25px;
        font-size: 30px;
    
      }
    

    DEMO

    【讨论】:

      【解决方案3】:

      尝试将其添加到您的风格中可能会对您有所帮助

      <style>
        .header {
          width: 100%;
          height: 110px;
          text-align: center;
          display: table;
           margin: 0 auto;
        }
        .title {
          margin-top: 25px;
          font-size: 30px;
          display: table-cell;
          vertical-align: middle;
        }
      </style>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        • 1970-01-01
        • 1970-01-01
        • 2013-06-12
        • 2011-10-25
        相关资源
        最近更新 更多