CSS for Developers

Lucas Schnüriger & Mithusan Sivakumar

CSS Basics

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:


                   
                

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

How to style HTML elements?

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.

There's a better way though…

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

    px

    Specifies a size in exact pixels

    Sizing relative to font size

    rem: specifies a size relative to the root font size

    em: specifies a size relative to the font size of the element being styled

    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 instead of px if possible

    Other Units

    • %: percentage based on the parent element
    • vh/vw: percentage of viewport (height and width)

    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?