A CSS selector selects the HTML element(s) you want to style.
Selectors for CSS
CSS selectors are used to "find" (or choose) the HTML elements to style.
CSS selectors are classified into five types:
Simple selectors (items are selected based on their name, id, or class)
Combinator selectors (select components depending on their unique connection)
Pseudo-class selectors (elements are selected based on their state)
Selectors for pseudo-elements (select and style a portion of an element)
Attribute selectors (elements that are selected based on an attribute or attribute value)
This article will go through the most fundamental CSS selectors.
CSS Elements Selector
The element selector chooses HTML elements based on their names.
The element selector selects HTML elements based on the element name.
EXAMPLE
HTML
<!DOCTYPE html>
<html>
<body>
<p>I'm Infected...</p>
<p id="para1">Me too...</p>
<p>What a sad reality...</p>
</body>
</html>
CSS
p {
color: red;
text-align: center;
}
The CSS id Selector.
The id selector uses an HTML element's id property to choose a specific element.
Because an element's id is unique inside a page, the id selector is used to pick only one element!
To pick an element with a given id, use the hash (#) character followed by the element's id.
The CSS rule below will be applied to the HTML element with id="para1":
HTML
<!DOCTYPE html>
<html>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style.</p>
</body>
</html>
CSS
#para1 {
text-align: center;
color: red;
}
The class selector is used to select HTML items that have a specified class property.
To pick components with a certain class, start with a period (.) and then the class name.
Example.
HTML
<!DOCTYPE html>
<html>
<body>
<h1 class="center">The center-align of the class heading</h1>
<p class="center">Red and center-aligned paragraph.</p>
</body>
</html>
CSS
.center {
text-align: center;
color: red;
}
The universal selector (*) selects all HTML elements on the page.
Example.
HTML
<!DOCTYPE html>
<html>
<body>
<h1>CSS SELECTOR</h1>
<p>Every element on the page will be affected by the style.</p>
<p id="para1">and</p>
<p>others</p>
</body>
</html>
CSS
* {
text-align: center;
color: blue;
}
All HTML elements with the same style definitions are selected by the grouping selector.
Examine the CSS code below (the h1, h2, and p elements all have the same style definitions):
Example
HTML
<!DOCTYPE html>
<html>
<body>
<h1>I'm BIG!!!</h1>
<h2>I'm Medium</h2>
<p>I'm small...</p>
</body>
</html>
CSS
body {
background-color: Lightblue
}
h1, h2, p {
text-align: center;
color: black;
}