Html 一个元素可以同时有一个 id 和一个类吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2813653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:02:55  来源:igfitidea点击:

Can an element have both an id and a class?

htmlcssclass

提问by kim holder wants Monica back

pretty self-explanatory.

不言自明。

回答by Nick Craver

Yes, an element can have one ID (which must be unique!) and multiple classes at the same time. To have multiple classes, use a space between them, here's an example:

是的,一个元素可以同时有一个 ID(必须是唯一的!)和多个类。要拥有多个类,请在它们之间使用空格,这是一个示例:

<div id="myID" class="class1 class2 class3">Content</div>

回答by Vandervidi

I would like to add that if you add both ID and a class that contradict each other, the ID will have higher priority.

我想补充一点,如果您同时添加 ID 和一个相互矛盾的类,则 ID 将具有更高的优先级。

For example:

例如:

CSS:

CSS:

.par_color{
    color:red;
}

#par_color{
    color:blue;
}

HTML:

HTML:

<section id="par_color" class="par_color">Some txt</section>

Some txt string will be shown in blue and not in red.

一些 txt 字符串将显示为蓝色而不是红色。

回答by Alex Mcp

Yes. Self explanatory.

是的。不言自明。

Additionally, it's common to have more than one class IE -

此外,拥有多个类 IE 是很常见的 -

<div class="oneClass andAnother"></div>

but only one ID per element, and each ID should only be used once per HTML page.

但每个元素只能有一个 ID,并且每个 ID 只能在每个 HTML 页面使用一次。

回答by Larsenal

Yes.

是的。

<div id="main" class="rounded">
</div>

回答by developmentalinsanity

In short, yes. Usually the class would be for styling and the id to allow direct manipulation by scripts.

简而言之,是的。通常该类用于样式和 id 以允许脚本直接操作。

回答by rishav kumar

yes you can add id and class as well as a class and a id

是的,您可以添加 id 和 class 以及 class 和 id

for a class and a id<h1 id="orange-text" class="pink-text blue-text">Hello World!</h1>for two classes<h1 class="orange-text" class="pink-text blue-text">Hello World!</h1>

一个班级和两个班级的 id<h1 id="orange-text" class="pink-text blue-text">Hello World!</h1><h1 class="orange-text" class="pink-text blue-text">Hello World!</h1>

回答by Gabriel Caldas

Yes, you can. But note that Id's must be unique within your html file, while classes can be used in multiples elements.

是的你可以。但请注意,Id 在您的 html 文件中必须是唯一的,而类可以在多个元素中使用。

<div class="examples" id="example1">text example</div>