Pseudo class and Pseudo elements
Pseudo-classes are used to define the special states of an element. They are typically prefixed with a colon (:
).
:hover
: Applies when the user designates an element (with a pointing device), but does not activate it. Often used to change the appearance of a button when the mouse pointer is over it.
button:hover {
background-color: lightblue;
}
http://127.0.0.1:5500/index.html
:focus
: Applies when an element has received focus (e.g., when clicked on or tabbed to).
input:focus {
border-color: blue;
}
http://127.0.0.1:5500/index.html
:nth-child(n)
: Matches elements based on their position in a group of siblings.
li:nth-child(2) {
color: green;
}
http://127.0.0.1:5500/index.html
- Red
- Green
- BLue
:first-child
: Applies to the first child of its parent.
.container div:first-child {
color: blue;
font-weight: bold;
}
http://127.0.0.1:5500/index.html
Hello
World
:nth-of-type(n)
: Matches elements based on their position among siblings of the same type.
div:nth-of-type(3)
{
color: red;
}
Pseudo Elementsβ
::before
: Inserts content before an element's actual content.
p::before {
content: "Note: ";
font-weight: bold;
}
::after
: Inserts content after an element's actual content.
p::after {
content: " - Read more";
font-style: italic;
}
::first-line
: Applies styles to the first line of a block-level element.
p::first-line {
color: red;
font-weight: bold;
}