CSS Id 和 Class


id and class selectors

If you want to set CSS styles in HTML elements, you need to set the "id" and "class" selectors in the element.


id Selector

The id selector can specify a specific style for HTML elements marked with a specific id.

The HTML element uses the id attribute to set the id selector, and the id selector in CSS is defined with "#".

The following style rules are applied to the element attribute id="para1":

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<style>
.center
{
	text-align:center;
}
</style>
</head>

<body>
<h1 class="center">标题居中</h1>
<p class="center">段落居中。</p> 
</body>
</html>

Run Example»

Click the "Run Instance" button to view the online instance

lamp.gif Do not start the ID attribute with a number. IDs starting with numbers will not work in Mozilla/Firefox browsers.


class selector

class selector is used to describe the style of a group of elements. The class selector is different from the id selector. Class can be used in multiple elements.

The class selector is represented by the class attribute in HTML. In CSS, the class selector is displayed with a dot ".":

In the following example, all objects with the center class HTML elements are all centered.

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<style>
.center
{
	text-align:center;
}
</style>
</head>

<body>
<h1 class="center">标题居中</h1>
<p class="center">段落居中。</p> 
</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance

You can also specify specific HTML elements using classes.

In the following example, all p elements use class="center" to center the text of the element:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<style>
p.center
{
	text-align:center;
}
</style>
</head>

<body>
<h1 class="center">This heading will not be affected</h1>
<p class="center">This paragraph will be center-aligned.</p> 
</body>
</html>

Run Example»

Click the "Run Example" button to view the online example

lamp.gif The first character of the class name cannot use numbers! It won't work in Mozilla or Firefox.