如何在嵌套div上设置上边距?

时间:2015-12-09 12:41:04

标签: html css

我正在尝试嵌套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>

enter image description here

3 个答案:

答案 0 :(得分:1)

display: inline-block添加到.header会使其回绕.title,而保证金将相对于父div。

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

答案 1 :(得分:0)

你可以尝试这个:

.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

答案 2 :(得分:0)

尝试在您的风格中添加此内容可能会对您有所帮助

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