Skip to main content

Command Palette

Search for a command to run...

CSS Selctor guide

basic selectors available in CSS with their syntax and example

Updated
•3 min read•View as Markdown
CSS Selctor guide

CSS - Cascading Style Sheets ...in simple language it is something which gives structure, cosmetic effects and lot more functionality to your HTML page...

To apply these effect, and place them in desire position on page you need to select correct object.

Following are the basic selectors types we usally need.

1. Element type selector

It selects element by name <elment name> from html page

h1{
font family: poppins;
font weight: 200;
}

2. Id selector

ID can be selected by placing prefix # before its ID name. be careful, we get consufed between ID and Class selector whille selecting them.

#id-test{
border: solid;
color: #ffff;
}

3. Class selector

to select class we put . as prefix to its class name.

.test-class{
border: solid;
color: #ffff;
}

4. Universal selector

sometimes there are condition where we need to target all elements in html page, which can be achived with * selector

*{
border 0;
margin 0;
}

5. group selector

we can select multiple items by placing their name seperated by , to apply same style to all of them

h1, h2{
border 0;
margin 0;
}

6. chained selector

When writing CSS rules, it’s possible to require an HTML element to have two or more CSS selectors at the same time.

This is done by combining multiple selectors, which we will refer to as chaining. For instance, if there was a .special class for h1 elements, the CSS would look like:

h1.special {

}

The code above would select only the h1 elements that have a class of special. If a p element also had a class of special, the rule in the example would not style the paragraph.

7. Direct child selector

Child selector is used to target child of parent. in syntax we need to put '>' between parent and child element. in below example h2 is inside div which we are targeting to apply font style.

div > h2{
font-family: poppins;
font-size; 20px;
{

8. Sibling selector

sibling selectors selects an element that is directly after specific element. in following example we are targetting first <n> th element after div.

div + n{
color: #ffff;
}

also there is option to select all sibling of the parent by putting '~' after parent as in follwoing example

div ~ n{
color: #ffff;
}

it will select all n elements after parent div.

9. Pseudo selector

A pseudo-class is used to define a special state of an element.

it can be used to:

  • Style an element when a user mouses over it - :active
  • Style visited and unvisited links differently - :visited
  • Style an element when it gets focus - :hover
/* visited link */
a:visited {
  color: #00FF00;
}

/* mouse over link */
a:hover {
  color: #FF00FF;
}

/* selected link */
a:active {
  color: #0000FF;
}