Steve Kim
Steve Kim

Reputation: 5611

Efficient ways to apply different css to same class

So, I have a collection of div as following for My Page.

 <div class="My_Page"> 
    <div class="one"> 
        <div class="two"> 
           <a href="#"> Hi </a>
        </div>
    </div>
 </div>

Then I have another page with same class= one and two.

 <div class="Your_Page"> 
    <div class="one"> 
        <div class="two"> 
           <a href="#"> Hi </a>
        </div>
    </div>
 </div>

However, I am trying to apply different css to class= one and two based on what page they are in.

For example:

  1. My_page: .My_Page .one{width:100%;}

  2. Your_Page: .Your_Page .one{width:50%}

I have one css file which contains both codes.

For either pages, these two css markups are loaded and I feel like there must be more efficient ways to apply different css based on what parental div it is in.

Or am I doing it right?

Thanks

Upvotes: 1

Views: 3753

Answers (4)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

.page{ ....  //common css for both page one and two}
.page .one{ width:100% .... //common for both  } 
.page .two{ .... //common for both  } 

.My_page .two{ width:50%;}


<div class="page My_page">
   <div class="one"> 
        <div class="two"> 
           <a href="#"> Hi </a>
        </div>
    </div>
</div>

Upvotes: 2

Joshua Carmody
Joshua Carmody

Reputation: 13740

Since your outer div has a different class, you could use a child selector to do something like this:

.My_Page .one {
    color: red;
}
.Your_Page .one {
    color: blue;
}

In that example, elements with the class one would only be red if they were inside a parent element with a class of My_Page.

Edit after re-reading the question:

Now I see that you seem to already be doing this. Yes, that is fine. You're doing it right. You could also include a different style sheet on each page if you're very concerned about the size of the style sheet. But that's not really necessary in most cases.

Upvotes: 1

Andrew Fan
Andrew Fan

Reputation: 1321

You are doing it correctly -

.outerclass .innerclass {  }

will apply the style changes to all instances of this specific scenario.

Upvotes: 2

DrCord
DrCord

Reputation: 3955

You are doing it correctly, CSS is very lightweight and loading unused code is not overly bad. However if you feel the need to do so you could load page specific CSS files and then have a whole site file that is loaded for all pages.

Upvotes: 2

Related Questions