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

如何使用HTML和CSS在两个div元素之间添加竖直线?

如何在两个
元素之间添加竖直线?

想要使用HTML和CSS实现如图所示的效果:
使用HTML和CSS实现该设计

下面提供两种实用的实现方案:


方案一:使用额外
作为竖线容器

这种方式直观易懂,适合需要对竖线做复杂样式控制的场景,你的示例代码已经采用了这个思路,这里做了小幅优化以兼容标准flex语法:

HTML代码

<div>
  <div class="flex-container mt-3 d-flex justify-content-center align-items-center">
    <div class="column">Karvat group was established in Mumbai.</div>
    <div class="vr"></div>
    <div class="column2 bg-alt box arrow-left ml-15"> 1952</div>
  </div>
</div>

CSS代码

.flex-container {
  display: flex; /* 补充标准flex语法,兼容更多浏览器 */
  display: -webkit-flex;
  margin: 0 auto;
  text-align: center;
  align-items: center; /* 确保内容和竖线垂直居中对齐 */
}

.flex-container .column {
  width: 320px;
  text-align: center;
}

.vr {
  border-left: 2px dotted black; /* 定义虚线竖线样式 */
  width: 2px;
  margin: 0 5px; /* 控制竖线和两侧内容的间距 */
  height: 200px; /* 设置竖线高度 */
}

方案二:利用伪元素实现(无需额外DOM标签)

这种方案更简洁,不需要添加额外的<div>,通过CSS伪元素生成竖线,更符合语义化要求:

HTML代码

<div>
  <div class="flex-container mt-3 d-flex justify-content-center align-items-center">
    <div class="column">Karvat group was established in Mumbai.</div>
    <div class="column2 bg-alt box arrow-left ml-15"> 1952</div>
  </div>
</div>

CSS代码

.flex-container {
  display: flex;
  display: -webkit-flex;
  margin: 0 auto;
  text-align: center;
  align-items: center;
}

.flex-container .column {
  width: 320px;
  text-align: center;
}

.column2 {
  margin-left: 15px;
  position: relative; /* 为伪元素提供定位基准 */
}

.column2::before {
  content: ""; /* 伪元素必须设置content属性 */
  position: absolute;
  left: -10px; /* 调整竖线的水平位置 */
  top: 50%;
  transform: translateY(-50%); /* 让竖线垂直居中 */
  border-left: 2px dotted black;
  height: 200px;
}

两种方案都能实现你需要的效果,可根据实际场景选择:如果需要动态控制竖线的显示/隐藏,方案一更灵活;如果追求DOM结构简洁,方案二更合适。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:25:44