Web Application Programming

Andrea De Lorenzo, University of Trieste

Class Schedule

Day Time Room
Monday 09:30am - 11:00am Aula V - Building G
Tuesday 03:00pm - 04:30pm Aula 4D - Building H2 bis
Wednesday 01:00pm - 02:30pm Aula 4D - Building H2 bis

http://delorenzo.inginf.units.it/

Class Format

  • In-person lectures, also recorded
  • Recordings available for about 6 months in the course Team
  • Access to the course Team via code:

2ajhwxg

Communications

Telegram Channel

https://t.me/+lRnU-qwJPP1kMGY0

Prerequisites

  • HTTP (Computer Networks)
  • Java
  • Databases

Programming Today

Some Numbers

Programming Today

Some Numbers:

  1. JavaScript
  2. Python
  3. Java
  4. PHP
  5. C#
  6. TypeScript
  7. CSS
  8. C++
  9. Ruby
  10. C

Course Program

Web Application Programming

Principles, methods, and techniques of web programming



But what does it actually mean?

Course Program

But what does it actually mean?

  • ≠ nstalling or configuring
    • Google Sites
    • Wordpress
    • Joomla
    • Drupal
    • etc.
  • ∞ Platforms and tools

Course Program

Practical Course, a lot of technologies:

Don0t use PHP
  • client side:
    • HTML, CSS, JavaScript
    • Ajax, VueJS
  • server side:
    • Node.js
    • Web Services

In practice: how to create a web application

Software

We will only use products available online, for free:

Teaching Materials

  • These slides, available on the instructor’s website
    (possibly released incrementally)
  • Additional references mentioned in the slides
    • optional
    • mandatory (→ official part of the syllabus))
  • For those who want to explore further:
    • "JavaScript Patterns", di Stoyan Stefanov
    • "JavaScript: The Good Parts", di Douglas Crockford
    • "You Don't Know JS Yet", di Kyle Simpson

Optional Teaching Materials

Programming Books:

  • "The Pragmatic Programmer: From Journeyman to Master", di Andrew Hunt
  • "Clean Code - A Handbook of Agile Software Craftsmanship", di Robert C. Martin
  • "Design Patterns", di Gamma, Helm, Johnson e Vlissides
  • "Refactoring: Improving the Design of Existing Code", di Martin Fowler

Optional Teaching Materials

Design Books:

  • "Design of everyday things", di Don Norman
  • "Designing with the Mind in Mind: Simple Guide to Understanding User Interface Design Guidelines", di Jeff Johnson
  • "Don't make me think. Un approccio di buon senso all'usabilità web e mobile", di Steve Krug
  • Seminario di Mark Miller sul design delle UI

Exam Format

  1. Final practical project (“tesina”), to be submitted three days in advance
  2. Oral exam starting with the presentation of the project

Exam Format

Some details:

  • Individual work
  • Specifications provided by the instructor
  • Specifications change at the beginning of a new course

Web Programming

WARNING!!

The technologies we will see:

Final goal: teach how to fish, rather than give the fish.

Looks simple...

Web Programming

Always evaluate:

  • How many users?
  • Required reliability?
  • Does something already exist that solves the problem?
  • Where will it reside on the server side?
  • Monolithic solution?
  • Modular solution (micro-services)?

HTML

HTML

HyperText Markup Language (HTML)

Language used to describe the content and the structure of the information in a web document

It does not describe the presentation of the information!

web page = web document

Brief History

  • Prehistory: CERN
    • 1991 → HTML (draft) first publicly available description
    • 1993 → HTML+ (draft)
    • 1995 → HTML 2.0
  • Yesterday: W3C
    • 1/1997 → HTML 3.2
    • 12/1997 → HTML 4.0
    • 2000–2001 → XHTML
  • Today: W3C + WHATWG
    • 2008–10/2014 → HTML 5 stable W3C Recommendation since October 2014
    • 12/2017 → HTML 5.2

much more complicated, actually

HTML 5 vs. HTML 4

Important enhancements:

  • one single standard, two possible syntaxes: HTML and XHTML (HTML → <!DOCTYPE html>)
  • new elements useful to make the semantics of the document more explicit: <article>, <section>, <nav>, <aside>
  • new elements useful for integrating multimedia content: <audio>, <video>

Official reference on the differences

To ensure backward compatibility, some things may be allowed for HTML interpreters but not for authors

HTML

The Basics

