pseudo-classes
testYourself CSS292
A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s) e.g. hover, active, visited, focus, checked, invalid, valid etc. A pseudo-class is prefixed with a single colon (:
).
required
The required
CSS pseudo-class represents any <input>
, <select>
, or <textarea>
element that has the required
attribute set on it.
style:
input:required {
border: 1px solid red;
}
html:
<p>
username:
<input type="text" required />
</p>
<p>
city:
<input type="text" />
</p>
result:
username:
city:
optional
The optional
CSS pseudo-class represents any <input>
, <select>
, or <textarea>
element that does not have the required
attribute set on it.
style:
input:optional {
border: 1px solid lightblue;
}
html:
<p>
username:
<input type="text" required />
</p>
<p>
city:
<input type="text" />
</p>
result:
username:
city:
checked
The checked
CSS pseudo-class selector represents any radio, checkbox, or option element that is checked or toggled on.
style:
input:checked {
box-shadow: 0 0 0 3px orange;
}
html:
<p>
chcked
<input type="checkbox" checked />
</p>
<p>
unchecked
<input type="checkbox" />
</p>
result:
checked
unchecked
nth-child
The nth-child
pseudo-class is specified with a single argument, which represents the pattern for matching elements. The index of the first element is 1.
css:
li:nth-child(2) {
color: blue;
}
html:
<ul>
<li>1st</li>
<li>2nd</li>
<li>3rd</li>
</ul>
result:
- 1st
- 2nd
- 3rd
first-child
The first-child
CSS pseudo-class represents the first element among a group of sibling elements.
css:
li:first-child {
color: blue;
}
html:
<ul>
<li>1st</li>
<li>2nd</li>
<li>3rd</li>
</ul>
result:
- 1st
- 2nd
- 3rd
last-child
The last-child
CSS pseudo-class represents the last element among a group of sibling elements.
css:
li:last-child {
color: blue;
}
html:
<ul>
<li>1st</li>
<li>2nd</li>
<li>3rd</li>
</ul>
result:
- 1st
- 2nd
- 3rd
hover
The hover
pseudo-class matches when the user interacts with an element with a pointing device but does not necessarily activate it.
style:
a:hover {
text-decoration: underline;
color: green;
}
html:
<a href="#">styled anchor</a>
result:
link
The link
pseudo-class represents an element that has not yet been visited.
style:
a:link {
color: pink;
}
html:
<a href="#">styled anchor</a>
result:
not
The not()
CSS pseudo-class represents elements that do not match a list of selectors.
style:
p:not(.warning) {
color: green;
}
html:
<p>normal paragraph</p>
<p>another normal paragraph</p>
<p class="warning">paragraph with warning</p>
result:
normal paragraph
another normal paragraph
paragraph with warning