cssjss

Can't change BG color of div if it has a certain img title


I'm trying to highlight a patent div if a nested, child div contains an image with a specific title.

I've semi-successfully used class selector, but it only adds a border around the image vs changing the bg color of the parent/container div.

What specifically do I need to put in my css to accomplish my goal?

Class selector code:

[title~="THIS"] {
  border: 2px solid red;
}
  <div class="mom">
    <b class="titlecenter">mom title</b>
  </div>

  <div class="pics">
    <a href="link.html">
      <p class="center"><img src="img.gif" title="yup!"></p>
    </a>    
  </div>
</div>

Class selector code used above


Solution

  • You can use the :has selector which is supported by all major browsers.
    https://developer.mozilla.org/en-US/docs/Web/CSS/:has

    .pics:has(img[title~="yup!"]) {
      background-color: red;
    }
        <div class="pics">
                    <a href="link.html">
                <p class="center"><img src="img.gif" title="yup!"></p>
            </a>    
        </div>
        
            <div class="pics">
                    <a href="link.html">
                <p class="center"><img src="img.gif" title="nope!"></p>
            </a>    
        </div>