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

页面第二个Block内添加自适应高度垂直中线的实现问题

实现Block内部高度同步的垂直中线

页面包含3个Block,需求是在第二个Block的中间添加一条垂直中线,要求中线高度与Block高度完全一致,且Block高度变化时中线高度自动同步。当前代码里的中线高度绑定了页面高度,且未正确以第二个Block为参照容器。

修改后的代码

CSS

.block1 {
  height: 200px;
  background-color: gray;
}

.block2 {
  height: 600px;
  /* 关键:设置相对定位,让内部绝对定位元素以该Block为参照 */
  position: relative;
}

.text {
  text-align: center;
  padding-top: 30px;
}

.block2 .scroll-line {
  position: absolute;
  top: 0; /* 从Block顶部开始 */
  left: 50%;
  transform: translateX(-50%); /* 仅水平居中 */
  height: 100%; /* 高度与Block一致 */
  border: 1px solid transparent;
  background: linear-gradient(#fff, #fff) padding-box,
              linear-gradient(45deg, red, orange) border-box;
}

.block3 {
  height: 200px;
  background-color: gray;
}

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" integrity="sha512-t4GWSVZO1eC8BM339Xd7Uphw5s17a86tIZIj8qRxhnKub6WoyhnrxeCIMeAqBPgdZGlCcG2PrZjMc+Wr78+5Xg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div class="block1"></div>

<div class="block2">
  <div class="row">
    <div class="col-6 text">Text</div>
    <div class="col-6 text">Text</div>
  </div>
  <div class="scroll-line"></div>
</div>

<div class="block3"></div>

核心修改说明

  • 给.block2添加position: relative:让内部的绝对定位元素.scroll-line以该Block为定位容器,而非整个页面
  • 调整.scroll-line的top值为0,简化transform为仅水平居中:确保中线从Block顶部延伸到底部,设置height: 100%后,会自动匹配Block的高度,当Block高度变化时,中线高度同步更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:33:23