Saravanan
Saravanan

Reputation: 911

CSS nested class can't be selected directly?

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:

Upvotes: 2

Views: 1342

Answers (3)

PHP Geek
PHP Geek

Reputation: 4033

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

Upvotes: 1

codeandcloud
codeandcloud

Reputation: 55200

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.

Upvotes: 2

kiran
kiran

Reputation: 693

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>

Upvotes: 2

Related Questions