Introduction to CSS

Introduction to CSS

Welcome to my weekly blog about Cascading Style Sheets (CSS). I know, I know, it's not the most exciting topic, but I'm here to make it fun! So grab a cup of coffee and get ready to learn some CSS -- and hopefully have a few laughs along the way!

What is CSS?

CSS stands for, Cascading Style Sheets.

A style sheet language for describing the rendering of structured documents (such as HTML and XML).

  • Supports rendering on different devices, such as screens, printers, and Braille devices.

Separates the presentation style of documents from the content of documents.

  • Thus, simplifies web authoring and site maintenance.

Development

Developed by the CSS Working Group of W3C.

Levels

CSS does not have versions in the traditional sense, instead it has levels:

  • CSS Level 1
  • CSS Level 2
  • CSS Level 3

Each level of CSS builds on the previous, refining definitions and adding features.

See: Levels, snapshots, modules... https://www.w3.org/Style/2011/CSS-process.en.html

CSS Level 1

Specification:

CSS Level 2

Is defined by the CSS2.1 specification (a single document):

  • Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification (W3C Recommendation, 7 June 2011) https://www.w3.org/TR/CSS21/
  • Its revision is currently under development:
CSS Level 3

Is currently under development.

Has a modular structure:

  • Is broken into modules, where each module defines a part of CSS.
    • Each module adds functionality and/or replaces part of the CSS2.1 specification.
  • Modules also have levels.
    • Modules with no CSS Level 2 equivalent start at Level 1.
    • Modules that update features that existed in CSS Level 2 start at Level 3.

Different CSS modules are at different levels of stability.

CSS Level 4 and Beyond

There is no CSS Level 4.

Independent modules can reach level 4 or beyond, but CSS the language no longer has levels.

“CSS Level 3” as a term is used only to differentiate it from the previous monolithic versions.

Box Model

Relevant specification:

CSS takes a source document, organized as a tree, and renders it onto a canvas (such as the screen) generating an intermediary structure, the box tree, which represents the formatting structure of the rendered document.

Each box in the box tree represents a corresponding element (or pseudo-element) from the document in space and/or time on the canvas.

For each element, CSS generates zero or more boxes as specified by that element’s display property.

  • Typically, an element generates a single box.

image

Characters

CSS uses the Unicode character set.

Escape Sequences

Unicode characters can be specified with escape sequences of the form \hhhhhh, where hhhhhh is a sequence of one to six hexadecimal digits representing the code point of the Unicode character.

  • If the number of hex digits is less than six and a character in the range [0-9a-fA-F] follows the hexadecimal number, then a whitespace character must end the escape sequence.
    • A whitespace character that immediately follows an escape sequence will be ignored.

Examples:

  • \9, \09, ..., \000009 denote the vertical tab character.
  • \A9, \0A9, ..., \0000A9 denote the copyright symbol (©).

Special characters can be escaped with a '\' character.

  • For example, it is required when a selector contains an element name that contains '.' characters.

Comments

Comments can be placed between the /* and */ delimiters.

Example:

  • /* Style sheet for index.html */

Can occur anywhere but in tokens. And also Cannot be nested.

Declaration Blocks

Start with a '{' character and end with a '}' character, in between there must be a list of zero or more declarations.

  • Declarations are of the form name:value, where whitespace characters are allowed before and after tokens.
    • In a declaration name is an identifier.
  • Declarations must end with a ';' character.
    • The ';' character after the last declaration can be omitted.

image

at-rules

Define special processing rules or values.

Start with a '@' character, followed by an identifier and includes everything up to the next ';' character, or the next declaration block.

Examples: @charset, @import, @namespace, @media

See: https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule

Rule Sets (Style Rules)

Consist of a selector (or a list of selectors separated with a ',' character) followed by a declaration block.

Properties

Parameters defined by CSS for controlling the rendering of documents. Properties have names and values.

The list of CSS properties: https://www.w3.org/Style/CSS/all-properties.en.html

  • The total number of distinct property names is 548.

Shorthand property: A property that allows authors to specify the values of several properties simultaneously.

For example, the margin property is a shorthand property for setting the value of the margin-top, margin-right, margin-bottom, and margin-left properties.

