重置CSS:nth-​​of-type计数器

时间:2018-05-21 18:14:55

标签: html css css-selectors

我正在使用WP事件插件,它以下列格式创建事件列表: -

.event-list .event {
    float: left;
    width: 30%;
    margin-left: 0;
    background: #eee;
}

span.month {
  width: 100%;
  border-bottom: solid 1px black;
  display: block;
  clear: both;
}

.event-list div.event:nth-of-type(3n){
margin-left:5%;
}

.event-list div.event:nth-of-type(3n+1){
margin-left: 0;
clear: both;
}

.event-list div.event:nth-of-type(3n+2){
margin-left:5%;
}
<div class="event-list">
<span class="month">January</span>
<div class="event">Event 1</div>
<div class="event">Event 2</div>
<div class="event">Event 3</div>
<div class="event">Event 4</div>
<span class="month">February</span>
<div class="event">Event 5</div>
<div class="event">Event 6</div>
<div class="event">Event 7</div>
<div class="event">Event 8</div>
<div class="event">Event 9</div>
<div class="event">Event 10</div>
</div>

我希望nth-of-type计数器在每个span元素之后重置,这样无论当月的事件数量如何,列都可以工作。我已经尝试过使用波浪号〜选择器(正如Excluding an element from nth-child pattern http://jsfiddle.net/jWxb6/11/所建议的那样),但我不能让我的生活让它发挥作用。如果可以的话,我想不使用JS / JQuery就可以做到,但如果没有纯CSS解决方案,这是一个选项。

2 个答案:

答案 0 :(得分:1)

为什么不考虑更简单的事情来实现这一点。这是和使用flexbox的想法,而不需要使用复杂的选择器,因为您的实际HTML结构将无法实现。

.event-list {
  display: flex;
  flex-wrap:wrap;
  justify-content:space-between;
}

.event-list .event {
  width: 30%;
  margin-left: 0;
  background: #eee;
}

span.month {
  width: 100%;
  border-bottom: solid 1px black;
}
<div class="event-list">
  <span class="month">January</span>
  <div class="event">Event 1</div>
  <div class="event">Event 2</div>
  <div class="event">Event 3</div>
  <div class="event">Event 4</div>
  <span class="month">February</span>
  <div class="event">Event 5</div>
  <div class="event">Event 6</div>
  <div class="event">Event 7</div>
  <div class="event">Event 8</div>
  <div class="event">Event 9</div>
  <div class="event">Event 10</div>
</div>

答案 1 :(得分:-1)

您只需将每个月的事件包装在一个新div中,以便计数器在父级内部重置为1。

.event-list .event {
    float: left;
    width: 30%;
    margin-left: 0;
    background: #eee;
}

span.month {
  width: 100%;
  border-bottom: solid 1px black;
  display: block;
  clear: both;
}

.event-list .month_wrapper div.event:nth-of-type(3n){
margin-left:5%;
}

.event-list .month_wrapper div.event:nth-of-type(3n+1){
margin-left: 0;
clear: both;
}

.event-list .month_wrapper div.event:nth-of-type(3n+2){
margin-left:5%;
}
<div class="event-list">
<div class="month_wrapper">
<span class="month">January</span>
<div class="event">Event 1</div>
<div class="event">Event 2</div>
<div class="event">Event 3</div>
<div class="event">Event 4</div>
</div>
<div class="month_wrapper">
<span class="month">February</span>
<div class="event">Event 5</div>
<div class="event">Event 6</div>
<div class="event">Event 7</div>
<div class="event">Event 8</div>
<div class="event">Event 9</div>
<div class="event">Event 10</div>
</div>
</div>