How to apply different CSS styles to 2 elements with the same class name?

css, html

Solution

I'll just add that typically when there are multiple menus you might have them wrapped in a different structure. Take for instance:

<nav class='mainnav'><div class="classname one"> Some code </div></nav>

<div class='wrapper'><div class="classname"> Some different code </div></div>

You can easily target these:

.mainnav>.classone {}
.wrapper>.classone {}

Or if the parent html has a class:

<div class='ancestor1'><div><div class="classname one"> Some code </div></div></div>
<div class='ancestor2'><div><div class="classname one"> Some code </div></div></div>

.ancestor1 .classname {}
.ancestor2 .classname {}

Obviously this depends on where in the html they might be.

Problem

I created a website that has different navigation menus. In 2 menus, I use the same HTML class element. I have a .css file that styles that class element in 1 menu. However, in another menu, I would like to style the elements differently. Yes, I know I can rename the class name, but to be consistent with what I have right now in the structure of my markup, and also the fact that the class name is used to style multiple other elements, how would I be able to apply different styles to 2 different elements with the same class name? Can this be done using some kind of if statement condition in CSS? For example, in 1.html: ``` <div class="classname"> Some code </div> ``` In 2.html: ``` <div class="classname"> Some different code </div> ``` Since I just want to style this "one" element differently in 2.html, can I just add an id attribute along with the class attribute, and use both the id and class and somehow as the selector? Once again, I would not like to remove the class name at all, if possible. Thanks!

Original source