Selectors

Type Selector

Written as a CSS qualified name, generally, an identifier. Matches the elements of that name.

Examples:

p { color: red }
a { text-decoration: none }
Universal Selector

Written as *. It matches all elements. May be omitted from a simple selector, if it is not the only component.

  • Thus, for example, the following selectors are equivalent:
    • *#nav and #nav
    • *.important and .important
    • *[title] and [title]
Attribute Selectors
  • [att]
    • Matches elements with the att attribute.
  • [att=val]
    • Matches elements with the att attribute whose value is exactly val.
  • [att~=val]
    • Matches elements with the att attribute whose value is a whitespace-separated list of words, one of which is exactly val.
  • [att|=val]
    • Matches elements with the att attribute, its value either being exactly val or beginning with val-.
    • Primarily intended to be used for attributes whose value is a language tag, for example, en-US, en-GB.
      • For the xml:lang attribute and the HTML lang attribute the :lang(C) pseudo-class should be used.

Additional attribute selectors introduced by CSS3:

  • [att^=val]
    • Matches elements with the att attribute whose value begins with the prefix val.
  • [att$=val]
    • Matches elements with the att attribute whose value ends with the suffix val.
  • [att*=val]
    • Matches elements with the att attribute whose value contains the substring val.

In each attribute selector, val must be a CSS identifier or a string.

  • Thus, for example, the [dir=rtl], [dir='rtl'], and [dir="rtl"] selectors are equivalent.

Examples:

style[type=italic] {
  font-style: italic;
}

style[type=bold] {
  font-weight: bold;
}

style[type=normal] {
  font-style: normal;
  font-weight: normal;
}

a[hreflang|=en] {
  text-decoration: line-through;
}
Class Selector

For HTML documents, the attribute selector [class~=val] is equivalent with the selector .val.

Examples:

div.centered {
  margin-left: auto;
  margin-right: auto;
}

.important {
  color: red;
  text-decoration: underline;
}
ID selector

A selector of the form #identifier matches the element with that identifier.

The identifier must be provided by an attribute of type ID in the document.

  • The name of such an attribute depends on the document language, for example, in HTML the attribute is named id.

Examples:

div#main {
  width: 50%;
  margin-left: auto;
  margin-right: auto;
}

#footer { text-align: center }
Pseudo-classes

Dynamic pseudo-classes:

An element may acquire or lose a dynamic pseudo-class while a user interacts with the document.

  • Link pseudo-classes:
    • :link : applies to links that have not yet been visited.
    • :visited: applies to links that have been visited by the user.
  • User action pseudo-classes:
    • :hover: applies while the user designates an element with a pointing device, but does not necessarily activate it.
    • :active: applies while an element is being activated by the user.
      • For example, between the times the user presses the mouse button and releases it.
    • :focus: applies while an element has the focus (accepts keyboard or mouse events, or other forms of input).

Examples:

:link {
  border-width: medium;
  border-style: solid;
  text-decoration: none;
}
:visited {
  text-decoration: line-through
}
a:hover {
  text-decoration: overline underline;
  color: red;
}
a:active { font-weight: bolder }

The :lang(C) pseudo-class:

  • Represents elements that are in language C.
    • C is a CSS identifier (language code).
  • Examples:
    • :lang(en), :lang(en-GB), :lang(en-US)
    • :lang(hu)
  • In XML documents the language used is defined by the xml:lang attribute. In HTML documents the language can be specified with the both the lang and the xml:lang attributes.
    • The lang and xml:lang attributes are not necessarily occur directly on an element.

Example: Hungarian quotation marks are used for quotations in Hungarian .

q:lang(hu) {
  quotes: "„" "”" "»" "«";
}
Structural pseudo-classes

Structural pseudo-classes:

Only elements are counted when calculating the position of an element in its list of siblings.

  • For example, text, comments, and processing instructions are ignored.

