1

I am trying to display or hide a paragraph in a html page. The html code is:

<input type="checkbox" id="show"> Show/Hide
<p id="toggle">Lorem ipsum dolor sit amet</p>
</div>

Then I use CSS3 to hide/show the paragraph:

 #toggle {
 display:none;
 }

#show:checked ~ p {
    display: block;
}

This does work. But if I try:

#toggle {
  display:none;
}

input[type='checkbox']:checked ~ p {
   display: block;
   }

this doesn't work anymore. I can't understand why. Is there any error in this selector?

  input[type='checkbox']:checked

Thanks for helping!!!

  • 1
    specificity issue ... use this instead `#show:checked ~ p#toggle` .. ID selector is more specific so the checked style never apply – Temani Afif Mar 14 '18 at 08:22
  • https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/ – CBroe Mar 14 '18 at 08:22
  • Possible duplicate of [How element selector is more specific than id selector?](https://stackoverflow.com/questions/9311165/how-element-selector-is-more-specific-than-id-selector) – Temani Afif Mar 14 '18 at 08:25
  • https://stackoverflow.com/questions/1637343/what-are-the-priorities-among-css-selectors – Temani Afif Mar 14 '18 at 08:26

1 Answers1

0

This has to do with the CSS specificity.
When looking at the specificity hierarchy , you'll see that id will go above the element.

That means that
#toggle is more specific then:
input[type='checkbox']:checked ~ p
and therefor will the id overrule the element selector.

So, use:

#toggle {
  display: none;
}

input[type='checkbox']:checked ~ p#toggle {
  display: block;
}
<div>
  <input type="checkbox" id="show"> Show/Hide
  <p id="toggle">Lorem ipsum dolor sit amet</p>
</div>

Or:

input[type='checkbox'] ~ p{
  display: none;
}

input[type='checkbox']:checked ~ p {
  display: block;
}
<div>
  <input type="checkbox" id="show"> Show/Hide
  <p id="toggle">Lorem ipsum dolor sit amet</p>
</div>
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
  • 1
    `you'll see that id will go above (pseudo)classes.` ? it's about ID and element selector, pseudo class and classes has nothing to do here. – Temani Afif Mar 14 '18 at 08:37