Writing CSS the Right Way

GU Yiling @ Baidu EFE

In this lecture:

  • General knowledge
  • Syntax
  • Cascading
  • Values & units
  • Layout basics
  • Rendering details & calculation

What is CSS?

Cascading Style Sheets

History

  • CSS 1 (1996)

    font, color, align, box-model, #id, .class, ...

  • CSS 2 (1998)

    position, z-index, media, text-shadow, ...

  • CSS 2.1 (2011)

    CSS 2.1 vs CSS 2

CSS 3, even CSS 4?

No. Modules + Level!

CSS Modules (incomplete)

Module Latest Level (2015/09) Example
Text 3 (LC) / 4 (FPWD) text-justify, word-break, hyphens
Flexible Box 1 (LC) flex, justify-content
Color 3 (REC) / 4 (ED) rgba(), currentColor, hwb()
Animations 1 (WD) animation, @keyframes
Transforms 1 (WD) transform, perspective
Transitions 1 (WD) transition, timing functions
Cascading Variables 1 (WD) --foo, var()
Round Display 1 (FPWD) border-boundary, position: polar

More... (Development Process)

Adding CSS to HTML

How?

1. Inline styles

<body>
    <h1 style="font-size: 2em; font-weight: 700;">
        Hello World
    </h1>
    <p style="margin: 2em 0;">
        Paragraph here
    </p>
</body>

2. <link> element

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Hello World</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
...

3. <style> element

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World</title>
    <style type="text/css">
        /* ... */
    </style>
</head>
<body>
...

3. @import rules inside <style> element

<style>
@import url(normalize.css);
@import url(layout.css);
@import url(typography.css);
</style>

Performs worse than the <link> way!
See don’t use @import.

Recap

  • Cascading Style Sheets
  • CSS 1, CSS 2, CSS 2.1, CSS 3, CSS 4
  • CSS Modules + Level
  • 3 ways to use CSS in HTML

CSS Syntax
— writing valid CSS

At-rules

  • @charset
    (before anything else — any character)
  • @import
    (before any statement except @charset)
  • @media
  • @font-face
  • ...
@charset "UTF-8";
@import "styles.css" screen and (min-width: 960px);

Properties

  • display
  • position
  • height
  • font-family
  • transition
  • ...

Why vendor prefixes?

Declarations

property: value

  • display: block
  • position: fixed
  • height: 2em
  • ...

Declaration blocks

{ declaration; declaration; ... }

/* single-line */
{ display: block; height: 3em }

/* multi-line */
{
    color: red;
    opacity: 0.5;
}

Semicolons (;) are only required between declarations.

Selectors

Pattern matching against document trees

Selectors (simple selectors)

Name a few?

Basic simple selectors Example
Type selectors p, span
Universal selectors *
Attribute selectors [title], [rel~="copyright"]
Class selectors .comment, .post
ID selectorss #nav, #main
Pseudo classes :hover, :lang(zh), :checked

Pseudo classes

How many pseudo classes do you know?

Type Example
Linguistic :dir(), :lang()
Location :link, :visited, :target, ...
User action :hover, :focus, ...
Input :checked, :valid, :disabled, ...
Tree-structural :first-child, :nth-child(), ...

Selectors (combinators)

Combinators Example
Descendent combinator ( ) .post p
Child combinator (>) ul > li
Adjacent sibling combinator (+) h1 + h2, :checked + label
General sibling combinator (~) h1 ~ pre

Selectors (pseudo elements)

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

Compatibility: :: vs. :

Rule sets

selector declaration block

.post a {
    color: #69c;
    text-decoration: underline;
}

Statements

at-rule | ruleset

A style sheet consists of a list of statements.

@charset "UTF-8";

a {
    color: #69c;
}

@media screen and (min-width: 35em) {
    a {
        font-size: 1.2em;
    }
}

Showcases (by Otakustay)

Demonstrates dropcap effect.
p:first-of-type::first-letter {
    font-size: 40px;
    font-weight: bold;
}

Showcases (by Otakustay)

Demonstrates a generated quotation mark on a blockquote element.
blockquote::before {
    content: "“";
    font-size: 60px;
    font-weight: bold;
    color: gray;
    vertical-align: bottom;
    position: relative;
    top: 15px;
}

Showcases (by Otakustay)

Rotate images according to its list order.
div:nth-child(2n+1) {
    transform: rotate(-10deg);
}
div:nth-child(2n+2) {
    transform: rotate(10deg);
}
div:nth-child(2n+3) {
    transform: rotate(0);
}

Recap

via Vocabs

Cascading & Inheritance

Value processing

declared → cascaded → specified → computed → used → actual

cascading → defaulting → absolutizing → calculation → UA adjustment

See Value processing examples.

Cascading

Finding value for an element/property combination

  1. Origin and importance
  2. Specificity
  3. Order of appearance

Style sheet origins

UA, user, author

... and we have !important ...

author vs. user?

What about
author & important vs. user & important?

Cascading (origin and importance)

  1. Important + UA
  2. Important + user
  3. Important + author
  4. Normal + author
  5. Normal + user
  6. Normal + UA

