CSS SELECTORS
CSS selectors are used to selecting the content you want to style. Selectors are the part of CSS rule set. CSS selectors select HTML elements according to their id, class, type, attribute, etc.
Types of selectors :-
- UNIVERSAL SELECTOR
The universal selector (*) selects all HTML elements on the page.
SYNTAX ->
* {
/* CSS code written here*/
}
this will select all the elements
EXAMPLE
The below example select all elements, and set their background color to yellow
* {
background-color: yellow;
}
- ID SELECTOR
The #id selector selects and styles the element with the specified id. To use an id selector we must use hash ( # ) before the id name.
SYNTAX -> #idname { /* CSS code written here */ }
EXAMPLE
#para1 {
text-align: center;
color: red;
}
- CLASS SELECTOR
The .class selector selects and styles all elements within the class that is specified. To use a class selector we must use dot (.) before the class name.
SYNTAX -> .class-name { /* CSS code written here */}
EXAMPLE
.center {
text-align: center;
color: red;
}
- GROUP SELECTOR
The grouping selector selects all the HTML elements with the same style definitions.
SYNTAX -> 1st element,2nd element {/* CSS code written here */}
EXAMPLE
h1, h2, p {
text-align: center;
color: red;
}
COMBINING SELECTORS
CSS selectors can also be combined. By combining selectors, then we can define CSS combinators.
- INSIDE AN ELEMENT SELECTOR
The element element selector is used to select elements inside elements.
SYNTAX -> 1st element 2nd element {/* CSS code written here */}
EXAMPLE
div p {
background-color: yellow;
}
- DIRECT CHILD SELECTOR
The child selector selects all elements that are the children of a specified element
SYNTAX -> element>child { /* CSS code written here */}
EXAMPLE
div > p {
background-color: yellow;
}
- ADJACENT SIBLING SELECTOR
The adjacent sibling selector is used to select an element that is directly after another specific element.
Sibling elements must have the same parent element, and "adjacent" means "immediately following".
SYNTAX -> element+sibling { /* CSS code written here */}
EXAMPLE
div + p {
background-color: yellow;
}
- GENERAL SIBLING SELECTOR
The general sibling selector selects all elements that are next siblings of a specified element.
SYNTAX -> element~sibling { /* CSS code written here */}
EXAMPLE
div ~ p {
background-color: yellow;
}
- CSS::AFTER PSEUDO-ELEMENT
The ::after selector inserts something after the content of each selected element(s).
SYNTAX -> element::after { /* CSS code written here */}
EXAMPLE
p::after {
content: " - Remember this";
}
- CSS::BEFORE PSEUDO-ELEMENT
The ::before selector inserts something before the content of each selected element(s).
SYNTAX -> element::before { /* CSS code written here */}
EXAMPLE
p::before {
content: " - Remember this";
}