CSS id and class
CSS id and class (CSS id和class)
In our previous chapter, we learned about selectors. Now we will speak about id and class selectors frequently used to style web page elements. (在上一章中,我们了解了选择器。现在,我们将讨论常用于网页元素样式的id和class选择器。)
CSS id selector
CSS id selector (CSS ID选择器)
An ID selector is a unique identifier of the HTML element to which a particular style must be applied. It is used only when a single HTML element on the web page must have a specific style. (ID选择器是必须应用特定样式的HTML元素的唯一标识符。仅当网页上的单个HTML元素必须具有特定样式时才使用它。)
Both in Internal and External Style Sheets we use hash (#) for an id selector.
Example of an ID selector:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
#blue {
color: #1c87c9;
}
</style>
</head>
<body>
<p>The first paragraph.</p>
<p id="blue">The second paragraph.</p>
<p>The third paragraph.</p>
</body>
</html>
As you see, we assigned blue as id selector of the second paragraph (id=“blue”), and declared its style using color property - #blue {color: #1c87c9;} in the <head> section. It means that the HTML element having id selector blue will be displayed in #1c87c9.
Check this code in our HTML online editor to see that the color of the second paragraph is #1c87c9.
CSS class selector
CSS class selector (类选择器)
A class selector is used when the same style must be applied to multiple HTML elements on the same web page. (当同一样式必须应用于同一网页上的多个HTML元素时,使用类选择器。)
Both in Internal and External Style Sheets we use a dot (.) for a class selector. (在内部和外部样式表中,我们都使用点(. )作为类选择器。)
Example of a class selector:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.blue {
color: #1c87c9;
}
</style>
</head>
<body>
<h2 class="blue">This is some heading.</h2>
<p>The second paragraph.</p>
<p class="blue">The third paragraph.</p>
</body>
</html>
In our example, a class selector is used twice, in heading and paragraph. (在我们的示例中,类选择器在标题和段落中使用了两次。)
As you see, we assigned blue as class selector (class=“blue”), and declared its style using color property - .blue {color: #1c87c9;} in the <head> section. It means that the elements having class selector blue will be displayed in #1c87c9.
In our example, the title and the third paragraph are #1c87c9. Check it in our HTML online editor.
The Difference Between ID and Class
The Difference Between ID and Class (ID和类之间的区别)
The difference between IDs and classes is that the first one is unique, and the second one is not. This means that each element can have only one ID, and each page can have only one element with this ID. When using the same ID on multiple elements, the code won’t pass validation. But as the classes are not unique, the same class can be used on multiple elements, and vice versa, you can use several classes on the same element. (ID和类的区别在于,第一个是唯一的,第二个不是。这意味着每个元素只能有一个ID ,每个页面只能有一个具有此ID的元素。当在多个元素上使用相同的ID时,代码将无法通过验证。但由于类不是唯一的,同一个类可以在多个元素上使用,反之亦然,您可以在同一个元素上使用多个类。)