Home > Software engineering >  Question on the relational selectors used on "Checkbox Hack" css trick
Question on the relational selectors used on "Checkbox Hack" css trick

Time:10-22

Recently, I've tried using the "checkbox hack" to be able to do cool styles on an image when clicked instead of hovered. I am a complete beginner and currently, I don't want to touch javascript. I am trying to understand how it works and I am currently having a difficulty understanding why use universal selector on css. I understand from a stackoverflow answer (Difference between universal and descending selector in CSS) that it helps to read from right to left when reading selectors. However how is it not possible to just use the descendant selector instead of using a universal selector (I tried only #box:checked ~ span but it just doesn't work)?

#box:checked ~ * span{
  font-weight: bolder;
}
<input type="checkbox" id="box">
<label  for="box">
  <span>Lorem Ipsum</span>
</label>

CodePudding user response:

Yes. It's possible to use a descendant selector. It's just about using the selectors in the correct way by taking care of CSS Specificity rules. You can read more about CSS specificity on the web.

Also, I suggest looking over the symbols used in CSS because there may be another way also to do the same.

Look over the code snippet below without the use of a universal selector.

#box:checked ~ .label-box span {
  font-weight: bolder;
}
<input type="checkbox" id="box">
<label  for="box">
  <span>Lorem Ipsum</span>
</label>

  • Related