Web Application Development

Jakub Klinkovský

:: Czech Technical University in Prague
:: Faculty of Nuclear Sciences and Physical Engineering
:: Department of Software Engineering

Academic Year 2024-2025

Cascading Style Sheets (CSS)

Motivation

  • HTML is suitable for describing the structure of a document – it is not intended for describing appearance (although historically this was not always the case).
  • The effort to separate presentation (appearance) from structure of web pages lead to the development of CSS.

Why use a separate definition of appearance (CSS):

  • clearer management of website content – shorter and simpler code,
  • easy to change the appearance (editing CSS, not rewriting the document itself).

Further advantages are brought by defining the style in a separate file:

  • unified appearance of all website pages (sharing CSS files for all pages),
  • it is possible to easily change the appearance and layout of all website pages – it is enough to edit the style definition in one place.

CSS History in a Nutshell

CSS1 (CSS level 1) – 1996-2018 – together with HTML 4.0 (no longer supported)

CSS2 (CSS level 2) – specification 1998

  • CSS 2.1 (CSS level 2 revision 1) – specification 2011
  • CSS 2.2 (CSS level 2 revision 2) – unofficial Working Draft from 2016

CSS3 (CSS level 3) – development from 1999, division into modules extending CSS2

Current State of CSS

  • CSS3, CSS4 etc. are "popular" terms, in practice it is all "CSS without a number"
  • some modules have numbers, e.g. CSS Color Level 5
  • support for newer CSS elements in browsers needs to be checked separately, e.g. using https://caniuse.com/
    (or reference manuals W3Schools and MDN Web Docs contain sections "Browser support" resp. "Browser compatibility" for each CSS property)
  • CSS definitions can be used for various markup languages: HTML, XML, SVG, MathML3
  • can be considered a Turing-complete language 😎

CSS Syntax

Style definitions or individual CSS rules always contain two parts: a selector and a list of appearance declarations inside curly braces:

selector {
  declaration1;
  declaration2;
}
  • declarations are terminated by a semicolon (only after the last declaration it may be omitted)
  • each declaration consists of a pair property : value (property : value)
  • after the pair property : value can follow !important (see below)
  • comments are written between tokens /* and */: e.g. /* comment */
  • the placement of white space (space, end of line, etc.) does not matter
    (note: space is used for combining selectors and values for certain properties)

Simple CSS Examples

Rule with one declaration (for the p tag – paragraph):

p {
  text-align: center;
}

Rule with two declarations (for the h1 tag – heading level 1):

h1 {
  font-size: 120%;
  color: blue;
}

Declarations

When declaring a style, any of the allowed properties (and their values) can be used depending on the type of element (selected by the selector).

Allowed properties and values

  • depends on the given element – unfortunately, not much can be said about them in general...
    • each element has its set of allowed properties
    • each property has its set of allowed values
  • you can use a "prompt" in the browser
  • reference manuals: e.g. W3Schools, MDN Web Docs

"General" Values – Numerical Quantities

For many properties, a numerical value with a corresponding unit (e.g. %, px, em, ex, in, cm, mm; s, ms; Hz, deg, ...) can be used. Numbers can be whole or decimal (with a decimal point), with or without a sign.

Note: there must be no space between the number and the unit!

Percentage Values

They always relate to another reference value, based on which the actual size is calculated ⇒ be aware of the reference value when specifying percentages!

Example: line height (line-height) relates to font size (font-size), so when declaring line-height: 120% and font size 10px (pixels), the line height will be 12px.

"General" Values – Font Families

General font families (generic font families) for the font-family property: we should always specify one of the five general font families in case the browser does not have any of the specified fonts available. Fonts specified earlier take precedence, i.e. the general font family is written after the specific font family.

Value Meaning (example) Primary Purpose
sans-serif sans-serif font (Arial, Helvetica) monitor
serif serif font (Times) printing on paper
monospace non-proportional font (Courier) source code