Index numbering starts at 1.

  • :root: represents the root element of the document.
  • :only-child: represents elements that have no siblings.
  • :only-of-type: represents elements that have no siblings with the same element name.
  • :empty: represents elements that have no children at all.
    • These elements do not contain any text or elements, but may contain comments and processing instructions.
  • :nth-child(an+b): where a and b are integers.
    • Represents elements that have an+b-1 siblings before it in the document, for any non-negative integer value of n.
  • :nth-last-child(an+b): where a and b are integers.
    • Represents element that have an+b-1 siblings after it in the document, for any non-negative integer value of n.
  • :nth-of-type(an+b): where a and b are integers
    • Represents elements that have an+b-1 siblings with the same element name before it in the document, for any non-negative integer value of n.
  • :nth-last-of-type(an+b): where a and b are integers
    • Represents elements that have an+b-1 siblings with the same element name after it in the document, for any non-negative integer value of n.
  • :nth-child(), :nth-last-child(), :nth-of-type() and :nth-last-of-type():
    • The argument an+0 can be specified as an in short.
    • The argument 0n+b can be specified as b in short.
    • For a negative b the argument must be specified as an-b, the form an+-b is invalid.
    • The argument 2n can be specified as even, the argument 2n+1 as odd, respectively.

image

Pseudo-elements

Pseudo-elements allow authors to refer to content in the document that is otherwise inaccessible.

  • This includes content that originally does not exist in the document (i.e., generated content).

Only one pseudo-element may appear per selector.

The following pseudo-elements are available:

  • ::first-line
  • ::first-letter
  • ::before, ::after

CSS3 uses '::' for pseudo-elements to distinguish them from pseudo-classes.

  • For compatibility ':' can be used also.

::first-line: represents the first formatted line of an element.

Example:

p::first-line {
  text-decoration: underline
}

::first-letter: represents the first letter or digit of an element, if it is not preceded by any other content (such as images) on its line.

Also applies to any punctuation character that precedes or follows the first letter.

Example:

p::first-letter {
  font-size: 2em;
  font-weight: bold;
}

::before and ::after: can be used to describe generated content before or after an element’s content.

Example:

div.proof::before {
  content: "Proof: ";
  font-weight: bold;
}
div.proof::after {
  content: "\220E" /* End of proof */
}
Descendant combinator

Whitespace that separates two sequences of simple selectors.

If P and Q are two sequences of simple selectors, the selector P Q represents elements matching Q that are descendants of elements matching P.

Example:

thead th { background-color: darkgrey }

Child combinator: A '>' character that separates two sequences of simple selectors

If P and Q are two sequences of simple selectors, the selector P > Q represents elements matching Q that are children of elements matching P.

Example:

nav > div { display: inline }
p > img:only-child { margin-left: 0 }

Next-sibling combinator:

A '+' character that separates two sequences of simple selectors.

If P and Q are two sequences of simple selectors, the selector P + Q represents elements matching Q that immediately follow an element matching P.

  • The elements represented by the two sequences share the same parent in the document.
  • Non-element constructs (e.g., text and comments) are ignored when considering adjacency of elements.

Example:

h1 + p { text-indent: 0 }
Specificity

For each selector and declaration a specificity is calculated, which is a vector (a, b, c) of length 3, where a, b, and c are non-negative integers.

The vectors are sorted in lexicographic order.

A selector's specificity is calculated as follows: the specificity of the selector is a vector (a, b, c), where:

  • a is the number of ID selectors in the selector.
  • b is the number of class selectors, attribute selectors, and pseudo-classes in the selector.
    • Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class!
  • c is the number of type selectors and pseudo-elements in the selector.

Specificity of a declaration:

  • Each declaration has the same specificity as of the selector of the style rule it appears in.
  • Declarations that do not belong to a style rule (such as the contents of a style attribute in HTML) are considered to have a specificity higher than any selector.
Calculating a Selector's Specificity

The specificity of the selector * is (a = 0, b = 0, c = 0).

  • Because it does not contain any ID selectors, class selectors, attribute selectors, pseudo-classes, type selectors, or pseudo-elements.

The specificity of the selector div is (a = 0, b = 0, c = 1).

The specificity of the selector p::first-letter, a img, and h1 + p is (a = 0, b = 0, c = 2).

The specificity of the selector div[class=nav] and the equivalent selector div.nav is (a = 0, b = 1, c = 1).

The specificity of the selector #main *:lang(en) is (a = 1, b = 1, c = 0).

