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

如何调整三层垂直对齐容器内的文本间距?

问题:缩小两个h2标签之间的间距

我通过三层div实现了元素的垂直居中,页面里包含1个h1和2个h2文本,都放在同一个容器内,但Header 1、Header 2-1和Header 2-2之间存在较大间距,尤其是两个h2之间的间距,尝试多种方法都无法缩小,需要解决这个问题。

原代码

CSS代码

.texts {
  -webkit-text-stroke: 1px white;
  font-family: sans-serif;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
}

#h1landing {
  font-size: 4em;
  animation: fading 3s forwards;
}

.outertexts {
  display: table;
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

.innertexts {
  display: table-cell;
  vertical-align: middle;
}

#h2 {
  animation: introThis 6s forwards;
  font-size: 2em;
}

#h2v2 {
  font-size: 2em;
  animation: introAwaits 9s forwards;
}

.h2 {
  margin-top: 0px;
}

@keyframes introThis {
  0% {
    opacity: 0%;
  }
  50% {
    opacity: 0%;
  }
  65% {
    opacity: 100%;
    transform: translateY(0px)
  }
  70% {
    animation-delay: 5s;
    transform: translateY(0px)
  }
  100% {
    transform: translateY(-150px)
  }
}

@keyframes introAwaits {
  0% {
    animation-delay: 5s;
    opacity: 0%;
  }
  60% {
    opacity: 0%
  }
  75% {
    opacity: 100%;
    transform: translateY(0px)
  }
  80% {
    animation-delay: 5s;
    transform: translateY(0px)
  }
  100% {
    transform: translateY(-100px)
  }
}

@keyframes fading {
  0% {
    opacity: 0%;
    transform: translateX(80%);
  }
  50% {
    opacity: 100%;
    transform: translateX(0);
  }
  75% {
    transform: translateY(0px);
    animation-delay: 10s
  }
  100% {
    transform: translateY(-200px)
  }
}

HTML代码

<div class="outertexts">
  <div class="innertexts">
    <div class="texts">
      <h1 id="h1landing">
        Header 1
      </h1>
      <div class="h2">
        <h2 id="h2">
          Header 2-1
        </h2>
        <h2 id="h2v2">
          Header 2-2
        </h2>
      </div>
    </div>
  </div>
</div>

解决方案

问题出在浏览器的默认样式上:所有标题标签(h1-h6)都自带默认的margin值,这就是导致间距过大的原因。你只需要针对性地重置h2的margin即可缩小间距,具体有两种方式:

方式1:直接给两个h2标签设置margin

在CSS中添加或修改以下样式:

#h2, #h2v2 {
  margin-top: 0;
  margin-bottom: 0.5em; /* 可根据需求调整这个值,控制h2之间的间距 */
}

方式2:给.h2容器内的所有h2统一设置样式

如果后续可能添加更多h2,这种方式更高效:

.h2 h2 {
  margin-top: 0;
  margin-bottom: 0.5em;
}

另外,如果需要缩小h1和第一个h2之间的间距,也可以给#h1landing设置margin-bottom,比如:

#h1landing {
  font-size: 4em;
  animation: fading 3s forwards;
  margin-bottom: 0.8em; /* 调整这个值控制h1和h2的间距 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:35:11