使用CSS而不是Javascript将类添加到父类

时间:2019-01-31 06:41:32

标签: css html5

如果选中此复选框,则在不使用Javascript的情况下将CSS类添加到父类。

这里是尝试的代码:

CSS代码:

span:focus~.to-be-changed {
  color: red;
}

HTML代码:

<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>
<span tabindex="0">Click me!</span>
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>

1 个答案:

答案 0 :(得分:0)

如果您允许更改html标记,则有一种方法。在父容器及其flex属性中使用order,以随机排列子元素。

span:focus~.to-be-changed {
  color: red;
}

div {
  display: flex;
  flex-direction: column;
}

span {
  order: 2;
}
<div>
  <span tabindex="0">Click me!</span>
  <p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>
  <p class="to-be-changed" style="order:3;">I'm going to be red! It's gonna be legen... Wait for it...</p>
</div>