使用CSS-Grid合并不同单元格的边框(边界折叠行为)

时间:2019-03-21 10:40:55

标签: javascript html css css3 css-grid

我发现了许多类似的问题,例如[this](Collapsing borders using CSS Grid),但是我仍然没有找到解决问题的方法。

我希望以下代码段的交叉线对齐。换句话说,我想得到(b),而不是(a)

     |
   --'          |
      .--     --+--
      |         |

    (a)        (b)

.grid  {
  display: grid;
  grid-gap: 0;
  grid-template-columns: 1fr 1fr;
}

.tl { 
   grid-column: 1; 
   grid-row: 1;  
   border-bottom: 5px solid black;
   border-right: 5px solid black;
}
.br { 
   grid-column: 2; 
   grid-row: 2;  
   border-top: 5px solid black;
   border-left: 5px solid black;
}
<div class="grid">
  <div class="tl">&nbsp;</div>
  <div class="br">&nbsp;</div>
</div>

2 个答案:

答案 0 :(得分:3)

您可以考虑采用阴影阴影对其进行近似。边框的一半带有ouset阴影,另一半则带有inset阴影。

.grid  {
  display: grid;
  grid-gap: 0;
  grid-template-columns: 1fr 1fr;
}

.tl { 
   grid-column: 1; 
   grid-row: 1;
   padding: 0 2px 2px 0;
   box-shadow:
    0px 2px black,
    2px 0px black,
    2px 2px black,
    -2px -2px black inset;
}
.br { 
   grid-column: 2; 
   grid-row: 2;  
   padding: 2px 0 0 2px;
   box-shadow:
    0px -2px black,
    -2px 0px black,
    -2px -2px black,
    2px 2px black inset;
}
<div class="grid">
  <div class="tl">&nbsp;</div>
  <div class="br">&nbsp;</div>
</div>

如果网格结构像您所拥有的那样简单,则可以在主容器上应用背景:

.grid  {
  display: grid;
  grid-gap: 0;
  grid-template-columns: 1fr 1fr;
  background:
    linear-gradient(#000,#000) center/100% 4px,
    linear-gradient(#000,#000) center/4px 100%;
  grid-gap:4px;
  background-repeat:no-repeat;
}

.tl { 
   grid-column: 1; 
   grid-row: 1;
}
.br { 
   grid-column: 2; 
   grid-row: 2;  
}
<div class="grid">
  <div class="tl">&nbsp;</div>
  <div class="br">&nbsp;</div>
</div>

它也可以用于复杂的网格,但是您需要找到正确的值:

.grid  {
  display: grid;
  grid-gap: 0;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 1fr;
  background:
    linear-gradient(#000,#000) 0 calc(100%/3)/50% 4px,
    linear-gradient(#000,#000) 100% calc(2*100%/3)/50% 4px,
    linear-gradient(#000,#000) center top/4px 100%;
  grid-gap:4px;
  background-repeat:no-repeat;
}
.grid > * {
  background:pink;
  min-height:50px;
}

.tl { 
   grid-column: 1; 
   grid-row: 1;
}
.br { 
   grid-column: 2; 
   grid-row: 2;  
}
.x { 
   grid-column: 1; 
   grid-row: 2/4;  
}
.y { 
   grid-column: 2; 
   grid-row: 3/4;  
}
<div class="grid">
  <div class="tl"></div>
  <div class="br"></div>
  <div class="x"></div>
  <div class="y"></div>
</div>

答案 1 :(得分:1)

一个简单的解决方法是在br上使用负边距-请参见下面的演示

.grid  {
  display: grid;
  grid-gap: 0;
  grid-template-columns: 1fr 1fr;
}

.tl { 
   grid-column: 1; 
   grid-row: 1;  
   border-bottom: 5px solid black;
   border-right: 5px solid black;
}
.br { 
   grid-column: 2; 
   grid-row: 2;  
   border-top: 5px solid black;
   border-left: 5px solid black;
   margin-left: -5px; /* added */
   margin-top: -5px; /* added */
}
<div class="grid">
  <div class="tl">&nbsp;</div>
  <div class="br">&nbsp;</div>
</div>