我正在寻找一行中第一个(或不是第一个)元素的CSS选择器。
在下面的图像中,我有12个块,用灰线水平分隔,这条线未显示在每行的第一个元素上,这是预期的结果。
是否可以使用CSS选择每行的第一个元素?
对我来说,使用CSS的其他任何方法都可以,甚至可以使用flex,grid或float。
div{
width: 100px;
height: 70px;
margin: 5px 0;
padding: 5px;
display: inline-block;
}
div:not(:first-child){
border-left: 3px solid #999;
}
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
答案 0 :(得分:2)
您可以考虑使用负的左边距来隐藏此行:
.wrapper > div {
width: 100px;
height: 70px;
margin: 5px 0;
padding: 5px;
display: inline-block;
border-left: 3px solid #999;
margin-left: -3px;
margin-right: 3px; /*to rectify the removed margin*/
}
/*hide the overflow on the parent element*/
.wrapper {
overflow: hidden;
}
<div class="wrapper">
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
<div>This is a block</div>
</div>
答案 1 :(得分:1)
这个问题有点棘手,因为如果您不知道顺序,就无法定位元素。但是,您可以使用负边距和父级的overflow: hidden
属性实现一些技巧。如果可以,那么您可以尝试以下方法:
.wrapper {
overflow: hidden;
}
.inner-wrap {
display: flex;
flex-wrap: wrap;
margin-left: -3px;
}
.box {
padding: 10px;
border-left: 3px solid #999;
flex: 0 0 70px;
height: 100px;
}
<div class="wrapper">
<div class="inner-wrap">
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
<div class="box">random bash</div>
</div>
</div>