首页 > 解决方案 > 跨整行 CSS GRID 的水平边框

问题描述

我需要使用网格布局,但也需要分隔每一行的水平线。

我唯一能找到的是为每个单元格应用边框,但这只有在有足够的单元格来填充每一行时才有效。

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 100px);
}

.box {
  border-bottom: 2px solid #ffa94d;
  padding: 1em;
}
<div class="wrapper">
  <div class="box">One</div>
  <div class="box">Two</div>
  <div class="box">Three</div>
  <div class="box">Four</div>
</div>

有没有办法解决上述问题,使整行都有边框?

标签: htmlcsscss-tablescss-grid

解决方案


添加grid-gap等于边框宽度的a,然后考虑渐变来实现这一点:

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 100px);
  grid-row-gap:2px;
  background:
    repeating-linear-gradient(to bottom,
      transparent 0,
      transparent 100px,
      #ffa94d 100px,
      #ffa94d 102px /*+2px here*/
    );
}

.box {
  padding: 1em;
}
<div class="wrapper">
  <div class="box">One</div>
  <div class="box">Two</div>
  <div class="box">Three</div>
  <div class="box">Four</div>
</div>

另一个想法是考虑添加到第 1、4、7 ..(3n + 1)个元素的伪元素:

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 100px);
  overflow:hidden;
}

.box {
  position:relative;
  padding: 1em;
}
.box:nth-child(3n + 1)::after {
  content:"";
  position:absolute;
  bottom:0px;
  left:0;
  width:100vw;
  height:2px;
  background:#ffa94d;
}
<div class="wrapper">
  <div class="box">One</div>
  <div class="box">Two</div>
  <div class="box">Three</div>
  <div class="box">Four</div>
</div>


推荐阅读