CSS for Developers

Basics

Foundation of the web

The 3 pillars

Websites are built by these three languages:

  • HTML: structured content
  • CSS: visual representation, style and layout
  • JS: interactivity and functionality
if you are familiar with this concept and HTML, we can skip to the next section to the right

HTML Elements

«Elements» are the building blocks of web pages, for example:

  • <h1> – Headings
  • <p> – Paragraphs
  • <a> – Links (a = anchor)
  • <img> – Images
  • <table> – Tables
  • <input> – Input fields (text, number, date, etc.)
HTML = Hypertext Markup Language

Core Aspects of HTML

  • Tags: define elements (e.g., <header>)
  • Attributes add extra info to elements (e.g., href="…")
  • Content: text or other elements inside tags
  • Nesting: elements can contain others (hierarchy matters)
  • Void elements: no closing tag needed (e.g., <br>)

Example: <div class="container"><p>Hello</p></div>

HTML Document Structure

The hierarchy (a tree structure) matters for CSS:

                  
                      <!DOCTYPE html>
                      <html>
                        <!-- non visible meta information in "head" -->
                        <head>
                          <meta charset="UTF-8">
                          <title>Page Title</title>
                        </head>
                        <!-- visible content belongs inside "body" -->
                        <body>
                          <main>
                            <p>Content goes here</p>
                          </main>
                        </body>
                      </html>
                  
                
HTML is very similar to XML in syntax but they're not interchangeable

Why is this important?

Most HTML elements have semantic meaning (keyword: «semantic HTML»). This provides context to the content and also allows parsing websites automatically (e.g. by screen readers).

CSS uses the hierarchy to define styling rules and relationships between elements.

CSS

Why do we need CSS?

HTML was never intended to include formatting. It is used to describe the structure and content of a web page.

CSS was introduced to allow style formatting.

CSS = Cascading Style Sheets

What can CSS do?

Three main categories:

  • text appearance: font, color, size, style, alignment, …
  • layout: arrange elements, visual organisation, …
  • interaction design: hover effects, animations, …

Adding CSS to our HTML

We have different options on how to add styling.

  • inline styles with the style attribute on any HTML element
  • CSS inside a <style> tag
  • include external CSS file (preferred option)

Link CSS file

Add a link tag to the HTML head with the href pointing to the CSS file:


                   
                

CSS Syntax

Syntax

CSS is a rule-based language: you define the rules by specifying groups of styles that should be applied to particular elements.

One rule consists of selector and declaration block:


                    selector { /* <- e.g. class name */
                        property: value; /* <- declaration */
                    }
                

Shorthand Properties

Some specific properties can be grouped with a shorthand version.


                    div {
                        background-image: url('logo.png');
                        background-position: top left;
                        background-repeat: no-repeat;
                    }
                

Can be simplified with the background shorthand:


                        div {
                            background: url('logo.png') top left no-repeat;
                        }
                    

Other shorthands

  • margin and padding instead of their specific top, right, bottom, left versions
  • font to set font family, size, weight and style
  • border for size, color and style of the border on all sides

Custom Properties

Also known as "CSS Variables", these allow to easily reuse values:


                    :root {
                        --primary-color: yellow; /* declare it, prefixed with double dash */
                    }

                    p {
                        color: var(--primary-color); /* access value with var() */
                    }
                
They behave like other declarations and can be overwritten!

Helpful resources

  • All of that and much more with explanations and examples can be found in this excellent CSS Handbook from 2019
  • CSS Section on the Mozilla Developer Network
  • Can I use? to check browser support of any CSS feature

Applying styles

Inline styles

We can use the style attribute to define styles for our HTML elements, using the following syntax:


                    

Inline styles example


                    

Paragraph text in red.

Paragraph text in red.

But, there's a better way …

The class attribute

We write a meaningful name into the class attribute:


                    

Paragraph text in red.

Then we can reference this class in CSS prefixed with a dot:


                        
                    

Classes

Elements can have multiple classes, which applies multiple rules:


                    

Paragraph text in red.

Precedence

What happens if we combine classes and inline styles?


                    

