CSS Selectors

CSS Selectors

CSS selectors allow you to select and manipulate HTML elements. Selectors are used to fine/select certain HTML elements based on their ID, attributes, classes, values, etc.

Element Selector

The element selector selects elements based on the element name. For example, by selecting the <p> element, then all the <p> elements on the page will be center-aligned with a red text:

p{
text-align: center;
color: red;
}

ID Selector

The id selector uses the ID attribute of an HTML tag to find the specific element. An ID should be unique within a page, so you should use the ID selector when you want to find a single, unique element.

To find an element with a specific ID, write a hash character, followed by the ID of the element. The style rule below will be applied to the HTML element with the id=”paragraph1″:

#paragraph1 {
text-align: center;
color: red;
}

Class Selector

The class selector uses the HTML class attribute and finds elements with the specific class. Write a period character followed by the name of the class to find elements with a specific class. The style rule below, all HTML elements with the class=”center” will be center-aligned:

.center {
text-align: center;
color: red;
}

You can also specify that only specific HTML elements should be affected by a  class. The rule below specifies all p elements with class=”center” will be center aligned:

p.center {
text-align:center;
color:red;
}

Grouping Selector

In style sheets there will often be elements with the same style (e.g. same text-align, color, etc.). In that case, you can minimize the code and group the selectors, separating them with a comma.

h1, h2, p {
text-align: center;
color: red;
}