1

I have the following HTML and CSS selector chain:

<div className="form-group">
    <div class="control-custom-checkbox position-relative">
        <input type="checkbox" class="custom-input" id="check1" checked>
        <label className="custom-label" htmlFor="check1"></label>
    </div> 
</div>
.control-custom-checkbox .custom-input:checked~.custom-label::after { }

Next I added another div into the HTML:

<div class="form-group">
    <div class="control-custom-checkbox position-relative">
       <div class="required">
          <input type="checkbox" class="custom-input" id="check1" checked>
       </div> 
       <label class="custom-label" htmlFor="check1"></label>   
    </div>
</div>

I wrapped the markup in a new <div class="required"> and my styles broke. How should I change my CSS selector?

ChrisM
  • 1,565
  • 14
  • 24
Mikhail Kostiuchenko
  • 9,121
  • 4
  • 15
  • 28

2 Answers2

2

To keep it work, how it was before another div, you didn't need to change anything in your selector - it still will work and target needed HTML element.

You can check it there: https://codepen.io/anon/pen/BELXqW

Volodymyr Humeniuk
  • 3,411
  • 9
  • 35
  • 70
1

The problem was your use of the 'sibling selector' in your CSS selector (~).

This requires that your .custom-label element be a sibling (i.e. next to each other within the DOM tree) of the .custom-input element. When you added the extra div it broke that relation (they were no longer 'next to' each other) so it broke your styling. (The fact that the div had the required class is irrelevant).

There aren't one size fits all fixes for this kind of issue but the safest fix would probably be to adjust the HTML so that they continue to be siblings.

<div class="form-group">
      <div class="control-custom-checkbox position-relative">
          <div class="required">
              <input type="checkbox" class="custom-input" id="check1" checked>
              <label class="custom-label" htmlFor="check1"></label>
          </div> 
      </div> 
  </div>

(Or, as suggested in a comment, just add required onto an existing wrapper.)

If, however, that is not a possibility for some reason. You may be able to get away with removing the sibling selector requirement. E.g.

.control-custom-checkbox .custom-label::after {
    /* Your CSS here */
}

Of course that selector may have been put there for a reason and removing it may have unintended side effects, especially if this will affect a large codebase. You will have to judge for yourself if it is safe to remove that sibling selector. I imagine it should be fine if .control-custom-checkbox always contains HTML structured just like your example, but there's no way to be sure without knowing more about the project.

ChrisM
  • 1,565
  • 14
  • 24