html - 像对待 <dt> 的 child 一样对待 <dd>

标签 html css css-selectors

我想做这样的事情:

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"> 中,我可能最终会这样做。

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

最佳答案

工作示例

.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>

关于html - 像对待 <dt> 的 child 一样对待 <dd>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59941878/

相关文章:

html - 是否有可能使任何 CSS 元素表现得像 <pre>

php - Internet Explorer 9 中的意外问题,假设它是由 html/css 引起的

javascript - 如何让 div 以最紧凑的方式垂直对齐?

javascript - 如何在 jQuery 中定义选择一个元素?

css - 在 CSS 选择器中使用空格或大于号 >?

html - div 容器中的表格布局和省略号

html - 显示行内 block

gmail - HTML 电子邮件的内联 CSS 在 Yahoo 和 Gmail 中显示时不断被剥离

html - :nth-child() and :nth-of-type() not working

html - CSS 选择器选择 n 个元素后的第一个元素