Lecture 6 Foundational Concepts of CSS

CSS beyond the browser?

Topics for today

Document flow & the box model

In CSS, every element is a box

A lot of CSS is about how these boxes are painted, and how they affect other boxes

Lorem Ipsum dolor sit amet
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor
Lorem Ipsum
ad minim veniam
ullamco laboris
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
velit esse cillum dolore
consectetur adipiscing elit, sed do eiusmod tempor incididunt
Excepteur sint occaecat cupidatat non proident

Block elements

  • Laid out top to bottom*
  • Line break before and after
  • Box as wide as available space (extrinsic)
  • Box as tall as all contents (wrapped)
  • Text wrapping inside box
Lorem Ipsum dolor sit amet
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Inline elements

  • Laid out left to right*
  • Inline with surrounding text
  • Box as wide as all contents (intrinsic)
  • Box as tall as one line
  • Text wrapping by box fragmentation
velit esse cillum dolore
consectetur adipiscing elit
sed do eiusmod tempor incididunt
Excepteur sint occaecat cupidatat non proident
\* In Western languages. Which elements that we have seen already are block and which inline?

Which of the elements we have seen so far are block and which inline?

div span p em ol ul strong article abbr details

Block Inline

Note that many of the elements we have seen are missing from this list. That’s because block and inline are not the whole story.
The display property How does the browser know which elements are block and which are inline? It’s not magic, that is also just CSS that is being applied to elements by default, called the *User Agent Stylesheet*. Open this in a new tab and inspect the paragraphs, `<em>` and `<strong>` elements, or even the `<body>`, `<head>` and `<html>` elements. We can set the `display` property ourselves as well, to override the defaults. Let's make the paragraphs inline and the `<em>` and `<strong>` elements block!

Each property has an initial value

