如何使伪元素跨越空白网格单元?

时间:2019-05-17 19:22:24

标签: css css-grid pseudo-element

我有一个Powerpoint风格的布局,我试图使用display:grid以响应方式进行构建。我正在使用伪元素:before:after在网格单元之间绘制连接线。当有相邻的单元格时,这可以正常工作。但是,有时我想在可能相隔一两行的两个单元格之间划一条线。在所附的示例中,我希望绿线从#2一直延伸到#7。

是否可以使连接的伪元素以不需要对高度进行硬编码的方式跨越间隙?我可能会提出另一种课程(例如.double-height:after { height: <whatever the height of a cell plus margins is> },但如果可能的话,我想避免这种情况。

.grid {
  display: grid;
  grid-template-columns: 45% 10% 45%;
 }
 
.column-0 { grid-column-start: 1; grid-column-end: 2;}
.column-1 { grid-column-start: 3; grid-column-end: 4;}
.row-0 { grid-row-start: 1; grid-row-end: 2;}
.row-1 { grid-row-start: 2; grid-row-end: 3;}
.row-2 { grid-row-start: 3; grid-row-end: 4;}
.row-3 { grid-row-start: 4; grid-row-end: 5;}
.row-4 { grid-row-start: 5; grid-row-end: 6;}
.row-5 { grid-row-start: 6; grid-row-end: 7;}
.row-6 { grid-row-start: 7; grid-row-end: 8;}

.grid > * { 
  padding: 0.25em;
  border: 1px solid #eee;
  margin: 0 0 30px;
  position: relative;
}

.line-down:after {
  content: '';
  position:absolute; 
  top:calc(100% + 5px);
  height: 20px;
  left:50%; 
  width:4px; 
  margin-left:-2px; 
  background:pink; 
  border-radius:2px; 
}
.column-1.row-1:after { background: #00ff00; }
<div class="grid">
  <div class="column-1 row-0 line-down">1</div>
  <div class="column-1 row-1 line-down">2</div>
  <div class="column-0 row-1 line-down">3</div>
  <div class="column-0 row-2 line-down">4</div>
  <div class="column-0 row-3 line-down">5</div>
  <div class="column-0 row-4 line-down">6</div>
  <div class="column-1 row-5 line-down">7</div>
  <div class="column-0 row-5">8</div>
  <div class="column-1 row-6">9</div>
</div>

1 个答案:

答案 0 :(得分:2)

我不确定这是否是您要使用的,因为您尚未完全解释网格的动态性或给定任何其他用例。该解决方案可以是硬编码的,也可以是动态的,因此,我认为至少可以将您引向正确的方向:

使用calc()可以更聪明地使用7 - 2 = 5属性,只要您有某种方式知道数量或行间距(在您的情况下为::after。这样,您可以根据以下数据设置绿线的rowHeight * 2 * rowsGap伪元素高度:rowHeight,请注意乘以2,因为每一行都用伪元素加倍。如果您使用JS来确定应用程序/网站中的rowsGap.grid { display: grid; grid-template-columns: 45% 10% 45%; } .column-0 { grid-column-start: 1; grid-column-end: 2;} .column-1 { grid-column-start: 3; grid-column-end: 4;} .row-0 { grid-row-start: 1; grid-row-end: 2;} .row-1 { grid-row-start: 2; grid-row-end: 3;} .row-2 { grid-row-start: 3; grid-row-end: 4;} .row-3 { grid-row-start: 4; grid-row-end: 5;} .row-4 { grid-row-start: 5; grid-row-end: 6;} .row-5 { grid-row-start: 6; grid-row-end: 7;} .row-6 { grid-row-start: 7; grid-row-end: 8;} .grid > * { padding: 0.25em; border: 1px solid #eee; margin: 0 0 30px; position: relative; } .line-down:after { content: ''; position:absolute; top:calc(100% + 5px); height: 20px; left:50%; width:4px; margin-left:-2px; background:pink; border-radius:2px; } .column-1.row-1:after { background: #00ff00; height: calc(20px * 10); } ,则可以按固定比例确定或动态设置。

这是实际的CSS代码:

.column-1.row-1:after

请注意,更改仅适用于.column-1.row-1:after { background: #00ff00; height: calc(20px * 10); } 规则:

php artisan vendor:publish --tag=laravel-notifications

这是一个有效的js小提琴:https://jsfiddle.net/wa01vz92/2/