CSS pseudo-classes

Understand the basics of CSS pseudo-classes

Pseudo-classes are predefined keywords that are used to select elements based on elementsstatus, Or target a specific child.

They areSingle colon :.

They can be used as part of a selector, and they are very useful for setting the style of activities or access links, for example, changing the style on hover, focusing or positioning to the first sub-object or odd-numbered rows. Very convenient in many cases.

These are the most popular pseudo-classes you might use:

Pseudo-class the goal
:active The element the user is activating (for example, clicking). Mainly used for links or buttons
:checked Enable checkbox, option or single choice input type
:default The default value in a set of options (for example, an option in a select or radio button)
:disabled Prohibited elements
:empty Element without children
:enabled Enabled elements (and:disabled)
:first-child The first child of a group of siblings
:focus Key elements
:hover Element hovered over
:last-child The last child of a group of siblings
:link Unvisited link
:not() Any element that does not match the passed selector. E.g:not(span)
:nth-child() Match the element at the specified position
:nth-last-child() Match elements at a specific position from beginning to end
:only-child Without any sibling elements
:required A form elementrequiredAttribute set
:root representativehtmlelement. Like positioninghtml, But more specific. usefulCSS variables.
:target Elements that match the current URL fragment (used for internal navigation in the page)
:valid Successfully validate the client's form elements
:visited Visited link

Let's make an example. In fact, this is a common one. You need to style the link, so you can create CSS rules to positionaelement:

a {
  color: yellow;
}

Everything is fine until you click a link. After clicking the link, the link will return to the predefined color (blue). Then, when you open the link and return to the page, the link is now blue.

Why is this so?

Because the link after clicking will change the status and enter:activestatus. When it is visited, it is in:visitedstatus. Until the user clears the browsing history.

Therefore, to make the link appear yellow correctly in all states, you need to write

a,
a:visited,
a:active {
  color: yellow;
}

:nth-child()Especially worth mentioning. Can be used for:nth-child(odd)with:nth-child(even).

It is usually used in lists, with different colors for odd and even rows:

ul:nth-child(odd) {
  color: white;
	background-color: black;
}

You can also use it to position the first three child elements of an element:nth-child(-n+3). Or you can set the style for every 5 elements:nth-child(5n).

Some pseudo-classes are only used for printing, for example:first,:left,:right, So you can locate the homepage, all left pages, and all right pages, which usually have slightly different styles.

Download mine for freeCSS Manual


More CSS tutorials: