如何将不同的CSS样式应用于具有相同类名的2个元素? [英] How to apply different CSS styles to 2 elements with the same class name?
问题描述
我创建了一个拥有不同导航菜单的网站。在2个菜单中,我使用了相同的HTML类元素。
我有一个.css文件,它在1菜单中设置类元素的样式。然而,在另一个菜单中,我想以不同的方式设计元素。
是的,我知道我可以重命名类名,但要符合我的权限现在在我的标记结构中,还有类名称用于样式多个其他元素的事实,我将如何将不同的样式应用于具有相同类名的2个不同元素?
这可以使用CSS中的某种if语句条件来完成吗?
例如,在1.html中:
< div class =classname>一些代码< / div>
在2.html中:
< div class =classname>一些不同的代码< / div>
因为我只想在2.html中对这个one元素进行不同的设置,我可以只添加一个id属性以及class属性,并使用id和class,并以某种方式作为选择器?
再一次,我不想删除类名所有,如果可能的话。
谢谢! 只需添加,通常当有多个菜单,你可能会把它们包装在不同的结构中。例如:
< nav class ='mainnav'>< div class =classname one>一些代码< / div>< / nav>
< div class ='wrapper'>< div class =classname>一些不同的代码< / div>< / div>
您可以轻松地定位这些:
.mainnav> .classone {}
.wrapper> .classone {}
或者如果父html有一个类:
< div class ='ancestor1'><< b ; div>< div class =classname one>一些代码< / div>< / div>< / div>
< div class ='ancestor2'>< div>< div class =classname one>一些代码< / div>< / div>< / div>
.ancestor1 .classname {}
.ancestor2 .classname {}
显然这取决于它们可能在html中的位置。
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!
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.
这篇关于如何将不同的CSS样式应用于具有相同类名的2个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!