【问题标题】:Merge border of different cells with CSS-Grid (border-collapse behavior)使用 CSS-Grid 合并不同单元格的边框(边框折叠行为)
【发布时间】:2019-03-21 10:40:55
【问题描述】:
我发现了很多类似的问题,例如 [this] (Collapsing borders using CSS Grid) one,但我仍然没有找到解决问题的方法。
我希望以下 sn-p 的交叉线对齐。换句话说,我想得到(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"> </div>
<div class="br"> </div>
</div>
【问题讨论】:
标签:
javascript
html
css
css-grid
【解决方案1】:
你可以考虑 box-shadow 来近似它。一半边框带有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"> </div>
<div class="br"> </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"> </div>
<div class="br"> </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>
【解决方案2】:
一个简单的解决方法是在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"> </div>
<div class="br"> </div>
</div>