ID selectors
Lesson 5 of 15 in Coddy's CSS Selectors course.
An ID selector is a type of CSS selector that selects elements that have a specific ID attribute. The ID attribute is a custom attribute that you can add to HTML elements to uniquely identify them.
To select elements with a specific ID, you use a hash (#) symbol followed by the ID value. For example, the selector #my-id selects the element with the ID my-id.
Here is an example of how to use an ID selector to style a web page:
#my-id {
color: red;
font-size: 2em;
}To add a id to an element write:
<div id="my-id"></div>Just like the Class selectors, this CSS rule will style the element with the ID my-id to be red and have a font size of 2em.
Challenge
EasyHere is an exercise to test your understanding of ID selectors:
- Create a web page with two
divelements. - Give the first
divelement the IDmy-id. - Use an ID selector to style the
divelement with the IDmy-idto be any color rather than black and have a font size of 30px.
Try it yourself
<html>
<head>
<title>ID Selector Exercise</title>
<style>
/* CSS Code goes here */
</style>
</head>
<body>
</body>
</html>
All lessons in CSS Selectors
3Combinator Selectors
Child selectorDescendant selectorAdjacent sibling selectorGeneral sibling selector