更改没有nth-child(x)的嵌套元素的颜色

时间:2018-12-10 11:40:59

标签: css css-selectors

我正在显示循环解析json文件的结果。我可以使用:nth-​​child(x)更改每个元素的背景颜色。但是,我无法使用此方法更改每个元素内标题的颜色。在这种情况下,我想将h4“ ROADMAP”颜色与卡片颜色进行匹配。

CSS

.displayResult{
  border: 2px solid black;
  border-radius: 10px;
  background-color: orange;
}

.card-title{
  display: flex;
  padding: 1em 1em 0em 1em;
  align-items: center;
  justify-content: space-around;
  margin-bottom: 0px;
}

.details-hidden{
  display: flex;
  padding: 1em;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  margin-top: 0px;
}

.details-hidden h4{
border: 2px solid black;
  border-width: 2px 0px;
  width: 100%;
  text-align: center;
  padding: 1em;
  background-color: black;
  color: orange;
  margin-top: 0px
}

.details-hidden h5{
border: 2px solid black;
  border-width: 2px 0px;
  width: 20%;
  text-align: center;
  padding: 0.8em;
  margin: 0px;
}

ul{
   list-style: none;
  padding: 0;
}

li{
  padding: 0.1em;
}


.displayResult:nth-child(2){
  background-color: #5cd65c;
}

.details-visible{
  display: flex;
  padding: 1em;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
}

HTML

<head><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>

<div class="displayResult">
<div class="card-title">
  <h4>BY TRAIN</h4>
    <p><i class="fa fa-clock-o" style="font-size:15px"></i> <b>02H26</b></p>
  <p><b>$ 210</b></p>
    <p>i</p>
 </div>

  <div class="details-hidden">
    <h4>ROADMAP</h4>
  <h5>TRAIN (02H26)</h5>
  <ul>
    <li>Paris Nord Eurostar</li>
    <li>Paris Nord Eurostar</li>
    <li>Paris Nord Eurostar</li>
     <li><b>MOSCOW<b></li>
   </ul>
    </div>
     <button>*</button>
  </div>


  <div class="displayResult">
<div class="card-title">
  <h4>BY BOAT</h4>
    <p><i class="fa fa-clock-o" style="font-size:15px"></i> <b>10H26</b></p>
  <p><b>$ 210</b></p>
    <p>i</p>
 </div>

  <div class="details-hidden">
    <h4>ROADMAP</h4>
  <h5>BOAT (02H26)</h5>
  <ul>
    <li>boat</li>
     <li><b>MOSCOW<b></li>
   </ul>
    </div>
     <button>*</button>
  </div>

JS

var btn = document.querySelector("button")
var details = document.querySelector(".details-hidden")

btn.onclick = function(){
  details.classList.add("details-visible");
  details.classList.remove("details-hidden");
}

Codepen Link

第一个“路线图”应为绿色,第二个应为橙色,等等。

由于我永远不知道会收到多少结果,因此我无法对新类进行硬编码。我必须更改颜色,这要归功于与nth-child方法类似的东西。

0 个答案:

没有答案