- We can set a property to its initial value by setting it to the keyword [`initial`](https://developer.mozilla.org/en-US/docs/Web/CSS/initial), which is valid for every property (it is a *global keyword*) - How do we find out what a property’s initial value actually is? By looking up its definition. E.g. here’s [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display#formal_definition) - Usually the initial value is the value that produces no effect, e.g. [`font-weight: normal`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#formal_definition)

Browsers apply default CSS through their User Agent Stylesheet

That is just a CSS file that is applied to every website. Curious what that looks like? Here are the UA stylesheets of some popular browsers: - [Chrome](https://source.chromium.org/chromium/chromium/src/+/master:third_party/blink/renderer/core/html/resources/html.css;bpv=0) - [Firefox](https://github.com/mozilla/gecko-dev/blob/master/layout/style/res/html.css) - [Safari](https://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css)

The combination of initial values and UA stylesheet values are the defaults we start with

Any CSS we write has priority over these defaults. We will discuss the exact mechanism in the next lecture.
The Box Model

There are a few properties that are crucial to how these boxes are sized:

  • padding controls the spacing from the element’s content to its edge. margin specifies the spacing from the element’s edge to the elements around it, and can be negative to bring the element closer to other elements instead of farther. border allows you to specify a visible border. It’s placed outside the padding.
  • Padding & border widths are added to width and height, not subtracted from it.
  • Outlines, shadows etc do not affect the box in any way.
  • Always use sufficient padding, otherwise the text is uncomfortable to read. As you may remember from the Graphic Design lecture, you usually need more padding horizontally than vertically.
Switching box models Sometimes the default box model is a problem. Let's look at an example. We want this input to have a width of 100%. However, if we set `width: 100%` it doesn’t work the way we expect. What is happening? How can we fix it? We *can* fix it with `calc()` but that way we are repeating the padding and border twice. How can we improve our code? We *could* use custom properties to eliminate duplication, but now our code is long and unwieldy. If only the box model could work differently! -------- Let’s apply `box-sizing` to make our code more maintainable.
Alternate Box Model
  • What happens when we specify a width of 100%? Does it match our intent?
  • We can change that with box-sizing: border-box, but that has its issues too
  • Each element has a content box, a padding box, a border box and a margin box that are delimited by the corresponding areas.
  • You can use the browser developer tools to inspect the box model, via the "Computed" tab in the Elements panel.

More block vs inline

Box properties on inline element The properties we saw behave entirely differently on inline elements! - `width` and `height` have no effect - `padding` and borders are applied to each fragment individually, and does not move it in any way. - Horizontal `margin` applies spacing before and after the element, vertical margin does nothing.

Wait a second… But that input was on the same line and had a width!
🤔🤔🤯

Block elements

  • Laid out top to bottom*
  • Line break before and after
  • Box as wide as all available space
  • Box as tall as all contents (wrapped)
  • Text wrapping inside box
  • We can set width, height, margin
Lorem Ipsum dolor sit amet
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Inline elements

  • Laid out left to right*
  • Inline with surrounding text
  • Box as wide as all contents
  • Box as tall as one line
  • Text wrapping by box fragmentation
  • width, height, margin have no effect.
velit esse cillum dolore
consectetur adipiscing elit
sed do eiusmod tempor incididunt
Excepteur sint occaecat cupidatat non proident

Inline-block elements

  • Laid out top to bottom*
  • Line break before and after
  • Box as wide as all available space
  • Box as tall as all contents (wrapped)
  • Text wrapping inside box
  • We can set width, height, margin-top, margin-bottom
  • Laid out left to right*
  • Inline with surrounding text
  • Box as wide as all contents
  • Box as tall as one line
  • Text wrapping by box fragmentation
  • width, height, margin-top, margin-bottom have no effect.
velit esse cillum dolore
Lorem Ipsum dolor sit amet
consectetur adipiscing elit
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
sed do eiusmod tempor incididunt
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Excepteur sint occaecat cupidatat non proident
  • Is image a block or inline element? Or maybe inline-block?
  • We can set width, height, margin, although they are not entirely independent
  • If we inspect, it's inline (?!?) What's going on?
  • Tip: object-fit and object-position help us adjust how the object contained within the replaced element should be positioned.

Image elements

Replaced elements

Examples

Block elements

div h1 h2 h3 h4 h5 h6 p body html

Inline elements

a span strong em mark code cite abbr

Inline-block elements

button input textarea select

Replaced elements

img video audio iframe canvas option object embed
  • All consecutive whitespace in HTML is collapsed to a single space
  • This allows us to format our code nicely without worrying that our whitespace will be rendered, but sometimes we actually want to render more than one consecutive space!
  • The CSS white-space property changes white space processing rules.
  • Even elements like head or style are boxes too!
  • They just have display: none from the User Agent stylesheet, which hides the element and removes it from normal flow.
  • Same with elements with the hidden attribute
  • You can apply display: none to elements you want to hide.

Values & Units

width: 400px;

width: 50%;

width: 400px;

width: 400px;

<length>

Read more about lengths

<length> units

cap ch em ex ic lh rem rlh vh vw vi vb vmin vmax px cm mm Q in pc pt

<length> units

  • Some useful units are:
    • % refers to a different thing depending on the property. Look it up on a case-by-case basis!
    • em is relative the current font size
    • rem is relative to the current font size of the html element
    • ch represents the width of the "0" glyph in the current font. This is useful in monospaced fonts where every character has the same width.
    • vw is a percentage of the viewport width (100vw = viewport width)
    • vh is a percentage of the viewport height (100vh = viewport height)
  • Font-relative units are useful in making components that scale by changing one property (the font-size).
  • Viewport-relative units are useful in making layouts that scale nicely with the viewport size.
Why are font-relative units useful? Let’s look at an example. Put your caret on the font-size and press Shift + &uparrow to increase the font size fast. Note that the rest of the styling (padding, line-height, border-radius etc) becomes disproportionately small. If we use font-relative units, we can make everything adapt! -------- Our button is now nicely scalable by changing only one parameter, but what if we want the button itself to adapt to the surrounding font size?
  • Viewport scalable units allow us to scale text to the viewport size.
  • calc allows us to perform calculations with different units. The type returned depends on the units that participate in the calculation.
  • min, clamp and max allow us to create upper and lower bounds for our values, and can participate in calc() expressions too.
  • All these functions can of course be combined, e.g. min can be used inside calc and vice versa.
  • Note that unlike Python or most other programming languages, these calculations are re-evaluated every time anything changes (e.g. the viewport or font size)

width: 50%;

Percentages

Each property defines whether percentages are allowed and what they represent

margin-left: 10%;

margin-top: 10%;

border: .3em dotted steelblue;

outline: .3em auto steelblue;

margin: auto;

overflow: auto;

Lorem Ipsum dolor sit amet

CSS-wide keywords

Other datatypes

opacity: [num];

transform: rotate([angle]deg);

background-color: hsl([hue], 100%, 40%);

background:
url(img/chocolate-mousse.png) center / cover,
linear-gradient(teal [stop]%, gold);

background: conic-gradient(teal [stop]%, gold);

Percentages do not always resolve to lengths. E.g. in conic gradients, they resolve to angles, since color stops are placed along a *gradient circle*.

Some properties inherit values from ancestors and others do not

What kinds of properties inherit?

background font border text-decoration display color padding white-space margin text-shadow box-sizing outline

Inherited Not inherited

Shorthands & Longhands

How do these different properties for border interact? What happens if we apply them on the same element?

Shorthands & Longhands

A shorthand is a CSS property that represents multiple other properties, its longhands

border: .3em dotted steelblue;

Disambiguation Shorthands often accept their arguments in either order, but only iff *disambiguation* is possible.

border: dotted .3em steelblue;

border: steelblue .3em dotted;

Longhands can be shorthands too

Longhands can belong to multiple shorthands

Often they evolve over time

CSS 1 CSS 2.1 CSS Backgrounds & Borders Level 3 CSS Backgrounds & Borders Level 4

Naming is not always consistent

What happens if we swap the order of these two declarations? Why??

⚠️

A shorthand always sets all of its longhands, whether values have been provided for them or not

padding: .2em .5em .1em .5em;

Top
Right
Bottom
Left
🕐

background: url(foo.png) 50% 50% / 100% auto no-repeat gold;

background: gold no-repeat 50% 50% / 100% auto url(foo.png);

Shorthand usability


			background: url(cat.jpg)
			            0 10% / 100% 100%
			            no-repeat
			            content-box border-box
			            fixed;
		

			background-image: url(cat.jpg);
			background-position: 0 10%;
			background-size: 100% 100%;
			background-repeat: no-repeat;
			background-origin: content-box;
			background-clip: border-box;
			background-attachment: fixed;
		
Computer languages are also interfaces, they are just text-based interfaces. The same usability dimensions apply. When it comes to CSS shorthands and longhands, which of these is more learnable? Which of these is more efficient?

Topics for next week