CSS网格: lines with labels

标签 css css-grid

我正在使用 css-grid 构建纯 css 图表。有没有办法用文本标记网格线?在附图中,我想标记垂直线:1、2、3、4。

Codepen

grid-template-columns: 150px repeat(12, 1fr);

enter image description here

最佳答案

您可以使用 :after 伪元素为每行添加数字,并且可以使用 css 计数器根据第一行中的元素数量为每列增加数字。

您可以通过在 counter-reset 上定义第二个参数(即数字)来从 1 而不是 0 开始计数器。

.grid {
  display: inline-grid;
  position: relative;
  counter-reset: columnLines 1 rowLines 1;
  grid-template-rows: repeat(3, 100px);
  border: 1px solid black;
  margin: 25px;
}

.row {
  display: grid;
  position: relative;
  grid-template-columns: repeat(3, 100px);
  counter-increment: rowLines;
}

.row:not(:last-child) {
  border-bottom: 1px solid black;
}

.row > div:not(:last-child) {
  border-right: 1px solid black;
}

/*Column lines*/
.row:first-child:before {
  content: "1";
  transform: translate(-50%, -100%);
  position: absolute;
  top: 0;
  left: 0;
}

.row:first-child > div {
  counter-increment: columnLines;
  position: relative;
}

.row:first-child > div:after{
  transform: translate(50%, -100%);
  content: counter(columnLines);
  position: absolute;
  top: 0;
  right: 0;
}

/*Row lines*/
.row:after {
  transform: translate(100%, 50%);
  content: counter(rowLines);
  position: absolute;
  bottom: 0;
  right: -5px;
}

.grid:before {
  transform: translate(100%, -50%);
  position: absolute;
  right: -5px;
  content: "1";
  top: 0;
}
<div class="grid">
  <div class="row">
    <div></div>
    <div></div>
    <div></div>
  </div>
  <div class="row">
    <div></div>
    <div></div>
    <div></div>
  </div>
  <div class="row">
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>

关于CSS网格: lines with labels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57044794/

相关文章:

javascript - 连续添加文本时,垂直滚动条如何保持在底部?

html - 制作 float 元素 "maximally wide"

html - CSS定位与不同顺序的div的flex

html - 将页脚保持在正文底部,但保持在同一列中

html - 如何在CSS网格中偏移一个div

html - 垂直对齐 html 引导行中的文本

html - 如何在CSS中制作渐变线

带 spritesheet 的 CSS 动画

javascript - CSS 网格布局 - 如何使用 javascript 计算出鼠标所在的网格单元格?

CSS - 在屏幕上移动网格元素调整大小