CSS Selectors
CSS Selectors
There are many ways we can select/address an element in CSS.
-
Using the tag name. For example, if we want to style all
<h1></h1>
tags on a page we can use the tag name to target the element.h1{ color: #fcfcfc; /* makes the text gray */ }
-
Using class name If we want to target all the elements with the class “red” (for example:
<h3 class="red"></h3>
) we can use a.
with the class name to target the group of elements with that class..red{ color: #fc2492; /* a magenta text */ }
-
Using ID If we want to target an element with the ID “xyz” (for example:
<h3 id="xyz"></h3>
) we can use a#
with the ID to target the element with that ID.#xyz{ color: #fc2492ff; /* a magenta text */ }
-
Universial Selector We can use the
*
as the universial selector. -
CSS Combinators There are different combinations we can use to target different elements -
a. Immidiate child:
div > p
gets all thep
tags which are immidiate child ofdiv
tag b. All descendents:div p
gets all thep
tags insidediv
tag c. Selector list:button, input
gets all thebutton
andinput
tag. d. Next sibling:#box+button
gets thebutton
tag right after the element with the id#box
-
Psudo Classes In CSS we have some psudo classes denoting states of elements, different states of form elements, or element position.
Example:
a:hover{ /* style the hover state of all anchor (a) tag */ }
div:nth-child(odd){ /* styles all the odd position div tags */ }
input:disabled{ /* styles the input element when it is disabled */ }
-
Psudo elements In CSS psudo elements target selective parts of an element. Example -
::before
,::after
,::first-letter
,::first-line
Example:
div::first-letter{ /* styles the first letter */ }
Fun note: In VSCode if you hover over a css selector it shows the definition provided by MDN for that selector