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 is cascading style sheets . these are used to beautify your web skeleton ( read prev blog on HTML for reference )

yes you can make all the web elements shown in cover image using css . just has to know how to use it .


CSS Selectors

used to "find" (or select) the HTML elements you want to style.

We can divide CSS selectors into five categories:

selector {
 property:value ;
property :value;
}

Types of Selectors

Element selector

these selectors use tagnames to select html elements , like for tag <h1></h1> the selector is h1 it will select all the h1 tags available in the doc

h1{
color:white;
}

Class Selector

these elements uses classes to select the elements . eg if a div is given class name intro then

.intro {
color : red;
margin : 10px;
}

Id selector

these use id assigned to element as id is unique it is given to one element . eg if a li in ul is given id orange

#orange {
 color: orange;
}

Group selectors

in this u can apply css properties to multiple elements , class , id at once

div, article{
 color : blue;
}

Descendent selector

if u want to target child of some element then u can use this, ( u can also use give that element a class , there is not right or wrong way ) eg u want to give color to h2 inside div

div h2{
color : green;
}

Selector Priority

IF you experiment a little you may tried to give multiple values to a single prop of an element using different type of selectors and see which one of it is applied .

In order to understand which value is prioritised you need to know how that priority is set by css

The priority of most specific selector is highest and as they become more general than its priority also decreases.

eg

  • * selects all so it is most general and hence least priority .

  • element selectors selects specific elements so prior. inc

  • class selectors allow to select more specific elements

  • id selectors since they are unique and applied to only an element these have the most prioirity .

summary :

Id > class > element > *