Stylesheet origins

Multiple stylesheets of different origins may belong to a document.

Stylesheets may have three different origins:

  • User agent
  • User
  • Author

Origins are listed in increasing order of precedence.

User agent stylesheets

User agents must apply a default stylesheet.

  • For example, they provide a style rule specifying that the content of the HTML em element is presented using an italic font.

Firefox: the default stylesheet can be accessed as follows:

Chromium, Google Chrome: the default stylesheet to render HTML documents:

User stylesheets

The user may be able to specify style information for a particular document.

  • This is important to people with disabilities.
  • The Stylish extension for the Chromium, Google Chrome, Firefox, and Opera browsers provides such functionality. https://userstyles.org/
  • Author stylesheets

In (X)HTML the link element associates an external stylesheet with the document.

Example:

<link rel="stylesheet" href="style.css"/>

In (X)HTML the style element allows the direct embedding of style rules in the document.

Example:

<style>
  h1, h2, h3, h4, h5, h6 { font-variant: small-caps }
</style>

In XML the xml-stylesheet processing instruction associates an external stylesheet with the document.

Example:

<?xml-stylesheet type="text/css" href="style.css"?>

See: Associating Style Sheets with XML documents 1.0 (Second Edition) (W3C Recommendation, 28 October 2010) https://www.w3.org/TR/xml-stylesheet/

Cascade

Several different declarations can set the value of the same variable.

  • These declarations can be of different origins.

The cascade is the process during which it is determined which declaration sets the value of a given property of a given element.

The cascade determines the cascaded value of a property for an element as follows:

  • The declarations that set the value of a property for the element are identified and collected.
    • Remember that these declarations are provided by style rules or the style HTML attribute.
  • These declarations are sorted by decreasing origin.
  • Declarations of the same origin are sorted by decreasing specificity.
    • In case of equal specificity the last declaration in document order wins.
  • The value of the property is set by the first declaration according to this order.

Rule Ordering

The ordering of style rules may be significant.

The ordering is significant when more than one style rule with the same specificity applies to an element.

In this case, the last declaration in document order wins.

For example, the first two rules will never be taken into account here:

a:active { color: red } /* (a = 0, b = 1, c = 1) */
a:hover { color: green } /* (a = 0, b = 1, c = 1) */
a:visited { color: black } /* (a = 0, b = 1, c = 1) */
a:link { color: blue } /* (a = 0, b = 1, c = 1) */

The correct order of these rules is the following (the first two rules are interchangeable):

a:visited { color: black }
a:link { color: blue }
a:hover { color: green }
a:active { color: red }

Inheritance

Inheritance propagates property values from parent elements to their children.

Some properties are inherited, this means that, unless the cascade results in a value, the value will be determined by inheritance.

For each property, the relevant CSS specification defines whether it is inherited or not.

  • For example, the font-family, font-style, font-variant, font-weight, font-size, and font properties are inherited.
  • For example, the margin-top, margin-bottom, margin-right, margin-left, margin, and width properties are not inherited.

If the cascaded value of a property is the inherit keyword, the inherited value becomes the property’s specified and computed values.

Example:

  • When no rules apply to the em HTML element below that set the value of the color property, the element inherits the value of the property from the span element (red).
<span style="color: red">
  May the <em>Force</em> be with you!
</span>

Example:

When the style rule below applies, a hyperlink inherits the value of the color property from it's parent. Thus, for example, the value of the color property of the a element in the div element is green.

a:visited, a:link {
  color: inherit
}

<p style="color: green">
  Click here: <a href="https://www.w3.org/">W3C</a>
</p>

Initial Value

Each property has an initial value, defined in the relevant CSS specification. The initial value can be defined to depend on the user agent.

If the property is not an inherited property, and the cascade does not result in a value, then the specified value of the property is its initial value.

If the cascaded value of a property is the initial keyword, the property’s initial value becomes its specified value.

Conclusion

So there you have it! Cascading Style Sheets are an important tool for web designers and developers and can help you create awesome websites. Just remember: don't get too carried away or you might find yourself in a sticky situation...literally!

Did you find this article valuable?

Support Mojtaba Maleki by becoming a sponsor. Any amount is appreciated!