我正在尝试使用 CSS 创建响应式布局。
基本上,我需要知道是否可以对元素进行计数,以及当它达到 x 数量时,然后在元素之后添加一个分隔符。
为了更好地解释这一点,我创建了这个 FIDDLE
如您所见,我有一个类名为 .divider
的元素,它位于第 5 个 .beers
元素之后。
如何在每 5 个 .beers
之后显示 .divider
元素?
我希望这是有道理的,并且有人可以帮助我。
提前致谢。
我的 CSS:
.wrapper{
width:100%;
}
.content{
width:960px;
height:500px;
}
.beers{
position: relative;
width: 166px;
display:inline-block;
margin-right: 5px;
height: 107px;
margin-bottom: 20px;
padding-left: 10px;
padding-right: 10px;
text-decoration: none;
border: 1px dotted #e46a10;
}
.divider{
display: block;
border-bottom: 1px dotted #ccc;
margin-bottom: 20px;
}
最佳答案
有一个技巧可以做到这一点,需要巧妙地使用伪元素。您可以将分隔线样式移动到 .beers::after
伪元素中,并针对每个 :nth-child(5n)
类。它看起来像这样:
.beers {
position: relative;
width: 166px;
display:inline-block;
margin-right: 5px;
height: 107px;
margin-bottom: 20px;
padding-left: 10px;
padding-right: 10px;
text-decoration: none;
border: 1px dotted #e46a10;
}
.beers:nth-child(5n)::after {
display: block;
border-bottom: 1px dotted #ccc;
margin-bottom: 20px;
content: "";
}
编辑:仔细检查您的代码后,您的啤酒似乎是内联 block 元素,并且您希望每 5 个分隔一次。因此,虽然这是一个聪明的技巧,但它可能不会给您带来预期的效果。
关于javascript - CSS:计算元素并在 x 数量的元素后自动添加分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38747904/