CSS nested class can't be selected directly?

Viewed 283

I have to style an image with the class offer-img

<section class="offer">
  <div class="container">
    <div class="row">
      <div class="col-2">
        <!-- The image I want to style -->
        <img src="img.png" class="offer-img">
      </div>

      <div class=".."> ... </div>
    </div>
  </div>
</section>

In my style.css, when I try to access it with

/* somewhere above the hierarchy */
.col-2 img{
    max-width: 100%;
    padding: 50px 0;
    background-size: cover;
}
/* Not working  
.offer-img {
  padding: 40px;
}
*/

/* Works fine */
.col-2 .offer-img {
  padding: 40px;
}

Edited:

  • When I try to access the .offer-img directly, my style is not applied.
  • It only works when I change .offer-img to .col-2 .offer-img
  • Why .col-2 img's padding is overriding .offer-img's padding?
  • Is .col-2 img more specific than .offer-img
3 Answers

there's a typo here you've missed closing Quotation mark class="row> it should be class="row"> besides code is working just fine, i could select the class you're referring to without any issues & see if you're overriding styles.

.offer-img{
    padding: 50px;
    width: 500px;
}
<section class="offer">
      <div class="container">
           <div class="row">
                   <div class="col-2">  
                       <!-- The image I want to style --> 
                       <img src="https://wallpaperaccess.com/full/193101.jpg
" class="offer-img">
                    </div>

                   <div class=".."> ...  </div>
              </div>
       </div>
</section>

Yes. You can access the class directly and there is nothing wrong with your code.

You are seeing CSS Specificity in action here

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.

The three css classes you used:

  1. .offer-img: an element with the class .offer-img (less specific)
  2. .col-2 img: img element inside an element with class-name .col2 (more specific)
  3. .col-2 .offer-img: an element with class-name .offer-img inside an element with class-name .col2 (most specific)

The most specific style for the element will be applied if there are conflicts.

Check If there is any css for only "img" tag in your style sheet which override your this class

Else give "!important" like

.offer-img {
  padding: 40px !important;
}

The '!important' rule in CSS is used to add more importance to a property/value than normal

Related