0

I want to use the state from a checkbox to show and hide a ::after who is a general sibling from this. I'm using this code, maybe you can help me with this issue. thanks.

.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>
David Thomas
  • 249,100
  • 51
  • 377
  • 410

2 Answers2

0

There needs to be an element after the <input> in order to use a pseudo-element like that. In this case you've got a <span> there.

.form-check [type="checkbox"]:checked  ~  span::after {
    background-color: blue;
}
Kravimir
  • 691
  • 1
  • 6
  • 7
0

The problem is that you're missing the essential properties – the content, height, width and display – from the CSS; if you add those then the posted code works:

.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 {
  /* forces the creation of the pseudo-element, without content
     it effectively doesn't exist: */
  content: '';
  /* because an empty string doesn't have any height, or width, by
     default we need to assign arbitrary non-zero values: */
  height: 1em;
  width: 1em;
  /* the ::before and ::after pseudo-elements are 'display: inline'
     by default, so to enable the element to accept its assigned width
     we make it 'display: inline-block' instead (though other values
     could be used if preferred): */
  display: inline-block;
  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>
  </label>
</div>

It's worth noting that the supplied selector:

.form-check [type="checkbox"]:checked ~ ::after

will select all ::after pseudo elements that follow the checked check-box; you may wish to modify the selector to reduce the likelihood of accidental matches, to:

.form-check [type="checkbox"]:checked ~ span::after

Which will match all ::after pseudo-elements of <span> elements, or to:

.form-check [type="checkbox"]:checked + span::after

to match only the ::after pseudo-element of the adjacent <span> element.

References:

Bibliography:

David Thomas
  • 249,100
  • 51
  • 377
  • 410