Very Simple HTML Document

<!DOCTYPE html>
<html>
  <head>
    <title>Hello HTML</title>
  </head>
  <body>
    <p>
      Hello <a href="http://www.units.it">UniTs</a>!<br/>
      We are learning!
    </p>
  </body>
</html>

Elements, Tags, Attributes

  • <title>Hello HTML</title>element
    • <title>start tag
    • Hello HTML → content
    • </title>end tag
  • The start tag can contain attributes:
    <a href="http://www.units.it">UniTs</a>
    • href="http://www.units.it" → attribute
    • href → attribute name
    • http://www.units.it → attribute value

Notes

  • Some elements have no content:
    • <img src="white-dog.png"/>
    • <br/>
    • there is only the start tag
  • Some attributes have no value:
    • <input type="checkbox" checked/>
  • Comments are inserted with <!--...-->:
    • <!--nobody can see this-->

Head and Body

  • <head>head, additional information about the document
  • <body> → informational content of the document

Additional Information

  • <title> → document title
  • <meta name="..." content="...">
    • name="author" → document author
    • name="description" → document description
    • name="keywords" → document keywords ("...,...,...")

From HTML to the Screen

Browser: HTML → DOM tree → screen rendering

Document Object Model (DOM)

Tree representation of the document, in memory

Alternatives to the screen:

  • speech synthesis
  • printer
  • ...

HTML

Rules

Rules

Different levels of correctness:

  • syntactic (HTML) → clear, but "it still works"
  • stylistic (HTML) → few and vague
  • stylistic (representation) → many and vague
  • semantic (HTML) → many, fairly clear

Syntactic Rules (HTML): Nesting

Elements can be nested but not overlapped

  • <p>Example <strong>correct</strong></p> → correct
  • <p>Example <strong>correct</p></strong>invalid

Syntactic Rules (HTML): Attribute Values

Attribute values must be in quotes if they contain spaces

  • <img src="white-dog.png" alt="White dog"/> → correct
  • <img src=white-dog.png alt="White dog"/> → correct
  • <img src="white-dog.png" alt=White dog/>invalid

To avoid mistakes, always use quotes!

Syntactic Rules (HTML): named character references

Special characters with a name:

  • &darr;down arrow (↓)
  • &rationals; → rationals (ℚ)
  • lots more available

Rules:

  • in the text you cannot use &s if s is the name of one of the characters
  • all named character references must end with a semicolon

Syntactic Rules (HTML):
is that all?

There are many more!

What to do?

  • consult the specification
  • use a validator

The Specification

The specification = THE manual = the bible:
HTML5 W3C Recommendation, https://html.spec.whatwg.org/multipage/

What does it contain?

  • which elements exist
  • for each element, nesting rules
  • for each element, which attributes
  • for each attribute, meaning and which values are valid
  • ...

Also as an introduction to HTML

HTML5 W3C Recommendation: extremely detailed manual

Example: start tag? end tag? />?

The start and end tags of certain normal elements can be omitted, as described later

Optional tags

complicated, better to always include the end tag

HTML5 W3C Recommendation: extremely detailed manual

Another example: <em>

The em element

Validator

W3C Validator

Validazione sito UniTS
W3C Validator at www.units.it

… the teacher is familiar with the W3C Validator

Stylistic rules (HTML)

  • Indentation!
  • ...
  • Attributes: always use quotes!
  • Close optional tags

Stylistic rules (representation)

Style → de gustibus?

Usability

Stylistic rules (representation)

Usability

10 usability crimes

they are not only about HTML (HTML ≠ representation)

HTML

HTML Elements

HTML Elements

  • <!-- --> → defines a comment
  • <!DOCTYPE> → defines the document type
  • <a> → defines a hyperlink
  • <abbr> → defines an abbreviation
  • <address> → defines an address element
  • ...

Complete list:

HTML Elements: list

