The ID selector in CSS is used to select a single element with a specific id attribute. Unlike class selectors, which can be applied to multiple elements, an ID should be unique within an HTML document. To use an ID selector, you prefix the id name with a hash symbol (#).
To apply a style to an element with a specific ID:
/* This will select the element with the ID "header" */
#header {
background-color: lightblue;
font-size: 20px;
}
You add the id attribute to your HTML element to apply the styles defined by the ID selector:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ID Selector Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="header">This is the header</div>
<p>This is a paragraph.</p>
<p id="unique-paragraph">This is a unique paragraph with a specific ID.</p>
</body>
</html>
ID selectors can be combined with other selectors for more specific targeting:
/* Selects the <p> element with the ID "unique-paragraph" */
p#unique-paragraph {
color: darkred;
font-weight: bold;
}
/* Selects the element with the ID "footer" within a <div> */
div#footer {
background-color: lightgrey;
padding: 10px;
}
Here is a complete example demonstrating the use of ID selectors in a simple HTML document:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ID Selector Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="header">This is the header</div>
<p>This is a paragraph.</p>
<p id="unique-paragraph">This is a unique paragraph with a specific ID.</p>
<div id="footer">This is the footer</div>
</body>
</html>
styles.css
)/* Selects the element with the ID "header" */
#header {
background-color: lightblue;
font-size: 20px;
padding: 10px;
}
/* Selects the <p> element with the ID "unique-paragraph" */
p#unique-paragraph {
color: darkred;
font-weight: bold;
}
/* Selects the element with the ID "footer" */
#footer {
background-color: lightgrey;
padding: 10px;
}
In this example:
header
will have a light blue background, a font size of 20px, and padding of 10px.<p>
element with the ID unique-paragraph
will have dark red text and bold font weight.footer
will have a light grey background and padding of 10px.#header
, #footer
, #main-content
).