ID Selector
Part of the Styling with CSS section of Coddy's HTML journey — lesson 13 of 76.
The ID selector is used to target a specific HTML element based on the value of its id attribute. Unlike class selectors, which can be used to style multiple elements, ID selectors are unique and can only be applied to a single element on a page. This makes them useful for styling individual elements with specific styles that should not be applied to any other element.
To target an element with a specific ID in your CSS, you use a hash symbol (#) followed by the ID value. Here's the basic syntax for using an ID selector:
#idname {
property: value;
}For example:
#intro {
color: blue;
font-size: 20px;
}In this example, the ID selector #intro targets the element with the ID "intro". The declarations set the text color to blue and the font size to 20 pixels for this element.
Challenge
EasyYou are given an HTML document with various elements, including a heading (<h1>), a paragraph (<p>), and a division (<div>). Your task is to use an ID selector to style a division element. Follow the steps below:
- Add an
idattribute with the value "special" to the<div>element. - Write a CSS rule using an ID selector that targets the element with the ID "special". Set the background color of this element to yellow and the text color to red.
Cheat sheet
The ID selector targets a specific HTML element using its id attribute. ID selectors are unique and can only be applied to a single element on a page.
Use a hash symbol (#) followed by the ID value:
#idname {
property: value;
}Example:
#intro {
color: blue;
font-size: 20px;
}Try it yourself
<html>
<head>
<title>ID Selector</title>
<style>
/* Write CSS rules here */
</style>
</head>
<body>
<h1>This is a main heading</h1>
<p>This is a paragraph.</p>
<div>This is a division.</div>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Styling with CSS
5 Colors and Backgrounds
Background ColorHEX ColorsRGB ColorsTransparency with RGBARecap Challenge #1