M1D5: CSS

Tags

Connects the CSS to the HTML.

  • ID – append with #
  • Class – append with a period
  • Type – no append

For example:

HTML

<p>This is a paragraph that I will change to red using CSS.</p>

CSS

p { 
  color: red;
}

Classes

HTML elements can have more than just a tag name; they can also have attributes. One common attribute is the class attribute. It’s also possible to select an element by its class attribute.

HTML

<p class="brand">Sole Shoe Company</p>

CSS

.brand {
  color: red;
}

IDs

For situations where you need more specificity in styling, you may also select elements for CSS using an id attribute. You can have different ids associated with a class (although a class is not required).

HTML

<p id=”solo” class="brand">Sole Shoe Company</p>

CSS

#solo {
  color: purple;
}

Pseudo-classes

A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s).

:hover
:visited
:before

selector:pseudo-class {
  property: value;
}

/** Example - Hover **/
a:hover {
  color: blue
}
/** This changes the color of the link when mouse is hovered over it **/

For more information on pseudo-classes, see the Mozilla Dev Docs here.

Attributes

Attribute selectors are a special kind of selector that will match elements based on their attributes and attribute values.

Their generic syntax consists of square brackets ([]) containing an attribute name followed by an optional condition to match against the value of the attribute.

Attribute selectors can be divided into two categories depending on the way they match attribute values:

  1. Presence and value attribute selectors and
  2. Substring value attribute selectors.

These attribute selectors try to match an exact attribute value:

  • [attr] This selector will select all elements with the attribute attr, whatever its value.
  • [attr=val] This selector will select all elements with the attribute attr, but only if its value is val.
  • [attr~=val] This selector will select all elements with the attribute attr, but only if val is one of a space-separated list of words contained in attr’s value. (This one is a bit more complex, so checking some documentation might be helpful.)

For example:

img[alt] 
/* This selector will select all images with the alt attribute, regardless of it's value. */

Multiple Selectors

h1 {
  font-family: "Helvetica", "Arial", sans-serif;
}

h2 {
  font-family: "Helvetica", "Arial", sans-serif;
}

h3 {
  font-family: "Helvetica", "Arial", sans-serif;
}

h4 {
  font-family: "Helvetica", "Arial", sans-serif;
}

h5 {
  font-family: "Helvetica", "Arial", sans-serif;
}

h6 {
  font-family: "Helvetica", "Arial", sans-serif;
}

We can write the above into this:

h1, h2, h3, h4, h5, h6 {
  font-family: "Helvetica", "Arial", sans-serif;
}
This entry was posted in Study Notes and tagged , . Bookmark the permalink.

Leave a Reply