CSS Advanced Selectors

Pseudo Classes

The following classes are really good for selecting a certain state of an element.

a:hover {
    background: #07a;
}

a:active {
    background: green;
}

a:visited {
    background: black;
}

input:focus {
    background: #222;
}

Child Selectors

Sometimes we need to select a certain child of a parent, for example the first or the fifth li in a list

li:first-child {
    background: black;
}

li:last-child {
    background: grey;
}

li:nth-child(3) {
    background: red;
}

Combinators

There selectors are, in my opinion, ridiculous. I suppose their may be times where you need to use them, but in my opinion, having to use these selectors may be a hint that you have organized your styles wrong. I hope you never have to use them. But if you do, here they are.

Adjacent Sibling

This styles the second tag if it comes after the first tag

a:first-of-type + a {
  color: red;
}
General Sibling

This only styles the second selector if it comes after the first sibling at some point, and its parent is the same. So if the second comes before the first in the list, it does not get styled.

a ~ span {
    color: green;
}
Direct Child

This only styles the second element if it is a direct child of the first

a > span {
    color: yellow;
}

results matching ""

    No results matching ""