Examples: CSS Web Safe Fonts or CSS: fonts

"General" Values – Font Sizes I

Absolute size (absolute size) for the font-size property:

value multiple idea
xx-small 3/5 size of h6
x-small 3/4
small 8/9 size of h5
medium 1 size of h4
large 6/5 size of h3
x-large 3/2 size of h2
xx-large 2 size of h1

"General" Values – Font Sizes II

Relative size (relative size) for the font-size property:

value meaning
larger one level larger
smaller one level smaller

Example: if the parent element has a size of large and we set smaller for the child, then the child will have a size of medium.

Colors I

Colors (for properties containing the word color) in CSS are most commonly specified:

  • by name: e.g. 16 basic colors, more at MDN Web Docs:

  • using RGB notation (mixture of red, green, and blue)

notation r, g, b values example (yellow)
#rgb 0,1,...,9,A,B,...,F #FF0
#rrggbb hexadecimal (00-FF) #FFFF00
rgb(r, g, b) decimal (0-255) rgb(255,255,0)
rgb(r%,g%,b%) percentage (0-100%) rgb(100%,100%,0%)

Colors II

Names of 16 basic colors:

Selectors

A selector (selector) ensures the binding to the corresponding HTML element (basically, it determines which elements of the web page the declared properties will be applied to). Selectors can be combined in various ways (see slide Combining Selectors).

Basic selectors:

  1. universal selector: *
  2. type selector: E, where E is the name of some element (HTML tag)
  3. class selector: .C, where C is the name of a class (value of the class attribute)
  4. ID selector: #I, where I is a unique ID used in the document (of the id attribute)
  5. attribute selector: [A], [A⊗value], [A⊗value i], [A⊗value s],
    where A is the name of an attribute, is some operator, and value is some value

Universal Selector

  • syntax: * (in simple cases it can be omitted, see later)
  • selects all elements

Example: setting the font color to red on the entire page

* {
  color: red;
}

Type Selector

  • syntax: E, where E is the name of some element (HTML tag)
  • e.g. the h3 selector affects the appearance of all h3 tags (all level 3 headings)
  • this is the most commonly used selector

Example: setting the font color to red for all level 1 headings

h1 {
  color: red;
}

Class Selector

  • syntax: .C, where C is the name of a class
  • selects tags with the given value of the class attribute
  • used when we want to display the given type of elements differently in different occurrences

Example: setting the font color to red for elements in the warning class

.warning { color: red; }

Example document:

<p class="warning">Lorem ipsum dolor sit amet, ...</p>

Note: combination with a type selector: e.g. p.warning

ID Selector

  • syntax: #I, where I is a unique ID used in the document (value of id attribute)
  • styling a single element only makes sense in the case of an exception (otherwise, we lose the ability to easily edit the appearance of the web page)

Example: setting the font color to red for the element with ID lorem-ipsum

#lorem-ipsum { color: red; }

Example document:

<p id="lorem-ipsum">Lorem ipsum dolor sit amet, ...</p>