That's all? Check CSS Cascading and Inheritance Level 3.

Specificity

  1. ID
    #main
  2. class/attribute/pseudo-class
    .title, [name], :hover
  3. type/pseudo-element
    article, ::before

Compare [a, b, c] and choose a winner!

style attribute > selectors

Quiz

<style>
p.row :hover {
    color: blue !important;
    text-decoration: underline !important;
}

#link {
    color: green;
}
</style>
<p class="row" stlye="color: red !important; text-decoration: underline !important;">
    <a id="link" href="post.html" style="text-decoration: none;">Go to post</a>
</p>

See the Pen XbJPjB by GU Yiling (@Justineo) on CodePen.

What's the color and text-decoration of the “Go to post” link?

Defaulting

  • initial value
  • inherited value
  • inherit keyword

Computed value of the parent element

.post {
    font-size: 16px;
    line-height: 2;    /* Which   */
    line-height: 200%; /* to      */
    line-height: 2em;  /* choose? */
}

Inherited value

line-height is defined with initial value of normal and is inherited.
  • line-height: 2
    Specified → 2
  • line-height: 200%
    line-height: 2em
    Absolute → 2 * 16px = 32px

Recap

  • Value processing start from cascading and defaulting
  • Origin/importance > specificity > order
  • Author > user > UA, reversed when important
  • Count simple selectors/pseudo elements to calculate specificity
  • Inherited values are computed values of the parent

Values and Units

  • 1.2rem
  • 60deg
  • rebeccapurple
  • 1000ms
  • url(logo.png)
  • ...

Quoted Strings: string

a[rel~="next"]::after {
    content: "→";
}

Resource Locators: url

body {
    background: url(starrynight.png);
}

Numeric Data

  • Integers: integer
    z-index: 1; order: 3;
  • Numbers: number
    line-height: 1.5; flex: 0.618;
  • Percentages: percentage
    width: 80%; font-size: 120%;

Distance Units: length

  • Relative
  • Absolute

0px0

length only!

Relative lengths

em, ex, ch, rem, vw, vh, ...

ex is the x-height, ch is the width of character "0"
ex and ch

Absolute lengths

px, pt, in, cm, mm, ...

Physical or pixel?

Pixels must become larger if the viewing distance increases.

Colors: color

  • Keywords
    lightgreen, gold, currentColor, transparent ← transparent, ...
  • Hexadecimal notation
    #69c, #abcdef, ...
  • Functional notation
    rgb(200, 150, 100), hsla(120, 100%, 50%, 0.5), ...

See more in CSS Color Module Level 4.

Other Units

angle, time, image, ...

.box {
    transform: rotate(30deg);
    transition-duration: 2s;
    background: linear-gradient(to top, red 0%, blue 100%);
}

Recap

  • Data types: number, integer, length, color, ...
  • Length: relative vs. “absolute”
  • Color: keywords, hex, rgb(a), hsl(a), ...

Dimension units after zero values are optional for length only!

Layout Basics

canvas and viewport
The canvas (not <canvas>) and the viewport

Box Model

box model consists of content, padding, border and margin

Why box-sizing?

What about * { box-sizing: border-box }?

A Web Desktop

See the Pen aOOZgG by GU Yiling (@Justineo) on CodePen.

Painting Order

Painting order is background-color → background-image → border → children → outline.

Positioning Schemes

  • Normal flow
  • Floats
  • Absolute positioning

Determined by position and float

Normal Flow

  • Block Formatting Context
  • Inline Formatting Context
  • Flex Formatting Context
  • Grid Formatting Context
  • Relative positioning

BFC vs. IFC

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

Floats

float: left;
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

What's “clear fix”?

Absolute Positioning

position: absolute/fixed

Finding the containing block

(See detail here.)

position: absolute

  • Closest parent with position other than static
    or with transform other than none
Initial containing block starts from the origin of the canvas and has the same size of the viewport.
no such parent → initial containing block
Initial containing block
body {
  width: 120%;
  background-color: khaki;
}

.box {
  position: absolute;
  bottom: 10px;
  right: 10px;
  width: 64px;
  height: 64px;
  background-color: lightgreen;
}

See the Pen dooBPz by GU Yiling (@Justineo) on CodePen.

position: fixed

  • The viewport
  • Closest parent with transform other than none
position: fixed & transform
.out {
  margin: 64px;
  width: 256px;
  height: 256px;
  background-color: khaki;
  transform: scale(1);
}

.in {
  position: fixed;
  top: 10px;
  left: 10px;
  width: 64px;
  height: 64px;
  background-color: lightgreen;
}

See the Pen yNNdNB by GU Yiling (@Justineo) on CodePen.

Recap

  • The canvas & the viewport
  • Box model & box-sizing
  • 3 position schemes:
    normal flow / floats / absolute positioning
  • BFC/IFC/FFC/...
  • Finding containing blocks for absolute positioning

Summary

  • History
  • Syntax
  • Cascading
  • Values & units
  • Layout basics

Further Reading

Resources

Q ? A : Thanks