首页 > 解决方案 > 如何使用来自其父级的 ::after 的通用兄弟选择器

问题描述

我想使用复选框中的状态来显示和隐藏一个 ::after,他是这个的一般兄弟。我正在使用此代码,也许您可​​以帮助我解决这个问题。谢谢。

.form-check label {
  position: relative;
}

.form-check label:after {
  content: " ";
  height: 25px;
  width: 25px;
  display: block;
  position: absolute;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: contain;
  right: -30px;
  top: 0;
  background-color: red;
}

.form-check [type="checkbox"]:checked~ ::after {
  background-color: blue;
}
<div class="form-check">
  <label class="form-check-label" for="example">
			<input class="form-check-input" type="checkbox" value="" id="example">
			<span>Example</span>
			::after
		</label>
</div>

标签: csscss-selectors

解决方案


之后需要有一个元素<input>才能使用这样的伪元素。在这种情况下,你有一个<span>那里。

.form-check [type="checkbox"]:checked  ~  span::after {
    background-color: blue;
}

推荐阅读