id和类之间的区别 [英] Difference between id and class

查看:119
本文介绍了id和类之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<div id="stockexchange-id" class="stockexchange-class">Text</div>

在上面的例子中,我在div语句中添加了一个类和一个id。他们之间有区别吗?如果我调用.stockexchange类CSS而不是#stockexchange-id CSS它有什么区别?如果它不然,那么它有两个点的点?

In the example above I added both a class and an id into the div statement. Is there a difference between them? If I call .stockexchange-class CSS instead of #stockexchange-id CSS does it make any difference? If it doesn't then what it the point of having both of them? Also which one would be better to use?

推荐答案

最大的区别是文档可以有多个具有相同类的元素,但不具有相同的ID。

The biggest difference is that a document can have multiple elements with the same class, but not with the same ID. An Identifier must be specific to a certain element within a document (i.e. full HTML page).

在应用CSS样式时,一些专家建议在ID上使用类来避免特殊性战争。 CSS Lint( http://csslint.net/ )推荐了这个方法。

When applying CSS styling, some experts have recommended using classes over IDs to avoid specificity wars. CSS Lint (http://csslint.net/) recommends this.

原因是样式表是从上到下读取的,但ID优先于类。这意味着:

The reason is that stylesheets are read from top to bottom, but IDs take precedence over class. This means that:

#stockexchange-id { 
  color: blue;
}

.stockexchange-class {
  color: red;
}

将文本颜色为蓝色,即使红色较晚。以下是解释特定性的好图片: https://stuffandnonsense.co.uk/archives/ images / specificitywars-05v2.jpg

Would color the text blue, even though red comes later. Here's a good graphic explaining specificity: https://stuffandnonsense.co.uk/archives/images/specificitywars-05v2.jpg.

如果一切都具有相同的特异性,并且大多数样式通过一个类应用,原因,因为它将读取从上到下,没有额外的样式混合在不同的顺序。

If everything has the same specificity, and most styles are applied via a single class, it makes the CSS easier to reason about, since it will read from top to bottom without extra styles being mixed in different orders. It also makes it easier to override classes, which can be useful.

最后,如果你基于类的风格,你可以在同一页面上重新使用样式将类应用于页面上的另一个元素。有了ID,由于它们是唯一的,你不能这样做。即使您认为某个元素在网页上是唯一的(例如购买按钮),这可能并不总是如此。设计者可以在页面的稍后再次请求相同的元素。

Finally, if you style based on classes, you can re-use the styling on the same page by applying the class to another element on the page. With IDs, since they are unique, you cannot do this. Even if you think an element is unique on a page (e.g. a Buy Button), this may not always be the case. A designer may request the same element again later in the page.

这篇关于id和类之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