Note: combination with a type selector (e.g. section#lorem-ipsum) makes sense when sharing CSS for multiple documents

Attribute Selector

  • syntax: [A], [A⊗value], [A⊗value i], [A⊗value s],
    where A is the name of an attribute, is some operator, and value is some value
  • valid operators: =, ~=, |=, ^=, $=, *=
  • the characters i and s before the closing bracket enforce either case-insensitive or case-sensitive behavior (distinguishing between uppercase and lowercase letters) – by default, it depends on the markup language used

Example: the *[lang] or just [lang] selector selects all elements that have the lang attribute set (e.g. <body lang="en"> and <p lang="en">, but not <p>)

Example: the a[title] selector selects all links with the title attribute

Attribute Selector – Examples of Operators I

Example:
the a[href="https://example.org"] selector selects all links whose target is exactly equal to "https://example.org"

Example:
the a[href*="example"] selector selects all links whose target contains "example"

Example:
the a[href$=".org"] selector selects all links whose target ends with ".org"

Example:
the a[href^="https://"] selector selects all links whose target starts with "https://"

Attribute Selector – Examples of Operators II

Example: the a[href^="https://"][href$=".org"] selector selects all links whose target starts with "https://" and ends with ".org"

Example: the a[class~="logo"] selector selects all links whose class attribute contains the word "logo"
Note: the ~= operator assumes that the attribute contains a list of words separated by spaces

Example: the p[lang|="en"] selector selects all paragraphs whose lang is exactly equal to "en" or starts with the string "en-" (e.g. "en-US", "en-GB")

Combining Selectors

Selectors can be combined in several ways:

  1. grouping: A, B selects elements corresponding to the selector A or B
    (union of sets of elements corresponding to A and B)
    e.g. h1, h2, h3, h4, h5, h6 for unified styling of all headings
  2. chaining: AB – intersection of sets of elements corresponding to A and B
    e.g. *.classname, body.classname, .class1.class2, .classname#idname, a[href^="https://"][href$=".org"]
  3. combining: A⊗B, where ⊗ is some operator (combinator)

Combining Selectors – Next Sibling

Example: how to style only the first paragraph after the heading?

<section>
  <h1>Heading</h1>
  <p>First paragraph</p>
  <p>Second paragraph</p>
  ...
</section>

E.g. with this CSS rule:

h1 + p {
  color: red;
}

Combining Selectors – General Sibling

Example: how to style all paragraphs following the heading?

<section>
  <p>This won't be red</p>
  <h1>Heading</h1>
  <p>This will be red</p>
  <h2>Subheading</h2>
  <p>This will also be red</p>
</section>

E.g. with this CSS rule:

h1 ~ p {
  color: red;
}

Combining Selectors – Child

Example: how to style all paragraphs that are children of a section?

<section>
  <h1>Heading</h1>
  <p>Selected paragraph...</p>
  <article>
    <p>Unselected paragraph...</p>
  </article>
  ...
</section>

E.g. with this CSS rule:

section > p {
  color: red;
}

Combining Selectors – Descendant

Example: how to style nested lists?

/* rule for first-level bullets */
li {
  list-style-type: disc;
}

/* rule for second-level bullets */
li li {
  list-style-type: circle;
}

Pseudo-classes I

Pseudo-classes are keywords used in selectors that specify a special state of a selected element. We will show only selected examples.

  • Pseudo-classes of links (used for the a tag):

    • :link – not yet visited link
    • :visited – already visited link
    • :any-link – any link (:link or :visited)
  • Pseudo-classes of user action – take into account the current interaction with the user

    • :active – activated element (e.g. click)
    • :hover – element being hovered

Note: when chaining, the order matters – typically, the order on this slide is appropriate.

Pseudo-classes II

  • Functional pseudo-classes:
    • :is(S1, S2, ...) – selects elements that correspond to any of the specified selectors (suitable for simplifying complex selectors)
    • :not(S) – selects elements that do not correspond to the selector S
    • 🆕 :has(R) – selects elements for which the relative selector R selects at least one element: e.g. h1 + h2 vs h1:has(+ h2)

Pseudo-classes III

  • Pseudo-classes that follow the document tree:
    • pseudo-class :root – root element of the document (for HTML, this is <html>)
    • :empty – empty element of the document (has no content or children)
    • the following pseudo-classes select elements based on their order among siblings:
      • :first-child (first), :last-child (last), :nth-child(n) (n-th), :nth-last-child(n) (n-th from the end), :only-child (only child)
      • n can be a natural number, even, odd, or even a polynomial in the form an+b, where a and b are integers
      • use: e.g. for tables and lists
    • by replacing the word child with of-type, we get pseudo-classes that relate to the order among siblings of the same type

Pseudo-elements

Pseudo-elements are keywords that allow styling parts of actual elements. To distinguish them from pseudo-classes, they contain a colon (::).

Examples of pseudo-elements:

  • ::first-line denotes the first line of a block element (according to how it is displayed in the browser)
  • ::first-letter denotes the first letter (called an "initial") of the selected element
  • ::before denotes the place before the beginning of the selected element
    (example of use: numbering headings)
  • ::after denotes the place after the end of the selected element

Further Information on Selectors

Cascading Algorithm

The cascading algorithm determines how style declarations from different sources are combined. For each property, the most relevant declaration is used. The selection is influenced by:

  1. Origin of the style definition
    • from the author of the page (CSS definition) – highest weight
    • from the user (they set their own formatting in the browser)
    • from the browser manufacturer (default settings) – lowest weight
  2. Specificity of the selector – compared in several categories according to the type of selector
    (ID  >  class, attribute, pseudo-class  >  type, pseudo-element  >  universal)
  3. 🆕 @layer and @scope
  4. Order of declaration: if the previous ones did not decide, the latest rule is used.

Cascading Algorithm – Examples and Exceptions

Examples of specificity:

#myElement {
  /* specificity 1-0-0 */
}
.bodyClass .sectionClass .parentClass [id="myElement"] {
  /* specificity 0-4-0 */
}
p {
  /* specificity 0-0-1 */
}
p.warning {
  /* specificity 0-1-1 */
}
  • The importance of a declaration can be increased by using !important (reversing the cascade). E.g. h1 {color: red !important}
  • Separate rules for advanced properties (@keyframes and transition)

