何时使用类选择器以及何时使用ID选择器

时间:2011-06-24 17:07:27

标签: css

  

可能重复:
  CSS: div id VS. div class

我是CSS新手并且有一般性问题:你如何决定使用类选择器或id选择器更好?

6 个答案:

答案 0 :(得分:1)

根据W3C标准,id只能在页面上使用一次,而一个类可以多次使用。

来自http://www.w3schools.com/tags/att_standard_id.asp

“ID”定义

The id attribute specifies a unique id for an HTML element.

The id must be unique within the HTML document.

The id attribute can be used by a JavaScript (via the HTML DOM) or 
by CSS to make changes or style the element with the specified id.
来自http://www.w3schools.com/tags/att_standard_class.asp“类”定义:

The class attribute specifies a classname for an element.

The class attribute is mostly used to point to a class in a style sheet. 
However, it can also be used by a JavaScript (via the HTML DOM) to make changes 
to HTML elements with a specified class.

由于id在页面上应该是唯一的,因此通过javascript

也可以更快地访问它

答案 1 :(得分:1)

ID必须是唯一的,而类不是。所以这取决于你想如何划分页面。

答案 2 :(得分:1)

id唯一标识一个元素,所以当你只有一个元素时就使用它(例如...

该类适用于具有相同功能的一组元素。

最佳实践说id在整个html页面中是唯一的

答案 3 :(得分:1)

ID应该用于单个元素:

<table id="specialtable">

类应该用于多个元素:

<h3 class="awesomeheader"> <!-- an awesome header -->
<h2 class="awesomeheader"> <!-- another awesome header -->

答案 4 :(得分:1)

当您只有一个需要样式的项目时,使用id是很好的。例如:

<div id = 'myDiv>Text</div>

#myDiv
{
   display: block;
}

但是当你想要以相同的方式设置多个项目时(例如在带有css文件的多个页面上),使用类更快(更好)

<div class = "MyDiv> text </div>
<div class = "MyDiv> more text</div>

.MyDiv
{
   color: black;
}

答案 5 :(得分:1)

这个页面上的答案都很好,但从更务实的角度来看,差别很大。让我试着从另一个角度向你解释一下。定义页面的概念实体时使用的ID,例如某些内容列表,页面页脚或导航菜单。你通常只有一个的东西,另一个没有意义,或者是另一种类型的实体。当你有一个重复实体的模式,或者用于相同目的的元素时,你倾向于为它们分配一个类,想一想部分标题,画廊中的照片等等。所以前面提到的列表中的项目都将被分配到同一个类名称。 但请注意,仅仅出于造型原因,您只能使用类,不要使用单个ID,并且完全没问题。你的课程只使用一次或多次都无关紧要。

相关问题