Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...