Inheritance

CSS has the concept of inheritance – most properties (especially font size, color, etc.) are inherited from the parent element. If an element does not have a property defined, it inherits it from its parent.

Tip: if you want to define a property common to all elements, define it for the body element. Then you can set exceptions (see cascading algorithm).

initial and inherit Values

The initial value represents the initial value of a property before applying the rules. It can also be explicitly enforced ("resetting" the property).
The inherit value declares that the element inherits the property from its parent. This value can also be used for properties that are not normally inheritable.

Example: h1 {font-size: inherit;}

Further Concepts

Practical Use of CSS

CSS Examples

Reference manuals with demo examples for certain properties:

Further Tips:

  • many examples and "real-world solutions" can be found on StackOverflow
  • JSFiddle allows you to test your own HTML + CSS + JavaScript directly in the browser
  • Firefox, Google Chrome: Developer Tools (Ctrl+Shift+I), then right-click on some element of the web page and select "inspect".

How to Add CSS to a Web Page?

Style definitions can be added to a web page in three ways:

  1. by connecting an external file (typically with the .css extension) to the page (in HTML, e.g. using the link tag),
  2. by writing CSS definitions directly into the document header (paired style tag),
  3. by adding the style attribute to any HTML tag.

The first method is the most advantageous (easy maintenance of the appearance of the entire website, minimizing data downloads, etc.)

Example of Connecting CSS I

  1. Connecting an external file with style definitions (e.g. styl.css) to a web page (inside the head tag):
    • using the link tag:

      <link href="filename.css" rel="stylesheet" type="text/css" >
      
    • inside the style tag:

      <style type="text/css" >
        @import "filename.css";
      </style>
      

      Note: if the CSS file is located on another server, you can use the following notation: @import url("http://www.xxx.cz/yyy.css");

Example of Connecting CSS II

  1. Writing style definitions into the document header (paired style tag):

    <style type="text/css" >
      body {color: blue}
      h1 {color: navy}
    </style>
    
  2. Assigning a style directly to some element (suitable only for exceptional cases, otherwise it is unnecessarily laborious and non-universal!):

    <h1 style="color: green" >heading</h1>
    

Resetting Styles

When designing web projects, the first step is often to reset the default styles. This ensures consistency in the display on various browsers and creates a clean state from which to build the new project.

More during the class 😉

Media Queries I

The @media block is used to limit the application of CSS rules based on certain conditions, typically the capabilities of the device (e.g. viewport size). Inside the block, regular CSS selectors are written. The @media keyword is followed by the device type and/or conditions, and a block of CSS rules.

