如何在 CSS 中设置样式和数组对象

cor*_*ord 1 html javascript css

我如何才能在 CSS 中而不是 JS 中获取每个数组并对其进行不同的样式?

count = ['1','2','3','4'];
container = document.getElementById('itemsContainer');
  for(i = 0; i < count.length; i++){
    container.innerHTML+='<div class="items"></div>';
  }

var square= document.getElementsByClassName('items')[2];
square.style.backgroundColor='red';
Run Code Online (Sandbox Code Playgroud)
.items{
  margin-top:10px;
  width:20px;
  height:20px;
  background:gold;
Run Code Online (Sandbox Code Playgroud)
<div id="itemsContainer"></div>
Run Code Online (Sandbox Code Playgroud)

Sco*_*cus 5

使用nth-child()伪类选择器,我们可以区分元素,而无需元素本身有任何唯一标识符。我们甚至不需要数组。

container = document.getElementById('itemsContainer');

for(i = 0; i < 6; i++){
    container.innerHTML+='<div class="items"></div>';
}
Run Code Online (Sandbox Code Playgroud)
.items{
  margin-top:10px;
  width:20px;
  height:20px;
  background:gray;
 }

.items:nth-child(1){ background:gold; }
.items:nth-child(2){ background:green; }
.items:nth-child(3){ background:red; }
.items:nth-child(4){ background:blue; }
Run Code Online (Sandbox Code Playgroud)
<div id="itemsContainer"></div>
Run Code Online (Sandbox Code Playgroud)