Tag Description
<!--...--> Defines a comment
<!DOCTYPE>  Defines the document type
<a> Defines a hyperlink
<abbr> Defines an abbreviation or an acronym
<acronym> Not supported in HTML5. Use <abbr> instead.
Defines an acronym
<address> Defines contact information for the author/owner of a document
<applet> Not supported in HTML5. Use <embed> or <object> instead.
Defines an embedded applet
<area> Defines an area inside an image-map
<article> Defines an article
<aside> Defines content aside from the page content
<audio> Defines sound content
<b> Defines bold text
<base> Specifies the base URL/target for all relative URLs in a document
<basefont> Not supported in HTML5. Use CSS instead.
Specifies a default color, size, and font for all text in a document
<bdi> Isolates a part of text that might be formatted in a different direction from other text outside it
<bdo> Overrides the current text direction
<big> Not supported in HTML5. Use CSS instead.
Defines big text
<blockquote> Defines a section that is quoted from another source
<body> Defines the document's body
<br> Defines a single line break
<button> Defines a clickable button
<canvas> Used to draw graphics, on the fly, via scripting (usually JavaScript)
<caption> Defines a table caption
<center> Not supported in HTML5. Use CSS instead.
Defines centered text
<cite> Defines the title of a work
<code> Defines a piece of computer code
<col> Specifies column properties for each column within a <colgroup> element 
List of tags on w3schools

Sections

  • article → a piece of independent content; if nested, the inner one is related to the outer one (e.g., a blog post and its comments).
  • section → a grouping of content that is part of a broader piece of content, typically with a heading
  • nav → a section with navigation links
  • aside → a piece of content complementary to its context (e.g., notes, Twitter messages, etc.)

Sections

  • h1, ..., h6 → headings (⚠ do not use for subtitles or taglines!)
  • header → introductory content (e.g., title and navigation)
  • footer → information related to the section (e.g., author, additional links, copyright, etc.)
  • address → contact information (⚠ not for generic addresses)

Sections: questions

  • Is the font of h1 larger than that of h2?
  • Is the vertical spacing between two section elements larger than that after an article?
  • How is the address tag rendered?

Sections: questions

Wrong, you shouldn’t be asking yourself that!

HyperText Markup Language (HTML)

Language used to describe the content and structure of the information in a web document

Not the representation!

Grouping content

<h2>My memoirs</h2>
        <p>
          I don’t remember them anymore...
        </p>
  • p → paragraph
  • hr → topic change (not needed between sections)
  • pre → preformatted text
  • blockquote → external quotation
  • main → main content of the page, not repeated across the site. ⚠ only one per page!

Grouping content

      <h3>Ingredients</h3>
              <ul>
              <li>Sicilian pesto</li>
              <li>fusilli</li>
              <li>grated cheese</li>
              </ul>
              <h3>Preparation</h3>
              <ol>
              <li>cook the pasta</li>
              <li>add the pesto</li>
              <li>garnish with cheese to taste</li>
              </ol>
  • ulunordered list
  • olordered list
  • lilist item

⚠ must not be placed inside paragraphs!

Line breaks

  • CR+LF ≠ new line
  • brline break, part of the content

br elements must be used only for line breaks that are actually part of the content, as in poems or addresses.

must be used? → semantic correctness (HTML)

Textual semantics

  • em → the content of the element deserves emphasis
  • strong → the content is important
  • mark → highlighted text for reference (e.g., searched text)
  • s → the content is no longer accurate or relevant
  • sub and sup → subscript and superscript text

Textual Semantics

  • i → different reading (e.g., another language, technical term, etc.)
  • u → text with non-textual annotation (e.g., intentionally incorrect)
  • Authors are encouraged to avoid using the u element where it could be confused for a hyperlink.
  • b → draw attention
    The b element should be used as a last resort when no other element is more appropriate.

Representing Code

  • code → the content is a piece of source code
  • samp → output produced by the code
  • var → a variable
  • kbd → keyboard input... sort of
    • inside samp → the key was pressed by the user and displayed on screen
    • containing a samp tag → a menu was selected
    • containing other kbd → key combination

Example kbd

Please press Ctrl + Shift + R to reload a page.

Please press Ctrl + Shift + R to reload a page.

Example: samp in kbd

To create a new file, choose the menu option FileNew Document .

Don't forget to click the OK button to confirm once you've entered the name of the new file.

To create a new file, choose the menu option FileNew Document.

Don't forget to click the OK button to confirm once you've entered the name of the new file.

Hyperlink

I go to the <a href="http://www.units.it">university</a>
  • a → link (anchor) to another document
  • href="" → location of the other document
    • same site (relative URL) → href="udine.html"
    • different site (absolute URL) → href="http://www.units.it"
    • same document → href="#people"
    • email address → href="mailto:andrea.delorenzo@units.it"

link is something else

Images

<img src="white-dog.jpg" alt="The white dog"/>
  • src → location of the image resource
  • altfallback content: content that is to be used when the external resource cannot be used

