根据计数以不同方式设置具有相同名称的CSS类

时间:2017-03-24 03:43:58

标签: html css css-selectors

给出一系列用户生成的列表,格式如下:

.birds {
  background-color: rgba(0, 0, 255, 1);
}
<div class="animals">
  <div class="elephants">
    elephants
  </div>
  <div class="cats">
    cats
  </div>
  <div class="birds">
    Birds
  </div>
  <div class="elephants">
    elephants
  </div>
  <div class="birds">
    Birds
  </div>
  <div class="birds">
    Birds
  </div>
  <div class="cats">
    cats
  </div>
  <div class="dogs">
    dogs
  </div>
  <div class="birds">
    Birds
  </div>
</div>

有没有办法为每个类“鸟”的每个实例设置样式,以便每个实例都根据有多少类“鸟”获得不同颜色的背景颜色蓝色(例如淡蓝色,中蓝色,深蓝色)在列表中,如果存在更多,会变暗请注意,我只能访问CSS,而不是HTML或Javascript。

2 个答案:

答案 0 :(得分:2)

.birds { color: white; }

.birds                   { background-color: lightblue; }
.birds ~ .birds          { background-color: blue;      }
.birds ~ .birds ~ .birds { background-color: darkblue;  }
<div class="animals">
  <div class="elephants"> elephants </div>
  <div class="cats">      cats      </div>
  <div class="birds">     Birds     </div>
  <div class="elephants"> elephants </div>
  <div class="birds">     Birds     </div>
  <div class="birds">     Birds     </div>
  <div class="cats">      cats      </div>
  <div class="dogs">      dogs      </div>
  <div class="birds">     Birds     </div>
</div>   

答案 1 :(得分:1)

你也可以试试其中一些:

&#13;
&#13;
.animals{
  background: linear-gradient(to bottom, lightblue, blue);
}
.animals > div:not(.birds){
  background: white;
}
&#13;
<div class="animals">
  <div class="elephants"> elephants </div>
  <div class="cats">      cats      </div>
  <div class="birds">     Birds     </div>
  <div class="elephants"> elephants </div>
  <div class="birds">     Birds     </div>
  <div class="birds">     Birds     </div>
  <div class="cats">      cats      </div>
  <div class="dogs">      dogs      </div>
  <div class="birds">     Birds     </div>
</div>
&#13;
&#13;
&#13;