Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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!

like image 857
user1631224 Avatar asked Jul 16 '14 02:07

user1631224


People also ask

How do I use different CSS in the same class?

If you have two CSS files containing the same class name, then the properties of both will be applied in a sort of combination. If both class declarations share the same property, then the one for the file that was linked last is applied. Any properties that are declared in only one of the CSS files will be applied.

Can two classes have same name in CSS?

That's perfectly valid, and perfectly readable. Note particularly that the order the classes are declared in is not important.

Can you have multiple style CSS?

Yes, you can include multiple style sheets, but you need to label them as alternate style sheets and give the user some way to activate them using JavaScript - perhaps by clicking a link.

Can elements have multiple classes CSS?

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.


1 Answers

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.

like image 96
lucuma Avatar answered Oct 11 '22 01:10

lucuma