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

如何在Grid布局中添加无边框的垂直线?

实现Grid布局中的纯垂直线(无横向边框)

你当前代码里给每个.grid-item设置了border: 1px solid ...,这会给每个网格项添加上下左右四个方向的边框,所以才会出现带横线的框体。要只保留垂直线,推荐两种简单方法:

方法一:给网格项设置左右边框(去除上下边框)

修改.grid-item的边框属性,只保留左右方向的边框,同时处理第一个项的左侧冗余线条:

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 明确列数,让垂直线布局更清晰 */
  color: #fff;
  opacity: .5;
}

.grid-item {
  border-left: 1px solid rgba(0, 0, 0, 0.8); /* 仅添加左边框 */
  padding: 20px;
  font-size: 30px;
}

/* 移除第一个网格项的左边框,避免容器左侧多出线条 */
.grid-item:first-child {
  border-left: none;
}

HTML部分保持不变:

<h1>Grid Elements</h1>
<p>A Grid Layout must have a parent element with the <em>display</em> property set to <em>grid</em> or <em>inline-grid</em>.</p>
<p>Direct child element(s) of the grid container automatically becomes grid items.</p>
<div class="grid-container">
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
</div>

方法二:通过Grid容器伪元素绘制垂直线

这种方法不需要修改网格项的边框,直接在容器层面生成垂直线,布局更灵活:

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  column-gap: 0; /* 清除默认列间距,避免线条错位 */
  color: #fff;
  opacity: .5;
  position: relative; /* 为伪元素定位提供基准 */
}

.grid-item {
  padding: 20px;
  font-size: 30px;
}

/* 生成列之间的垂直线 */
.grid-container::before,
.grid-container::after {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  width: 1px;
  background-color: rgba(0, 0, 0, 0.8);
}

/* 第一条垂直线:第一列与第二列之间 */
.grid-container::before {
  left: 33.333%;
}

/* 第二条垂直线:第二列与第三列之间 */
.grid-container::after {
  left: 66.666%;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:20:43