Skip to main content

Command Palette

Search for a command to run...

CSS Selectors 101: Targeting Elements with Precision

Published
3 min read
CSS Selectors 101: Targeting Elements with Precision

CSS - Cascading style sheets is a very essential part of web development, HTML makes the structure of the webpage and CSS is used to impart visual effects to the website making it appealing.

In this article we are going to learn about CSS selectors

Why CSS selectors are needed

We need CSS selectors to target elements from the .html page for styling, if we don’t have CSS selectors the only way left would be adding style to every individual element using inline styling that will make the code chaotic and reduce readability. Also the clarity we get by separating html and css styling will be lost.

Element selector

This selector is used to style all occurrences of a specific element in the html page.

<p>Example of element selector<p>
<p>This is demo text<p>
p{
color : blue;
}

Class selector (.)

This selector comes in handy when we wish to apply the same style to a group of elements of the html page. It applies style to all elements having the same class value. It uses a period (.) symbol.

<p class="selector-example">Example of class selector<p>
<p>This is demo text<p>
.selector-example{
color: green;
}

ID selector (#)

When we have to add specific style to only one element whose sibling or other occurrences may have different styles applied we can use id selector, since id value is unique only the single element with the specific id will be affected. It uses a hash(#) symbol.

<p>Example of ID selector<p>
<p id="id-example">This is demo text<p>
#id-example{
color: orange;
}

Group selectors

Another way to style group of elements is using the grouping selector which allows us to name all the elements we wish to style in a single selection separated by commas (,)

<h1>Example of group selector</h1>
<p>This is demo text<p>
<div>This is new text</div>
p, div {
color: yellow;
}

Descendant selectors

The Descendant selector is used to target elements inside another element. It uses a greater than (>) symbol.

<div>
<p>Example of element selector<p>
<p>This is demo text<p>
</div>
div > p {
background-color: red;
}

Universal Selector

The universal selector is used to apply styles to all the elements in the .html page. It is uses asterisk(*) symbol.

<p>This is an example of Universal selector<p>
<div>
<h1>This is new text example</h1>
</div>
*{
background-color: pink;
}

Basic selector priority

From highest to lowest priority:

  1. Inline styles

  2. ID selector (#)

  3. Class selector (.)

  4. Element selector

  5. Universal selector (*)

If two selectors target the same element, the one with higher specificity wins. If specificity is equal, the later one in the CSS file is applied.