Images: atrribute alt

Is alt mandatory?

Except where otherwise specified, the alt attribute must be specified and its value must not be empty; the value must be an appropriate replacement for the image.

One way to think of alternative text is to think about how you would read the page containing the image to someone over the phone, without mentioning that there is an image present.

In some cases, the icon is supplemental to a text label conveying the same meaning. In those cases, the alt attribute must be present but must be empty.

[...] In such cases, the alt attribute may be omitted, but one of the following conditions must be met [...]

“Almost” mandatory to include it, but it can be alt=""

Tables

<table>
  <caption>Line 36 Timetable</caption>
  <thead>
    <tr><th>Hour</th><th>Minute</th></tr>
  </thead>
  <tbody>
    <tr><td>8</td><td>00 15 30 45</td></tr>
    <tr><td>9</td><td>15 45</td></tr>
  </tbody>
</table>
  • caption → title, heading
  • thead; tfoot → column labels; totals, etc. (header, footer)
  • tbody → body (with the values)
  • tr → row (table row)
  • td, th → cell (table data/header cell)

Tables

Do not use them for formatting!

Tables must not be used as layout aids. Historically, some Web authors have misused tables in HTML as a way to control their page layout. This usage is non-conforming, because tools attempting to extract tabular data from such documents would obtain very confusing results. In particular, users of accessibility tools like screen readers are likely to find it very difficult to navigate pages with tables used for layout.

There are a variety of alternatives to using HTML tables for layout, primarily using CSS positioning and the CSS table model.

div and span

The div element has no special meaning at all. It represents its children. It can be used with the class, lang, and title attributes to mark up semantics common to a group of consecutive elements.

→ BLOCK level

The span element doesn't mean anything on its own, but can be useful when used together with the global attributes, e.g. class, lang, or dir. It represents its children.

→ inside a text line

div: example

<article lang="en-US">
  <h1>My use of language and my cats</h1>
  <p>My cat's behavior hasn't changed much since her absence, except
  that she plays her new physique to the neighbors regularly, in an
  attempt to get pets.</p>
  <div lang="en-GB">
    <p>My other cat, coloured black and white, is a sweetie. He followed
    us to the pool today, walking down the pavement with us. Yesterday
    he apparently visited our neighbours. I wonder if he recognises that
    their flat is a mirror image of ours.</p>
    <p>Hm, I just noticed that in the last paragraph I used British
    English. But I'm supposed to write in American English. So I
    shouldn't say "pavement" or "flat" or "colour"...</p>
  </div>
  <p>I should say "sidewalk" and "apartment" and "color"!</p>
</article>

span: example

<code class="lang-c"><span class="keyword">for</span> (<span class="ident">j</span> = 0; <span class="ident">j</span> &lt; 256; <span class="ident">j</span>++) {
  <span class="ident">i_t3</span> = (<span class="ident">i_t3</span> & 0x1ffff) | (<span class="ident">j</span> &lt;&lt; 17);
  <span class="ident">i_t6</span> = (((((((<span class="ident">i_t3</span> >> 3) ^ <span class="ident">i_t3</span>) >> 1) ^ <span class="ident">i_t3</span>) >> 8) ^ <span class="ident">i_t3</span>) >> 5) & 0xff;
  <span class="keyword">if</span> (<span class="ident">i_t6</span> == <span class="ident">i_t1</span>)
    <span class="keyword">break</span>;
}</code>
for (j = 0; j < 256; j++) {
i_t3 = (i_t3 & 0x1ffff) | (j << 17);
i_t6 = (((((((i_t3 >> 3) ^ i_t3) >> 1) ^ i_t3) >> 8) ^ i_t3) >> 5) & 0xff;
if (i_t6 == i_t1)
break;
}

HTML

Global Attributes

id Attribute

id → unique identifier

  • unique across the whole document
  • no spaces: <section id="abstract">

It can be used for:

  • internal links <a href="#abstract">
  • ... to be seen later

Identifiers are opaque strings. Particular meanings should not be derived from the value of the id attribute.

title Attribute

title → descriptive indication

  • <a href="udine.html" title="Info page of the neighboring city">Udine</a>
  • <abbr title="Cascading Style Sheet">CSS</abbr>

Advisory information for the element, such as would be appropriate for a tooltip.

⚠ Warning...

  • Do not consider them tooltips (e.g., on tablets?)
  • Inheritance
  • new line in HTML → actual new line!

