More CSS

More about selectors

The C in CSS

The C is CSS stands for Cascading

Property values “cascade” down from different style sheets.

Anything we don’t explicitly style with our own CSS is styled by the default stylesheet built into the browser.

It is also possible to write your own per-user stylesheets and they can also be installed by browser extensions.

Elements can also be selected by different rules

More complex selectors

So far we have used CSS rules where the selector selects elements by their type.

h1 { font-family: sans-serif; } /* selects all h1's */

p { font-size: 16px; } /* selects all p's */

Class and id selectors

In CSS

/* a class selector starts with a . */
.warning { color: red; }

/* an id selector starts with a # */
#copyright { font-size: 12px; }

Class and id selectors

In HTML

<!-- selected by .warning -->
<p class="warning">This will be red</p>

<!-- selected by #copyright -->
<p id="copyright">This will be small.</p>

Now what happens with this

Given this CSS:

p {
  color: blue;
  font-size: 16px;
}

.warning { color: red; }

And this HTML

<p class="warning">
  What color do you think this will be? And what font size?
</p>

Specificity

The browser finds all the rules that apply to each element.

And for each property it uses the most specific rule that applies.

Roughly speaking id selectors are the most specific, class selectors next, and then element selectors.

Thus, given

p {
  color: blue;
  font-size: 16px;
}

.warning { color: red; }

The .warning selector is more specific than the p selector so the color property is set by the .warning rule.

But the font-size property is still set by the p rule.

And regular p elements will be blue.

Combinators

We can also combine rules in various ways. I’ll just mention one

ul.my-list li { color: pink; }

The selector ul.my-list means ul elements with class="my-list" and li means all li elements.

Combining them like this, with a space between them, means select li items that are enclosed in a ul with class="my-list".

Example

<ul class="my-list">
  <li>This will be pink</li>
  <li>And this too</li>
</ul>

<ul>
  <li>This will not be pink</li>
  <li>Nor this</li>
</ul>

Inheritance

Properties that are not set directly on an element will usually be inherited from an enclosing element.

For instance this CSS

body { font-size: 18px; }

will set the font-size for all elements within the body to 18px that don’t have a specific value otherwise set.

Summary

We can select elements by type, class, and id.

In HTML we use the class and id attributes to mark elements to work with class and id selectors.

We can combine selectors to select elements within other elements.

Unspecified properties are inherited from enclosing elements.