What is a CSS selector?
CSS selectors are used to target the HTML elements on our web pages that we want to style.
h1 {
color: red;
background-color: black;
}
p {
color: aqua;
}
h1 is a CSS Selector , it targets the h1 element
text color=red ,background_color =black will apply to h1 elements.
** CSS selector Types **
Basic selectors
- Universal selector: Selects all elements , The CSS universal selector (*) matches elements of any type.
* {
color: blueviolet;
}
- **type selector ** It selects all elements of the given type within a Html document.
span {
background-color: skyblue;
}
- Class selector Selects all elements that have the given class attribute.
.container {
background-color: aqua;
}
- ID selector The CSS ID selector matches an element based on the value of the element's id attribute.
#name_input {
background-color:#1f1f1f ;
}
- Attribute selector The CSS attribute selector matches elements based on the presence or value of a given attribute.
a[href$=".org"] {
color: red;
}
/*Links that end in ".org" are red.*/
Grouping selectors
- The ,(comma) selector is a grouping method that selects all the matching nodes. Example: div, span will match both span and div elements.
div,span {
color: aqua;
}
Combinators
- ** Descendant combinator ** The " " (space) combinator selects nodes that are descendants of the first element. Example: div span will match all **span **elements that are inside a div element.
div span {
color: aqua;
}
- Child combinator The > combinator selects nodes that are direct children of the first element. Example: ul > li will match all li elements that are nested directly inside a ul element.
ul>li{
background-color: aquamarine;
}
- General sibling combinator The ~ combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent. Example: p ~ span will match all span elements that follow a p, immediately or not.
span ~ p{
background-color: azure;
}
- Adjacent sibling combinator
The + combinator matches the second element only if it immediately follows the first element. Example: h2 + p will match the first p element that immediately follow an h2 element.
h2+p{
background-color: azure;
}
Pseudo
-** Pseudo classes** The : pseudo allow the selection of elements based on state information that is not contained in the document tree. Example: a:visited will match all a elements that have been visited by the user.
a:visited {
color: yellow;
}
-** Pseudo elements** The :: pseudo represent entities that are not included in HTML. Example: p::first-line formats the first line of the text in all
elements:
p::first-line {
font-size: 1.2em;
}
Further reading:Mdn Web Docs : CSS Selectors