lang and translate Attributes

lang → main language of the content

<p lang="it">English is difficult to pronounce:
for example the word <span lang="en-UK">Wednesday</span>.</p>
<p lang="de"><span lang="en-UK">Wednesday</span>
ist ein schwieriges Wort auszusprechen.</p>

translate → whether or not this content should be localized

Enumerated values:

  • yes
  • no

Example: code fragments, keyboard input, menus, etc.

class attribute

Value: a set of space-separated names:
<span class="content keyword">if</span>

Authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content

semantic correctness (HTML)

data-* Attribute

          <section data-dog-weight="12.8kg" data-dog-speed="75%">
<h1>White dog</h1>
<p>The white dog is stocky but fast.</p>
</section>
  • what follows data- is the name of the custom attribute
  • private data for the page (or application)
  • CamelCase → camel-case (⚠ uppercase letters not allowed)

dir and style Attributes

dir → text direction

style → appearance of the element, we’ll see later

Semantic Elements – Overview

<header>
<nav>
<section><aside>
<article>
<footer>

article inside section or the other way around?

The article element specifies independent, self-contained content.

The section element defines a section in a document.

Can we use the definition to decide how to nest these elements? No.

In some HTML pages a section will contain an article, and in others an article will contain a section.

HTML Exercise 1

Write a (HTML-only) document about your city or neighborhood.

Content (items):

  • the 3 most famous people/animals
  • or, the 3 most beautiful buildings/places

We will assess the syntactic, semantic, and stylistic correctness of the HTML document.

HTML Exercise 1

Rules:

  • at least 3 items with at least 3 sections
  • use aside, i, em, strong, nav, lang, li
  • each item must include at least 500 characters of text
  • the total document must include at least 5,000 characters of text
  • include at least one internal link

Text Editor

Choose whichever you like, I suggest:

Text Editor – Visual Studio Code

Recommended extensions:

Text Editor – Sublime Text

Recommended packages:

Text Editor – Zed

Features:

  • Lightweight and very fast editor
  • Collaborative editing in real-time
  • Built-in support for multiple languages
  • Modern UI and native performance

Fewer plugins than VS Code or Sublime, but designed for speed and teamwork.

HTML Representation

Representing an HTML document

HyperText Markup Language (HTML)

Language used to describe the content and the structure of the information in a web document

The browser renders the document:
how does it draw it on the screen?

How does it draw it?

  1. HTML
  2. DOM tree
    (in-memory representation)
  3. representation on screen

How?

  • HTML → DOM tree: implicit transformation rules
  • DOM tree → screen: ...

HTML → DOM tree

HTML

<!DOCTYPE html>
<html>
 <head>
  <title>Sample page</title>
 </head>
 <body>
  <h1>Sample page</h1>
  <p>This is a <a href="demo.html">simple</a> sample.</p>
  <!-- this is a comment -->
 </body>
</html>

HTML → DOM tree

DOM tree:

  • DOCTYPE: html
  • html
    • head
      • #text: ⏎␣␣
      • title
        • #text: Sample page
      • #text: ⏎␣
    • #text: ⏎␣
    • body
      • #text: ⏎␣␣
      • h1
        • #text: Sample page
      • #text: ⏎␣␣
      • p
        • #text: This is a
        • a href="demo.html"
          • #text: simple
        • #text: sample.
      • #text: ⏎␣␣
      • #comment: this is a comment
      • #text: ⏎␣⏎

DOM tree: terminology

