1

I'm using a hack from this answer to make an image to resize on click (the checkbox method). It works fine. However, when I try to also apply a css style on a text on image click, it doesn't work:

<html>
<body>
  <input type="checkbox" id="img-box"/>
  <label for = "img-box">
    <img src="http://www.al-van.org/AV/Manners_files/greeneyedcat.jpg"/>
  </label>

  <p id="some-text">
    some text
  </p>
</body>
</html>


#img-box:checked + label > img  {
    width: 100px;

}

#img-box:checked + p  {
    background-color: red;

}

What is my mistake here and how should I fix it?

The jsfiddle: https://jsfiddle.net/eus18r3h/

parsecer
  • 4,758
  • 13
  • 71
  • 140

2 Answers2

2

The input element with the id "img-box" is not a direct sibling to the p tag. #img-box:checked + p would only style a p tag which is directly next to the input, you have a label in between.

This would be the selector you are looking for '#img-box:checked + label + p'

C. Johnson
  • 211
  • 1
  • 5
  • Thank you! It worked. But what if such an image is at the top of the page and I need to change a background of a text at the very bottom - meaning there may be many other elements in between? Would I need to specify each element in a selector too? – parsecer May 26 '18 at 22:54
  • You can use the general sibling selector which is ~. so it would look like "#img-box:checked ~ p" I only used multiple +'s because i was trying to show you how the + functioned and what you were doing wrong. – C. Johnson May 26 '18 at 23:05
  • Hey thanks for answer, the other answer talked about ~ first, so I had to accept them. But I appreciate your help as well. – parsecer May 26 '18 at 23:08
  • Well you should have asked for a selector with more elements in between. The selector he gave you isn't great because it is going to change the background color on every p element in that container lol. – C. Johnson May 26 '18 at 23:11
  • Your best bet is to probably put a class on the p tag and then use the sibling selector. – C. Johnson May 26 '18 at 23:14
  • 1
    C. Johnson Not every. I use that selector with id # instead of just p. Used p just for the sake of simplicity here. – parsecer May 26 '18 at 23:31
1

You have used the adjacent sibling combinator (+) for your paragraph tag, but it only works if you have one element after another. So since you have the label tag in between, it doesn't work. If you just replace the + with the general sibling combinator ~ the code should work.

#img-box:checked ~ p{
    background-color: red;
}
bluecouch
  • 193
  • 3
  • 12
  • I found it doesn't work if the p is outside the parent tag - if you put an inout with label into a div and the text outside that div, such a selector wouldn't work. Is there any way around it too? – parsecer May 26 '18 at 23:07
  • I am not sure you can do that with CSS. I think you would have to use JS instead. – bluecouch May 26 '18 at 23:21