id 和 class 有什么区别? [英] What's the difference between an id and a class?
问题描述
<div class="">
和 <div id="">
在 CSS 方面有什么区别?用<div id="">
可以吗?
What's the difference between <div class="">
and <div id="">
when it comes to CSS? Is it alright to use <div id="">
?
我看到不同的开发人员以两种方式这样做,而且由于我是自学的,所以我从来没有真正弄明白过.
I see different developers doing this in both ways, and since I'm self taught, I've never really figured it out.
推荐答案
ids
必须是唯一的,因为 class
可以应用于很多事情.在 CSS 中,id
s 看起来像 #elementID
而 class
元素看起来像 .someClass
ids
must be unique where as class
can be applied to many things. In CSS, id
s look like #elementID
and class
elements look like .someClass
通常,当您想引用特定元素时使用 id
,而当您有许多相似的东西时,请使用 class
.例如,常见的 id
元素是诸如 header
、footer
、sidebar
之类的东西.常见的 class
元素是诸如 highlight
或 external-link
之类的东西.
In general, use id
whenever you want to refer to a specific element and class
when you have a number of things that are all alike. For instance, common id
elements are things like header
, footer
, sidebar
. Common class
elements are things like highlight
or external-link
.
阅读级联并了解分配给各种选择器的优先级是个好主意:http://www.w3.org/TR/CSS2/cascade.html
It's a good idea to read up on the cascade and understand the precedence assigned to various selectors: http://www.w3.org/TR/CSS2/cascade.html
然而,您应该了解的最基本的优先级是 id
选择器优先于 class
选择器.如果你有这个:
The most basic precedence you should understand, however, is that id
selectors take precedence over class
selectors. If you had this:
<p id="intro" class="foo">Hello!</p>
和:
#intro { color: red }
.foo { color: blue }
文本会是红色的,因为 id
选择器优先于 class
选择器.
The text would be red because the id
selector takes precedence over the class
selector.
这篇关于id 和 class 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!