首页 > 解决方案 > 治疗

像一个孩子

问题描述

我想做这样的事情:

dt.red {
  color: red;
}

.red~dd {
  border-left: solid red;
}

dt.blue {
  color: blue;
}

.blue~dd {
  border-left: solid blue;
}
<dl>
  <dt class="red">Red</dt>
  <dd>Crimson</dd>
  <dt class="blue">Blue</dt>
  <dd>Azure</dd>
  <dd>Cyan</dd>
  <dt class="red">More red!</dt>
  <dd>Vermilion</dd>
  <dd>Scarlet</dd>
</dl>

https://www.w3schools.com/code/tryit.asp?filename=GBC5PEYKTOJB但是因为蓝色规则排在第二位,所以 <dd>后面class="blue都是蓝色的。

如果只有一个,我可以使用.red + dd,但通常不止一个。我可以将每个段包装在一个<div class="color">中,我可能最终会这样做。

但是有没有别的办法?让每个后续的都覆盖过去的东西?

标签: htmlcsscss-selectors

解决方案


工作示例

.red {
    color: red;
}

.blue {
    color: blue;
}

dt, dd {
  padding: 5px;
}

.red ~ dd,
.red ~ .blue ~ .red ~ dd,
.red ~ .blue ~ .red ~ .blue ~ .red ~ dd {
    border-left: 3px solid red;
}

.blue ~ dd,
.blue ~ .red ~ .blue ~ dd,
.blue ~ .red ~ .blue ~ .red ~ .blue  ~ dd {
    border-left: 3px solid blue;
}
<dl>
  <dt class="red">Red</dt>
  <dd>after red</dd>
  <dd>Red also</dd>

  <dt class="blue">Blue</dt>
  <dd>after blue</dd>
  <dd>should be blue</dd>

  <dt class="blue">Blue</dt>
  <dd>should be blue</dd>
  <dd>should be blue</dd>

  <dt class="red">Red</dt>
  <dd>should be red</dd>
  <dd>should be red</dd>


  <dt class="blue">Blue</dt>
  <dd>should be blue</dd>
  <dd>should be blue</dd>


  <dt class="blue">Blue</dt>
  <dd>should be blue</dd>
  <dd>should be blue</dd>


  <dt class="red">Red</dt>
  <dd>should be red</dd>
  <dd>should be red</dd>

  <dt class="red">Red</dt>
  <dd>should be red</dd>
  <dd>should be red</dd>

  <dt class="red">Red</dt>
  <dd>should be red</dd>
  <dd>should be red</dd>


  <dt class="blue">Blue</dt>
  <dd>should be blue</dd>
  <dd>should be blue</dd>

  <dt class="blue">Blue</dt>
  <dd>should be blue</dd>
  <dd>should be blue</dd>
</dl>


推荐阅读