You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS中margin-top属性失效问题求助

问题:无法通过margin-top实现两个section的间距

我的HTML网页呈现效果如下:
网页呈现效果

原始网页结构:

<header>
<h1></h1>
</header>
<section>
<article id="article1"></article>
<article id="article2"></article>
</section>
<section>
<article id="article3"></article>
</section>

对应的CSS代码:

body {
  background-color: #ffffcc;
}

header {
  background-color: #6699ff;
  color: #ffffff;
  text-align: center;
}

section {
  width: 700px;
  clear: both;
}

article {
  background-color: #99ffff;
  padding: 10px;
}

h2 {
  background-color: #6699ff;
  color: #ffffff;
}

#article1 {
  float: left;
  width: 320px;
  height: 250px;
}

#article2 {
  float: right;
  width: 320px;
  height: 250px;
}

#article3 {
  width: 680px;
}

我希望让上方包含两篇文章的section和下方的article3所在section分开,于是修改了HTML代码,给下方section添加内联样式:

<header>
<h1></h1>
</header>
<section>
<article id="article1"></article>
<article id="article2"></article>
</section>
<section style="margin-top: 10px">
<article id="article3"></article>
</section>

但修改后没有任何效果,我了解margin塌陷的概念,但这似乎不属于该情况,求解决办法。


解决办法

问题根源是第一个section因为内部子元素浮动,导致自身高度塌陷为0,所以给第二个section设置的margin-top实际上是和header的底部计算间距,而不是和第一个section的底部。

可以通过以下几种方式修复:

方法1:给第一个section触发BFC(块级格式化上下文)

修改CSS中的section样式,添加overflow: hidden:

section {
  width: 700px;
  clear: both;
  overflow: hidden; /* 新增,触发BFC包裹浮动元素 */
}

方法2:添加清除浮动的伪元素

给包含浮动元素的section设置伪元素清除浮动:

section::after {
  content: "";
  display: table;
  clear: both;
}

方法3:给第一个section设置固定高度(不推荐)

如果内容高度固定,可以直接给第一个section设置高度,但这种方式不够灵活,内容变化时需要同步修改高度:

section:first-of-type {
  height: 270px; /* 等于article的高度250px加上上下padding各10px */
}

采用方法1或2后,第一个section会正确包裹住内部的浮动article,此时给第二个section设置的margin-top:10px就能正常生效,实现两个section之间的间距。

内容的提问来源于stack exchange,提问作者Hrutvik Palutla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:56:03