CSS Basic selectors
Universal Selector:
The universal selector selects all elements.
It is denoted using *
*{ color= "red"; }
The difference between the universal selector and if we use a class selector such as a body
in which all the elements of the document are present is that:
body{ color= "red"; }
In the second case, the default browser styles do not get overridden.
Eg: The default browser style for <a href> will get override only with universal selector.
<a href="https://www.google.com"> Search </a>
a{ color= "blue"; text-decoration="underline";}
Class Selector:
Selects all the elements which are present inside that class.
There can be multiple elements with the same class name.
<div class="post">
.post{ background-color : yellow; }
This will give a yellow background color to all the elements which are inside the post class
Id Selector:
This selects the element which has got that particular id.
There can be only one element with a given ID in a file.
<div id=#header>
Adjacent Selectors:
The +
combinator selects adjacent siblings. This means that the second element directly follows the first, and both share the same parent.
Eg : div + p
Selects all <p> elements that are placed immediately after <div> element.
Attribute Selectors:
Attribute Selectors are used to selecting elements with given attributes or values
div[a]
Eg: Here all the a
tags present inside the div are targeted.
We can be more specific with the attributes such as by using ^
we can select all the elements starting with the given attribute, also if we use $
this will select all the elements ending with the specified elements
a[href^="https"]
Selects every <a> element whose href attribute value begins with “https”
a[href$=".jpg"]
Selects every <a> element whose href attribute value ends with “.jpg”
Pseudo Class Groups:
There are 2 types of Pseudo-classes they are:
Dynamic Pseudo Classes:
Allow us to style an element in relation to user actions, such as:
- Whether a link is being hovered over
- Whether a button is being pressed
- Whether a tick box has been checked
Structural Pseudo Classes:
Allow us to style elements based on advanced structural techniques not possible from ordinary CSS selectors.
- The 5th<li> tag in a list
- A parent tag that has no children
Child Selectors: Direct Child
The class which is present immediately after the parent class is called Direct Child.
If you want to target these direct child there is no need to give a separate name to this element.
They can be accessed as:
#header > p{color: red;}
So here the element p
which is present after the header
can be targeted simply by using >
symbol.
Nth Child Selector:
li:nth-child(5)
— This will select 5th element of the list
li:nth-child(even)
— This will select all the even elements of the list
li:nth-child(2n+1)
— You can also try adding a complex formula inside this nth child ; )