Let’s consider the subtree of the node body (some #text omitted):

  • the node body is the parent of the node h1
  • the nodes p, #comment, ... are sibling of the node h1
  • the nodes h1, p, ... are children of the node body
  • the nodes a, h1, p, ... are descendant of the node body
  • the nodes like body, p, h1, a are elements
  • the nodes #text are text (they have no children!)

DOM tree → screen: informally

For each node of the DOM tree:

  • what should be drawn?
  • where?
  • how?

reading the document: "drawn" → "spoken", "where" → "when"

Imagine you are the browser, or that you have to write the browser program’s code...

DOM tree → screen: formally

Goal: DOM tree → boxes tree

Main transformation rules:

  • each element E of the DOM tree may generate zero or more boxes
  • a box BE of the element E may be child of another box B'E of E or child of a box BEp of Ep, parent of E

What should be drawn?

An element is drawn if and only if all the following conditions are valid:

  • the parent has been drawn (or has no parent)
  • it is not explicitly marked as "not to be drawn"

Where should it be drawn?

Premise: types of boxes

  • block-level boxlike a paragraph
  • line boxlike a line of text
  • inline-level boxlike a word

Types of boxes: content

What they can contain:

  • block-level box
    • block-level boxes
    • line boxes
  • line box
    • inline-level boxes
  • inline-level box
    • text
    • inline-level boxes
    • block-level boxes (e.g., a list inside a strong element)

Where should it be drawn?

Roughly speaking:

  • consecutive block-level boxes are placed one below the other inside the parent block-level box

    They try to fill all the available horizontal space

  • consecutive line boxes are placed one below the other inside the parent block-level box
  • consecutive inline-level boxes are placed side by side inside the parent line-level box

    They only occupy the strictly necessary space

"consecutive" → follows the order of the DOM tree

Block-Level boxes

Non-exhaustive list:

  • p
  • table
  • nav
  • div
  • form
  • main, article, section
  • h1, h2, ...
  • ...ecc.

Inline-Level boxes

Non-exhaustive list:

  • a
  • span
  • em
  • strong
  • input, button, textarea
  • img
  • ...ecc.

Line boxes

And which elements generate Line Boxes?

They are generated automatically!

The rectangular area that contains the boxes that form a line is called a line box.

When several inline-level boxes cannot fit horizontally within a single line box, they are distributed among two or more vertically-stacked line boxes. Thus, a paragraph is a vertical stack of line boxes.

When an inline box exceeds the width of a line box, it is split into several boxes and these boxes are distributed across several line boxes. If an inline box cannot be split (e.g., if the inline box contains a single character, or language specific word breaking rules disallow a break within the inline box, or if the inline box is affected by a white-space value of nowrap or pre), then the inline box overflows the line box.

Example

DOM tree and boxes
Simplification of the transition HTML → boxes

How is it drawn?

We’re missing something:

  • given an element, what type of box does it generate?
  • given an element, how much margin does it have?
  • ...
  • "how is it drawn?"

"box type", "margin", ... → style properties of boxes

Properties and CSS

Cascading Style Sheet (CSS)

A document that specifies which values to assign to which elements’ properties

  • sheet → sheet, document
  • styleproperties related to stylistic representation
  • cascading → we’ll see...

CSS

Cascading Style Sheet (CSS)

A document that specifies which values to assign to which elements’ properties

"the element of type p must correspond to a block-level box with a 1cm margin"

HTML without CSS?

But the browser still displays my page, even though I haven’t provided any CSS!

implicit rules

The CSS rules given in these subsections are, except where otherwise specified, expected to be used as part of the user-agent level style sheet defaults for all documents that contain HTML elements.

In the specification, a CSS follows

CSS

CSS: short history

  • 1996 → CSS 1
  • 1998 → CSS 2
  • 2011 → CSS 2.1
  • (2005) → CSS 3 (still in development)
You don't need to be a programmer or a CS major to understand the CSS specifications. You don't need to be over 18 or have a Bachelor's degree. You just need to be very pedantic, very persistent, and very thorough.

CSS: basic principles

  • Compatibility: forward and backward
  • Complementary to structured documents (HTML and XML)
  • Independent from Vendor/Platform/Device (roughly, cf. printers)
  • Easy maintenance
  • Simple: only one way to achieve an effect
  • Network performance (e.g., I send formatted text instead of images)
  • Flexible: can be defined in multiple places
  • Compatible with other languages (e.g., JS)
  • Accessibility

CSS 3: the "bible"?

Less simple compared to HTML: the specification is modular

As the popularity of CSS grows, so does interest in making additions to the specification. Rather than attempting to shove dozens of updates into a single monolithic specification, it will be much easier and more efficient to be able to update individual pieces of the specification. Modules will enable CSS to be updated in a more timely and precise fashion, thus allowing for a more flexible and timely evolution of the specification as a whole.

For resource constrained devices, it may be impractical to support all of CSS. For example, an aural browser may be concerned only with aural styles, whereas a visual browser may care nothing for aural styles. In such cases, a user agent may implement a subset of CSS. Subsets of CSS are limited to combining selected CSS modules, and once a module has been chosen, all of its features must be supported.

CSS: modular specification

Development status of the specification modules

CSS: definitions

Cascading Style Sheet (CSS)

An ordered list of rules

Rule

  • selector → which elements the rule applies to
  • zero or more declarations → what applies to those elements

Declaration

  • property name
  • property value

does not apply only to HTML documents

CSS syntax

        selector {
          property-name: property-value;
          property-name: property-value;
          ...
        }

        selector { /* comment */
          property-name: property-value;
          property-name: property-value;
          ...
        }

        /* comment */

The specification defines:

  • the syntax of the selector
  • the list of property names
  • for each property, the possible values (syntax)

@ Rule

There are special rules that start with @:
  • @charset
  • @import
  • @namespace
  • @media
  • @viewport
  • ...

But we’ll talk about them later...

CSS syntax

Attention: if the syntax of a rule is incorrect, the browser must ignore the entire rule!

"must ignore" = "the specification recommends that the browser ignore it" → the browser may not ignore...

different from what happens with HTML

CSS syntax

Three levels of correctness:

  • syntactic (CSS) → otherwise it is ignored
  • stylistic (CSS) → indentation, please!
  • stylistic (representation: HTML+CSS)

there is a CSS validator

CSS location

Who defines the style?

  • Author
  • User
  • User agent

CSS location: Author

Where do I specify that I want to use certain rules for a given HTML document d? Three methods:

  • as an external text document linked to d:
    <link rel="stylesheet" type="text/css" href="...">
  • embedded in d, as the content of a style element:
    <style>...</style>
  • inside (inline) d: with only the declaration(s) as the value of a style attribute of the element I want to style (the selector is not needed!):
  • <p style="...">

CSS location: @import

The @import rule allows you to import other style sheets into a CSS code

  • It must be the first line of the CSS file
    • before it, only @charset is allowed
  • The user agent will include the file as if it were written at that point
  • Conditions can be added (e.g., device type, resolution, etc.)

Example: importing a Google Web Font

<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" >

font-family: 'Roboto', sans-serif;

CSS

CSS Cascading

Source

Many methods...

All methods can be used together → they are all applied!

  • Multiple external documents (multiple <link ...>)

    link is also used for other purposes

  • And if multiple rules are in conflict? (rules that specify different values for the same property of one or more elements)
  • And if some property is not defined?

Inheritance

If a property P is not defined for an element E, the element inherits the value of P from its parent (parent of E)

  • For many elements and many properties, the value from the user-agent level style sheet is used

Inheritance → cascading style sheet

Inheritance: property values

How do I compute the value of each property?

Six values for each property...

  1. Declared: explicitly in the code
  2. Inherited (inherited): after applying inheritance
  3. Specified: takes the default if not declared and not inherited
  4. Computed: e.g. "2 times the font size"
  5. Used: after processing the parent (e.g. "10% width")
  6. Actual: impossible requests for the User Agent → 10.9 becomes 11

Inheritance: property values

Examples:

Declared Inherited Specified Computed Used Actual
text-align: left left left left left left
width: (none) (none) auto auto 120px 120px
font-size: 1.2em 1.2em 1.2em 14.1px 14.1px 14px
width: 80% 80% 80% 80% 354.2px 354px

em is the font size → 2em = 2 times the font size.

Inheritance: conflict

What if multiple rules are in conflict?

  1. method (origin)
    1. inline style sheet (style="...", most important)
    2. embedded style sheet (<style>)
    3. external document (<link>)
    4. user level style sheet
    5. user-agent level style sheet (least important)
  2. specificity (we’ll see)
  3. source order (the last one wins)

Inheritance: !important

CSS attempts to create a balance of power between author and user style sheets. By default, rules in an author’s style sheet override those in a user’s style sheet.

!important changes the priority:

  1. User-agent
  2. User
  3. Author

Example:

{ background-color: lightgrey !important; }

Some legitimate use cases for !important

  • You are using a Content Management System (CMS: WordPress, Drupal, ...) and cannot modify the style
  • You want to give a uniform style to the buttons of your site, so you define a generic rule. Then you add a rule with higher specificity that overrides it (we’ll see). In this case !important solves the problem

Some legitimate use cases for !important

.button {
  background-color: #8c8c8c;
  color: white;
  padding: 5px;
  border: 1px solid black;
}

#myDiv a {
  color: red;
  background-color: yellow;
}
.button {
  background-color: #8c8c8c !important;
  color: white !important;
  padding: 5px !important;
  border: 1px solid black !important;
}

#myDiv a {
  color: red;
  background-color: yellow;
}