Example:

body {
  background-color: pink;
}

@media screen and (min-width: 480px) {
  body {
    background-color: lightgreen;
  }
}

Media Queries II

Device types in CSS3:

  • all = all devices
  • print = printers (i.e. appearance for printing)
  • screen = screens (computers, tablets, smartphones, ...)

Most commonly used "capabilities" (media features):

  • max-width = maximum width of the viewport (e.g. browser window)
  • min-width = minimum width of the viewport (e.g. browser window)

There are dozens of "capabilities", see e.g. MDN Web Docs

Media Queries III

Try it out:

Further information:

Responsive Web Design I

Responsive web design (RWD) is about the optimal layout of a web page when displayed on various types of devices. Most often, it addresses the following factors: page layout, position and behavior of navigation menus, and image sizes.

RWD uses:

General information about RWD: w3schools, MDN Web Docs

Responsive Web Design II

How to test RWD:

  • Firefox, Google Chrome: Developer Tools (Ctrl+Shift+I), then there is an icon for displaying on mobile devices (Ctrl+Shift+M). Alternatively, right-click on an element of the web page and select "inspect".
  • Am I Responsive?

Frameworks and Libraries for Web Development

CSS Preprocessors

CSS preprocessors are styling languages that are "compiled" into CSS. Compared to CSS, they provide more advanced features and/or simpler, more readable syntax.

Examples: LESS, SASS, Stylus.

Introductory articles:

Frameworks for HTML and CSS

Libraries that enable quick web design. They provide a unified/standard appearance and layout, but can be configured, extended, or customized to your needs.

Examples: (free and open-source)

More information on Wikipedia

- English manuals (current): [W3Schools](https://www.w3schools.com/cssref/index.php) ([examples](https://www.w3schools.com/css/css_examples.asp)), [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference#index) - older Czech materials: - [JakPsatWeb](https://www.jakpsatweb.cz/css/css-vlastnosti-hodnoty-prehled.html) (approx. CSS 2.1) [alphabetical list](https://www.jakpsatweb.cz/css/vlastnosti.html), [examples](https://www.jakpsatweb.cz/css/priklady/index.html) - [WebTvorba](http://www.webtvorba.cz/css/css-vlastnosti.html) (max. CSS 2.1) - [Kosek](https://www.kosek.cz/clanky/web/css-ref.html) (CSS1), newer on [htmlguru](http://htmlguru.cz/css.html)

- Pseudo-classes for working with forms (continued) - `:in-range` – elements whose value is within the specified range - `:out-of-range` – elements whose value is outside the specified range - `:valid` – elements whose value is correct (valid) - `:invalid` – elements whose value is incorrect (invalid) - `:read-only` – styles elements for which the `readonly` attribute is specified - `:read-write` – styles elements for which the `readonly` attribute is _not_ specified

--- ## Element Classification - block (_block_): have a line break before and after, can set width and height (e.g. `p`, `div`, `h1`, tables, and lists; see [JakPsatWeb, blocks](https://www.jakpsatweb.cz/html/bloky.html)) - inline (_inline_): are part of the text on the line, do not have a line break after (e.g. `strong`, `span`, `cite`; see [JakPsatWeb, text](https://www.jakpsatweb.cz/html/text.html)) - elements replaced by "foreign" content: the browser omits the required width and height, after loading it adds the content (e.g. `img`, `object`)

--- ## CSS Validator W3C offers an online CSS validator: http://jigsaw.w3.org/css-validator/ You can check the correctness of CSS in several ways: - by entering the URL (for the CSS file itself or for HTML including CSS) - by uploading the CSS file - by copying CSS into the form You can also specify additional options (especially the CSS version). The CSS validator is currently translated into Czech, so it is easy to use. You can read about types of errors and their causes (from the time when the validator was only in English) at http://www.webtvorba.cz/css/css-validator-w3c.html.