如何在CSS中结合使用图像不透明度和nth-child或nth-of-type?

时间:2018-11-09 15:34:54

标签: css image css-selectors opacity

I posted this question yesterday and was referred to some other answers.

这些答案帮助我以所需的不透明度显示了图像,这很好,但是问题是我要显示的下一个图像没有被选择(我想打一次鼓,第二次要打电吉他)行):

enter image description here

.concert .details .bg-image:nth-of-type(8n+1) {
  position: absolute;
  z-index: -1;
  top: 0;
  right: 0;
  bottom: 0;
  background: url(drums.png) 66% 33%;
  opacity: 0.2;
  width: 33%;
  height: 100%;
}

.concert .details .bg-image:nth-of-type(8n+2) {
  position: absolute;
  z-index: -1;
  top: 0;
  right: 0;
  bottom: 0;
  background: url(electricguitar.png) 66% 33;
  opacity: 0.2;
  width: 33%;
  height: 100%;
}
<div class="concerts">
  {% for concert in concerts %}
  <div class="concert">
    <div class="date">
      <span class="day">{{ concert.date.day }}</span>
      <span class="month">{{ concert.date|date:'F' }}</span>
      <span class="year">{{ concert.date.year }}</span>
    </div>
    <div class="details">
      <div class="bg-image"></div>
      <span class="headliner">{{ concert.headliner }}</span>
      <span class="support">{{ concert.support }}</span>
      <span class="price">{{ concert.price }}</span>
      <span class="notes"> {{ concert.notes }}</span>
      <span class="concert_website">
                <a href="{{ concert.website }}" target="_blank">
                  Event Website &#9835;
                </a>
              </span>
    </div>
    <div class="venue">
      <span class="venue_name">
                <a href="{% url 'concerts:venue_events' slug=concert.venue.slug %}">
                  {{ concert.venue.name }}
                </a>
              </span>
      <span class="address">{{ concert.venue.address }}</span>
      <span class="venue_website">
                <a href="{{ concert.venue.website }}" target="_blank">
                  Venue Website &#9833;
                </a>
              </span>
    </div>
  </div>
  {% endfor %}
</div>

为什么电吉他图像未显示在第二行中?我确定它与我的nth-type选择器有关,并且我尝试了我能想到的nth-of-type和nth-child的每个排列,但是很显然,我不了解。我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您需要将第n种类型用于演唱会(bg-image始终是details div的第一个子项):

/* you can cut down your css by adding all shared styles to one class*/

.concert .details .bg-image {
  position: absolute;
  z-index: -1;
  top: 0;
  right: 0;
  bottom: 0;
  opacity: 0.2;
  width: 33%;
  height: 100%;
}

/* then you just change your backgrounds */
.concert:nth-of-type(8n+1) .details .bg-image {
  background: url(drums.png) 66% 33%;
}

.concert:nth-of-type(8n+2) .details .bg-image {
  background: url(electricguitar.png) 66% 33%;
}