Internet
Seminar

Spring 2019
course
site

everything you wanted to know about css selectors

Jim on Jan 28

resources

background

First, you need to understand that an HTML document is made of

Here's a short snip of HTML with all of that: tags with types "div", "p", attributes "source", "id", "class", forming a tree with siblings and children.

<div source="Jim">
  <p class="title">This might be the title of the stuff.</p>
  <div class="important">
    <p>This is the first line, eh?<p/>
    <p id="secondline">Oh, and this is the second line.</p>
    <p class="title">Another title !??</p>
    <p class="important">Why would you want to put a title there?</p>
  </div>
</div>
div
|   \
p    div
    / | | \
   p  p p  p

Each part of a css specification has two parts : a selector, and a body with "properties" and "values".

#secondline {
    color: red;
    margin: 2em;
}

The selector is the leading part, before the curly braces. It describes a subset of the tags in the document ... in several tricky ways.

The syntax of selectors is

And you can combine selectors in several ways.

First, selectors right after each other mean that both must match

p.title       a "p" tag with class "title"
.foo.bar      a tag which has class "foo" and class "bar", i.e. <div class="foo bar">
img[alt]      image tags which have an "alt" attribute
a:hover       a link that the mouse is hovering over

Second, selectors with commas mean that the styles apply to all.

h1, p        type "h1" or "p"

Third, selectors with spaces between mean that the second is "a descendant of" the first, i.e. somewhere inside.

div span     matches a "span" which is within a "div", e.g. <div><p><span>this matches</span></p></div>

And finally, there are several other binary infix operators besides those three :

example

Here's a short example on codepen :

<!-- It's some html, eh? -->
<div copyright="cc-by-jim">
  <p class="title">This might be the title of the stuff.</p>
  <div class="importnt">
      <p>This is the first line, eh?<p/>
      <p id="secondline">And this would be the second line.</p>
      <p class="title">Another title !??</p>
      <p class="importnt">Why would you want to put a title there?</p>
  </div>
  <p style="color:green">Mouse over me ...</p>
</div>
/* It's some css, eh? */

#secondline {
  color: darkred;
  margin-left: 2em;
}

.title {
  font-weight: bold;
  font-size: 1.5em;
}

p:hover {
  color: blue;
}

p.importnt {
  font-family: sans-serif;
}

div.importnt {
  background: #ccc;
  border: solid 1px green;
}

[copyright] {
  padding: 0.5em;
  background: #eef;
}

Quick quiz: mousing over most of the paragraphs turns the text blue ... but not the last one. Why not?

Are we having fun yet?

aside