Tidying up my CSS (selector help)

I have W3 selector reference open most of the time but I can’t seem to figure this out.

Have a look at my HTML/CSS

Below I have some CSS I want to tidy up. What is the correct selector for:

  1. Selecting everything inside a specific div, in this case .container2.
  2. Selecting say an img element only within a specific div? I can only seem to see selectors for children that comes after a generic element i.e div > img or div img.

I just seem to have loads of classes/ids and it all feels very messy and I’m creating a new CSS{} for each little change.

.container2, #blue, #yellow, 
#pink, #image1, #image2, 
#image3, span {
  background-color: #A9DFBF;
}


//HTML//

<div class="container2">
<div id="image1">
  <img id="yellow" src="https://i.ibb.co/VtsdZHt/yellowmac.png" height="80" alt="yellow macaron"><span class="text">Macarons have more in common with pasta than you thought..</span>
</div>
  
<div id="image2">
    <img id="blue" src="https://i.ibb.co/S3sRwqT/bluemac.png" height="80" alt="blue macaron"> <span class="text"> It is the most popular sweet sold in France.</span>

</div>
<div id="image3">
    <img id="pink" src="https://i.ibb.co/gMn6yqG/pinkmac.png" height="80" alt="pink macaron"> <span class="text">In North America, the coconut macaroon is the best known variety.</span></div>

</div>

Cheers!

does your div have a specific class that other divs do not have or an id? select the div specifically, you can also select the img specifically

or give the img a class

My div is classed with .container2 but if I want to change the background-color of everything inside that container I seem to have to select everything inside it individually, otherwise the background-color doesn’t work fully.

 .container2, #blue, #yellow, 
#pink, #image1, #image2, 
#image3, span {
  background-color: #A9DFBF;
}

do you have a pen or anyway a demo online?

you should be able to do something like .container2 > *

a cheat sheet may help you

1 Like

Thanks, I have the selector sheet but after seeing your example I see where I was going wrong. I thought I could only use selectors that are generic i.e ‘div > P’ and not ‘.class > img’

That said, even .container2 > * isn’t selecting all elements inside of it (to change background-color for example)

https://codepen.io/YKKZIP/pen/VwKwaLr

the one element > element works only for direct childrens, for all descendants you need to use element element

1 Like

Thank you, I’ve already tidied it up considerably!