CSS Pseudo Classes
Learn the basics of CSS Pseudo classes.
Pseudo classes are predefined keywords that are used to select an element based on its state, or to target a specific child.
They start with a single colon :
.
They can be used as part of a selector, and they are very useful to style active or visited links for example, change the style on hover, focus, or target the first child, or odd rows. Very handy in many cases.
Example
Let’s do an example. A common one, actually. You want to style a link, so you create a CSS rule to target the a
element:
a {
color: green;
}
Things seem to work fine, until you click one link. The link goes back to the predefined color (blue) when you click it. Then when you open the link and go back to the page, now the link is blue.
Why does that happen?
Because the link when clicked changes state, and goes in the :active
state. And when it’s been visited, it is in the :visited
state. Forever, until the user clears the browsing history.
So, to correctly make the link yellow across all states, you need to write
a,
a:visited,
a:active {
color: green;
}
CSS Pseudo Elements
A CSS pseudo-element is a keyword added to a CSS selector that lets you style a specific part of the selected HTML element. In CSS3, they are usually denoted by two colons — for example, ::first-line
— to differentiate them from pseudo-classes.
Syntax
The general syntax for CSS pseudo-elements looks like this:
selector::pseudo-element {
property: value;
}
It looks just like normal styling statements but with the colons to indicate the specific part of the elements contained in the selector that you want to style.
Download FREE CSS Pseudo Cheat Sheet
Contact me if you have any questions or need a website.