CSS Selectors
Selectors are used to style HTML elements according to their type and/or attributes.
All markups can be selected with the * selector:
* {/* declarations here */}
Selecting by Type
The element selector selects HTML elements based on the element name.
Syntax
element-name {/* declarations here */}
The element-type must be a valid HTML element.
Example
In the following example, all of the <p> elements on the page will be centered with a red text color:
p {text-align: center;color: red;}
Selecting by Attribute
The class selector selects elements that are assigned a class attribute, it can be used across multiple elements, and begins with a period, .. Similarly, the id selector selects an HTML element that has an id attribute. In contrast, the id selector can only be applied once and begins with the hashtag symbol, #.
Syntax
#id-name {/* declarations here */}.class-name {/* declarations here */}element[attribute='value'] {/* declarations here */}
The id of an element is unique within a page, so the id selector is used to select one unique element. An element can be selected with a specific id, by using a hash (#) character, followed by id-name.
Multiple class values can be assigned to a single element. Elements are selected by class with a period (.) character, followed by class-name. Unlike id values, class values can be duplicated on a page with different elements.
Example
The following rules select elements based on id, class, and other attributes:
#para1 {text-align: center;color: red;}.center {text-align: center;color: red;}li[title='red'] {background-color: red;color: #fff;}
It can also be specified that only certain HTML elements with a given class should be styled. For example, here, only <p> tags with a class of "center" will have its text center-aligned:
p.center {text-align: center;color: red;}
The CSS Grouping Selector
The grouping selector selects a group of HTML elements and applies a specific set of styles to each one of them, helping in minimizing the codebase.
Syntax
elm1, elm2, elm3 {
/* Declarations are inserted here */
}
In the following example, a particular set of styles is applied to all the h1, h2, and p elements:
Example
h1,h2,p {text-align: center;color: red;}
Video Walkthrough
Watch this video on how to compare the various selectors in CSS.
All contributors
sczerman
BrandonDusch
christian.dinh- Anonymous contributor
- Anonymous contributor
artyspangler
CaupolicanDiaz
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn CSS on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- In this CSS tutorial, you’ll learn how to add CSS to visually transform HTML into eye-catching sites.
- Beginner Friendly.6 hours