Html 单个元素html上的多个类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17366432/
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 10:34:41  来源:igfitidea点击:

multiple classes on single element html

htmlcss

提问by Andrius

Is it a good practice to use many classes on one single HTML element? For example:

在一个 HTML 元素上使用多个类是一种好习惯吗?例如:

<div class="nav nav-centered nav-reversed navbar navigation-block"></div>

I don't mean that two or three classes on one element is bad, but how about four, five or even six?

我并不是说一个元素上的两个或三个类是不好的,但是四个、五个甚至六个呢?

回答by Jeff Noel

Short Answer

简答

Yes.

是的。



Explanation

解释

It is a good practicesince an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

这是一种很好的做法,因为一个元素可以属于不同,并且您可能希望特定元素属于多个组。元素在 HTML5 中可以容纳无限数量的类,而在 HTML4 中,您受到特定长度的限制。

The following example will show you the use of multiple classes.

以下示例将向您展示多个类的使用。

The first class makes the text colorred.

第一堂课使文本color变红

The second class makes the background-colorblue.

第二类使background-color蓝色

See how the DOM Elementwith multiple classes will behave, it will wear bothCSS statements at the same time.

看看具有多个类的DOM 元素将如何表现,它会同时使用两个CSS 语句。

Result:multiple CSS statements in different classes will stack up.

结果:不同类中的多个 CSS 语句会堆叠起来

You can read more about CSS Specificity.

您可以阅读有关CSS 特异性的更多信息。



CSS

CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

现场演示

回答by relic

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

如果您需要它们,这是一个很好的做法。这也是一个很好的做法,因为它们有意义,因此未来的编码人员可以理解您在做什么。

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

但一般来说,将 10 个类名附加到一个对象并不是一个好习惯,因为很可能无论您将它们用于什么目的,您都可以使用更少的类来完成相同的事情。大概只有 1 或 2 个。

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

为了符合该声明,javascript 插件和脚本可能会附加更多的类名来执行它们将要执行的任何操作。例如,Modernizr 将 5 - 25 个类附加到您的 body 标签,这是一个很好的理由。当您使用该库中的一个小部件时,jQuery UI 会附加许多类名。