Is it red or blue?

It's blue!

Inline styles take precedence.

Class vs. Inline

Why use classes instead of inline styles?

  • Inline styles are hard to override/adjust
  • We can easily reuse styles
  • Separates the concerns of styling and structure
  • Easier to read and maintain
  • Inline styles are less performant
Avoid inline styles, classes were made for this

Selectors

Selectors

Classes aren't our only way to target elements. We can use different identifiers from our HTML as selector:

Multiple Selectors

We can list multiple selectors separated with comma to apply the same rule to different elements:


                    p, li {
                        color: red;
                    }
                

Combinator Selectors

Some elements should look different based on where they are.


                        /* span that are descendants of a li */
                        li span {
                            color: red;
                        }
                    

                        
  • red text red text
  • Combinator Selectors

    Use > to style only direct child elements.

    
                            /* span that are direct children of a li */
                            li > span {
                                color: red;
                            }
                        
    
                            
  • other text red text
  • Combinator Selectors

    Select next adjacent siblings following an element with +.

    
                            /* p that are adjacent siblings following a ul */
                            ul + p {
                                color: red;
                            }
                        
    
                            

    some paragraph content

      ...

    red text

    some more paragraph content

    Combined Selectors

    We can combine selectors to target more specific elements:

    div.banner a
    form#upload button:enabled
    ul > li
    section p + p

    CSS Diner Exercise

    Exercise Solve levels 1 to 14 of CSS Diner (open link or use next slide)
    Solve levels 1 to 14 (press down to hide this)

    Nesting

    Official Standard

    Since December 2023 all major browsers support CSS nesting.

    Nesting (along with variables) used to be a major argument for preprocessors and has now finally found it way into the CSS standard.

    Nesting Syntax

    
                        ul {
                            font-size: 1.2rem;
                            li {
                                color: red;
                            }
                        }
                    

    is parsed as:

    
                            ul {
                                font-size: 1.2rem;
                            }
    
                            ul li {
                                color: red;
                            }
                        

    Compound Selectors

    The new & nesting selector is used to explicitly specify the relationship between parent and child.

    
                        a {
                            &:hover {
                                color: red;
                            }
                        }
                    

    turns into:

    
                            a:hover { /* without "&" it would be: a *:hover { … } */
                                color: red;
                            }
                        
    you can't concatenate selector strings with "&"

    Advanced Use

    The nesting selector doesn't have to be at the start:

    
                        h2 {
                            color: blue;
                            .highlight & {
                                color: red;
                            }
                        }
                    

    turns into:

    
                            h2 {
                                color: blue;
                            }
    
                            .highlight h2 {
                                color: red;
                            }
                        

    Use Cases

    Nesting helps with readability and maintainability of CSS. It can also be used with "at-rules" such as media or container queries.

    It's especially helpful to override special cases like hover states or responsive behaviour.

    But: don't nest just because you can. Don't bloat the selector unnecessarily.

    Further Reading

    There are plenty more examples and in-depth explanations in the CSS nesting section on MDN.

    Units

    Absolute units

    • px: size in exact pixels
    • cm/mm: size in metric units (e.g. useful for print)

    Sizing relative to font size

    • rem: size relative to the root font size (<html>)
    • em: size relative to the font size of the element itself

    Why rem?

    • Some users change the root font size (for example for accessibility reasons)
    • With px this preference is ignored
    • With rem everything can scale accordingly
    use rem/em instead of px if possible

    Percentage

    %: relative to another value, depending on where it's used

    Viewport Units

    Units relative to the viewport (usually browser window size):

    • vh/vw: percentage of viewport, height and width
      (1vh = 100% of viewport height)
    • vmax/vmin: the max, resp. min, dimension of the viewport
    • sv*/lv*/dv*: small, large and dynamic viewport sizes for dynamic browser interfaces (i.e. address bar on mobile)

    Calculations

    CSS offers a calc() function for basic math operations. It allows different units:

    
                        div {
                            max-width: calc(80% - 100px);
                            height: calc(100vh / 3);
                        }
                    

    Questions?