<分区>
标签 css sass css-selectors
<分区>
我需要实现正常的无限列表布局,每个元素周围都有一个边框。我不希望在两个元素的边界相交处出现 2-border look。我试过 a few approaches并由于 :last-child
的行为而卡住,即父元素仅将最后一个元素视为最后一个子元素。
HTML
<div class="parent">
<div class="child">
<span>Has proper border</span>
</div>
<div class="child">
<span>Not proper border</span>
</div>
<p>I introduced border issue</p> <!-- Can't remove this tag -->
</div>
SCSS 和 CSS
span {
display: inline-block;
padding: 10px;
border: 1px solid black;
}
.parent {
margin: 15px 0;
.child {
&:not(:last-child) {
span{ border-bottom-width: 0; }
}
// tried just to make things work. But it doesn't.
&:last-child {
span{ border-bottom-width: 1px; }
}
}
}
// Equivalent CSS -
.parent .child:not(:last-child) span {
border-bottom-wdth: 0;
}
.parent .child:last-child span {
border-bottom-wdth: 1px;
}
最佳答案
我在 CSS(1 和 2)和 SCSS(1)中阅读了一些关于兄弟选择器的文章/问题,并应用了以下选项来实现所需的行为,同时保持相同的 HTML -
<强>1。相邻兄弟选择器(“+”)方法 - Working example
.parent {
/* siblings approach */
margin: 15px 0;
$className: child;
.#{ $className } {
& + .#{ $className } {
span {
border-top-width: 0;
}
}
}
}
// Equivalent CSS -
.parent .child + child span {
border-top-width: 0;
}
<强>2。 ":last-of-type"方法 -
// Same can be achieved using ":first-of-type"
.parent {
/* :last-of-type approach */
margin 15px 0;
span {
border: 1px solid black;
border-bottom-width: 0;
}
.child:last-of-type {
span {
border-bottom-width: 1px;
}
}
}
// Equivalent CSS
.parent .child:last-of-type span {
border-bottom-width: 1px;
}
关于css - 没有双边框或间隙的兄弟元素的边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57767999/