Estelle Weyl | @estellevw | Github | Press key to advance.

Select This!
CSS Selectors

estelle.github.io/selectors/45.html

Basic Selectors

<ul>
 <li id="myID" class="myClass">item 1</li>
 <li class="myClass">item 2</li>
 <li>item 3</li>
</ul> 
#myID
ID
.myClass
class
li
tag name

Selectors API

var chil = $('#bar .foo');

Natively

var el   = document.querySelector('#bar');

var chil = el.querySelectorAll('.foo');

or

chil = document.querySelectorAll('#bar .foo');

Relational selectors

  1. item 1
  2. item 2
  3. item 3
    • item a
    • item b
    • item c
  4. hasaclass
  5. item 5
  6. item 6
  7. item 7
ul li,
ol li
descendant selector
matches nested <li>s
ol > li
child selector 
matches <li>s in <ol> but not nested <ul>
li.hasaclass + li
adjacent sibling 
NEW  (IE7+)
li.hasaclass ~ li
general sibling selector
matches later siblings, but not nested.

In case you were wondering...

function hasaclass(selector){
  var i = j = 0,
  elements = document.querySelectorAll('.current .ex li'),
  update = document.querySelectorAll('.current .ex ' + selector);

  for (; i < elements.length; i++){
    elements[i].classList.remove('active');
  }

  for (; j < update.length; j++){
    update[j].classList.add('active');
  }

}      

Lots 'o Selectors

  • *
  • E
  • .class
  • #id
  • E F
  • E > F
  • E + F
  • E[attribute]
  • E[attribute=value]
  • E[attribute~=value]
  • E[attribute|=value]
  • :first-child
  • :lang()
  • :before
  • ::before
  • ::selection
  • :after
  • ::after
  • :first-letter
  • ::first-letter
  • :first-line
  • ::first-line
  • E[attribute^=value]
  • E[attribute$=value]
  • E[attribute*=value]
  • E ~ F
  • :root
  • :last-child
  • :only-child
  • :nth-child()
  • :nth-last-child()
  • :first-of-type
  • :last-of-type
  • :only-of-type
  • :nth-of-type()
  • :nth-last-of-type()
  • :empty
  • :not()
  • :target
  • :enabled
  • :disabled
  • :checked
  • :indeterminate
  • :default
  • :valid
  • :invalid
  • :in-range
  • :out-of-range
  • :required
  • :optional
  • :read-only
  • :read-write

All supported since IE9, and all other browsers

Attribute selectors

element[attribute]
Select elements containing the named attribute
img[alt] {}
     <img src="image.jpg" alt="accessible">
     <img src="image.jpg" title="inaccessible">
form [type] {}
     <input type=date>
     <select>

IE6 sucks 
IE7 support basic non-empty attribute

Note: Multiple attributes work! a[title][href]

Older attribute selectors

E[attr]
Element E that has the attribute attr with any value.
E[attr="val"]
Element E that has the attribute attr with the exact, case-sensitive if attribute is case sensitive, value val.
E[attr|=val]
Element E whose attribute attr has a value val or begins with val- ("val" plus "-").
p[lang|="en"]{/*<p lang="en-us">  <p lang="en-uk"> */ }
E[attr~=val]
Element E whose attribute attr has within its value the space-separated full word val.
a[title~=more] {/* <a title="want more info about this?">}

CSS3 Attribute Selectors

E[attr^=val]
Element E whose attribute attr starts with the value val.
a[href^="mailto:"] {background-image: url(emailicon.gif);}
a[href^=http]:after {content: " (" attr(href) ")";}
E[attr$=val]
Element E whose attribute attr ends in val . 
a[href$=".pdf"] {background-image: url(pdficon.gif);}
a[href$=".pdf"]:after {content: " (PDF)";}
E[attr*=val]
Element E whose attribute attr matches val anywhere within the attribute. Similar to E[attr~=val] above, except the val can be part of a word.

Attribute Selectors

E[att]      {/* has the attribute at all */}

E[att=val]  {/* exact */}

E[att~=val] {/* val is a space separated word */}

E[att|=val] {/* with a dash */}

E[att^=val] {/* begins with val */}

E[att$=val] {/* ends with val */}

E[att*=val] {/* val is anywhere as a substring */}
@media print{
  abbr[title]:after {
    content: "(" attr(title) ")";
  }
  a[href^=http]:after {
    content: "(" attr(href) ")";
  }
}

Note: Multiple attributes work! a[title][href]

Structural selectors

:nth-child()

:nth-last-child()

:nth-of-type()

:nth-last-of-type()

:first-child*

:last-child

:first-of-type

:last-of-type

:only-child

:only-of-type

:root

:empty

:not(:empty)
  • Target elements on the page based on their relationships to other elements in the DOM.
  • Updates dynamically if page updates.
  • Reduced need for extra markup, classes and IDs
* CSS2 / IE8

First, last, & only

:first-child

:last-child

:first-of-type

