w3resource

CSS id selectors

 

Id selectors

CSS id selectors select any element in an HTML page, if it has an attribute called id, whose value matches the name of the id selector.

In a stylesheet document, the name of the id selector is preceded by a "#".

If an id selector is combined with another or more selectors, id selectors must be preceded with a #.

IDs can only be applied once in an HTML page.


syntax:

#idname{ CSS-Property: value; ........................ }

Simple Example of CSS id selectors

CSS code:

 #w3r {
color: red; /* sets color to red */ 
background-color: aliceblue; /* sets background color to aliceblue */ 
}
s

HTML code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Simple Example of CSS id selectors</title>
<link rel='stylesheet' href='Simple-Example-of-CSS-id-selector.css' type='text/css'>
</head>
<body>
<p id="w3r" >Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a urna elit.</p>
</body>
</html>

Result:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a urna elit.

View this simple example of CSS id selector in a separate browser window.

Advanced Example of CSS id selectors

CSS code:

p#w3r {
color: red; /* sets color to red */
background-color: aliceblue; /* sets background color to aliceblue */
}
h2#w3r {
color: blue; /* sets color to blue */
background-color: lime; /* sets background color to lime */
}

HTML code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Advanced Example of CSS id selectors</title>
<link rel='stylesheet' href='Advanced-Example-of-CSS-id-selector.css' type='text/css'>
</head>
<body>
<div>
<h2 id="w3r">CSS examples</h2>
<p id="w3r">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a urna elit.</p>
</div>
</body>
</html> 

Result:

CSS examples:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a urna elit.

 

View this advanced example of CSS id selector in a separate browser window.

Previous: CSS class selectors
Next: CSS pseudo classes



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/css/selectors/CSS-id-selector.php