Home > Net >  Css tilda doesn't work if using id and class
Css tilda doesn't work if using id and class

Time:06-21

#header__menu~.header__button {
  background-color: red;
}
<div >
  <div >
    <div ></div>
    <div ></div>
    <div ></div>
  </div>
  <input type="checkbox" name="" id="header__menu">
</div>

this code just doesn't work. I have no idea why. I spent like 30 minutes trying to fix it, but I have literally no idea why. screenshot

CodePudding user response:

The tilde is a General Sibling Combinator which means it works on siblings, not parents and children. Specifically, it works on siblings B that comes after sibling A and has the same parent, where you have A ~ B. So, in your code, if you have

.header__button-1 ~ .header__button-2 {
  background-color: red;
}

then .header__button-2 would have a red background. But if you did

.header__button-3 ~ .header__button-2 {
  background-color: green
}

there wouldn't be anything that really happens. There is no header__button-2 that comes after a .header__button-3.

CodePudding user response:

Related selectors behave similar to neighboring selectors, but unlike the, style rules apply to all nearby elements.

.header__button-1 ~ div {
    background-color: red;
}
  • Related