Variable Visions

Articles CSS CSS-Selectors


tutorials - CSS and Web-Development.

CSS Selectors

Published Mon. Sep. 17, 2012


Have you ever seen symbols like >, +, and ~ in CSS files but never fully understood what they meant?

Here is an easy to read cheat sheet on the intermediate CSS selectors.

See the + and > in action in this tutorial, as ALL CSS Selectors can be used as jQuery targets !



"DESCENDANTS VS. DIRECT CHILDREN VS. ADJACENT"

SELECT ALL DESCENDANT H1 TAGS INSIDE OF CONTAINER
#container h1 {
    color: #666;
}
SELECT ALL DIRECT CHILDREN H1 TAGS INSIDE OF CONTAINER
(ALL H1 TAGS INSIDE THE FIRST LEVEL BUT NOT IF THEY ARE DEEPER IN)
#container > h1 {
    color: #666;
}
SELECT THE H1 TAGS WHEN DIRECTLY ADJACENT TO A IMMEDIATELY PRECEDING  DIV
(WHEN A DIV AND A H1 ARE DIRECTLY NEXT TO EACH OTHER)
#container div +  h1 {
    color: #666;
}
SELECT THE H1 TAGS WHEN  A GENERAL SIBLING TO A PRECEDING DIV BUT NOT NECESSARILY RIGHT NEXT TO EACHOTHER
#container div ~  h1 {
    color: #666;
}

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


"Structural pseudo-classes (:NTH-CHILD)"


ALTERNATING BACKGROUND COLORS ON LIST ITEMS
ul#mainmenu li:nth-child(even) {background: #efeded;}
ul#mainmenu li:nth-child(odd) {background: #e8e5e5;}

FIRST LIST ITEM
ul#mainmenu li:first-child {
    font-size: 1.2em;
}
LAST LIST ITEM
ul#mainmenu li:last-child {
    font-size: .8em;
}
EVERY THIRD LIST ITEM
ul#mainmenu li:nth-child(3n+3) {
    background: #e8e5e5;
}
ONLY THE FIFTH LIST ITEM
ul#mainmenu li:nth-child(5) {
    background: #e8e5e5;
}

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


"ATTRIBUTE SELECTORS"


ZERO OUT THE LEFT MARGIN WHEN A IMG TAG WITHIN CONTAINER HAS THE FLOAT ATTRIBUTE SET TO LEFT
#container img[float="left"] {
    margin-left: 0 !important;
}
AND, ZERO OUT THE RIGHT MARGIN WHEN A IMG TAG WITHIN CONTAINER HAS THE FLOAT ATTRIBUTE SET TO RIGHT
#container img[float="right"] {
    margin-right: 0  !important;
}
ZERO OUT THE LEFT MARGIN WHEN A IMG TAG WITHIN CONTAINER HAS THE FLOAT ATTRIBUTE SET TO LEFT OR RIGHT
#container img[float] {
    border-radius: 5px;
}
PUT A BOX SHADOW ON ALL INPUTS WITH A TYPE OF TEXT OR PASSWORD
input[type=text], input[type=password] {
    box-shadow: inset 0 1px 3px rgba(0,0,0,0.3) !important;
}






There are many other selectors:
first-of-type, last-of-type, only-child, only-of-type, empty (no children), visited, link, active, hover (most common), focus, target, before, after, :not(x), first-letter, etc.

I will go into first-of-type and other advanced CSS selectors in the next tutorial.


Tag(s): css selectors, descendant, direct children, adjacent siblings, pseudo-classes