:last-of-type

:only-child

:only-of-type

Easier to explain by example

First, last, & only

First, last and only

nth pseudo-classes

:nth-child(3n)

:nth-last-child(odd)

:nth-of-type(5)

:nth-last-of-type(3n+1) 

Target element or elements based on argument passed to the selector

  • :nth-of-type(even)
  • :nth-of-type(odd)
  • :nth-of-type(an+b)

Structural Selectors

li:first-child,
li:last-child {
  font-weight: bold;
}
li:first-of-type,
li:last-of-type{
  text-decoration:line-through;
}
li:nth-child(even) {
  background-color: #CCC;
}
li:nth-child(3) {
  color: #CCC;
}
li:nth-of-type(odd) {
  background-color: #FFF;
}
li:nth-of-type(4n) {
  color: #C61800;
}
li:nth-of-type(3n-1) {
  text-align: right;
}

  • item 1
  • item 2
  • item 3
  • item 4
  • item 5
  • item 6
  • item 7
  • item 8
  • item 9
  • item 10

Structural Selectors

  • 1
  • 1
  • 2
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
  • 4
 li:only-of-type{width: 100%;}
 li:nth-of-type(1):nth-last-of-type(2),
 li:nth-of-type(2):nth-last-of-type(1){width: 50%;}
 li:nth-of-type(1):nth-last-of-type(3),
 li:nth-of-type(3):nth-last-of-type(1),
 li:nth-of-type(2):nth-last-of-type(2){width: 33.33%;}
 li:nth-of-type(1):nth-last-of-type(4),
 li:nth-of-type(2):nth-last-of-type(3),
 li:nth-of-type(3):nth-last-of-type(2),
 li:nth-of-type(4):nth-last-of-type(1){width: 25%;}

:not - Negation pseudo-class

 div:not(.excludeMe)
  • The :not has no value in terms of specificity weight, but parameter selector does

:not - Negation pseudo-class

Structural Selectors

UI pseudo-classes

Based on current state of UI

:enabled
:disabled
:checked
:invalid
:required
:optional
:in-range
:out-of-range
:read-only
:read-write
:default

Example:

input[type=checkbox]:checked + label {
  color: red;
}

UI selectors

UI Selectors

Test them out for yourselves

Other Pseudo Classes

  :lang
  :target
  :empty
  

link & user action pseudo-classes

  :link
  :visited

  :hover
  :active
  :focus
  

:target pseudo-class

:target example

:root

:root

Selects the document root, which is <html>

  • Declare font-size on :root if using rem units
  • Style :root only if showing <head> (as in our exercise files)
  • In CSS4, define Defining Variables on root. (see Variables module)

example

Pseudo elements

Pseudo elements

::first-line
::first-letter
::selection (not in specification)
::before
::after
    

Pseudo-classes select elements that already exist.
Pseudo-elements create "faux" elements you can style.

Use single colon because of IE

::before and ::after

p:before {
  content: "before content - ";
  font-weight: bold;
}
p:after{
  content: " - after content";
  font-weight: bold;
}
<p>the content</p>

the content

<p>
    <before>before content - </before>
        the content
    <after> - after content</after>
</p>
Try it out

Generated Content

Generated Content

Test them out for yourselves

::first-letter

You can even pretty drop-caps with :first-letter, but make sure to apply it to p:first-of-type so your site not too ugly. Code for drop cap.

p:first-of-type::first-letter {
	position: relative;
	top: 8px;
	float: left;
	font-size: 3em;
	line-height: 1;
	color: #990000;
	padding: 0 4px 2px 0;
	font-weight: bold;
}
 
Drop Cap

::first-line

First Line

::selection

.thisSlide *::selection {
   background-color: #990000;
   color: #ffffff;
}

Prefix with -moz- for Firefox
Use single colon because of IE

Disabling ::selection

.thisSlide *::selection {
   background-color: #990000;
   color: #ffffff;
}

For mobile but impacts desktop too:

.thisSlide {
  -webkit-tap-highlight-color: #bada55;
  -webkit-user-select: none;
  -webkit-touch-callout: none;
}

Specificity (SpeciFISHity)

Specificity: The less than obvious

The * selector, or global selector, has no value.

* {} 0-0-0 

Combinators, like ~, >, and + have no value

ul li {} 0-0-2
ul > li {} 0-0-2

:not has no value, but parameter selector does

.myClass:not(p) {} 0-1-1

Specificity is not inheritance

Tips

  • selectivizr.com + JS Library = JS for backward compatibility
  • jQuery $(selector) == document.querySelectorAll(selector)
  • Many pseudo-elements in the shadow DOM
    • ::-webkit-progress-bar
    • ::-webkit-inner-spin-button /outer-spin-button
    • ::-webkit-validation-bubble / arrow-clipper /arrow /message
    • ::-webkit-scrollbar
    • ::-webkit-scrollbar-button / thumb / track
  • Mozilla Pseudo-elements and pseudo-classes