为什么边距顶部不起作用,无法将黄色框放下



不介意注释掉的行。我正在试验盒子模型,但似乎无法弄清楚为什么我不能使用边距顶部将黄色盒子放下一点?我可以使用左边距让它向右移动,所以这对我来说似乎很奇怪......谢谢。

我想了解为什么会发生这种情况:)

.largebox {
    width: 800px;
    height: 350px;
    background-color: #00f;
    //padding-left: 50px;
    margin-left: 10px;
    //border: 2px solid black;
}
.box1 {
    width: 250px;
    height: 300px;
    background-color: #ff0;
    //display: inline;
    //float: left;
    //margin-right: 0px;
    margin-left: 50px;
    margin-top: 25px;
 }
    <div class="largebox">
        <div class="box1"></div>
    </div>

这是由于margin collapsing 发生的 - 因此borderpadding父元素或inline内容(任何inline元素)将关闭边距折叠。

请参阅下面的演示:

.largebox {
  width: 800px;
  height: 350px;
  background-color: #00f;
  margin-left: 10px;
  border: 1px solid; /*ADDED THIS*/
}
.box1 {
  width: 250px;
  height: 300px;
  background-color: #ff0;
  margin-left: 50px;
  margin-top: 25px;
}
<div class="largebox">
  <div class="box1"></div>
</div>

box1中使用display:inline-block;

.largebox {
    width: 800px;
    height: 350px;
    background-color: #00f;
    //padding-left: 50px;
    margin-left: 10px;
    //border: 2px solid black;
}
.box1 {
    width: 250px;
    height: 300px;
    background-color: #ff0;
    //display: inline;
    //float: left;
    //margin-right: 0px;
    margin-left: 50px;
    margin-top: 25px;
    display:inline-block;
 }
 
 
<div class="largebox">
        <div class="box1"></div>
    </div>

您可以

尝试在.box1中使用position:absolute;,如下所示:

.box1{
    position:absolute;
}

最新更新