在新div中包装元素时,CSS断开(兄弟选择器)

时间:2019-04-08 12:11:14

标签: html css css-selectors

我有以下HTML和CSS选择器链:

<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 { }

接下来,我在HTML中添加了另一个div

<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>

我将标记包裹在新的<div class="required">中,样式变坏了。我应该如何更改CSS选择器?

2 个答案:

答案 0 :(得分:2)

要使其正常工作,就像在另一个div之前一样,您无需更改选择器中的任何内容-它仍然可以工作并定位所需的HTML元素。

您可以在此处检查它:https://codepen.io/anon/pen/BELXqW

答案 1 :(得分: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.