font-display - CSS: Cascading Style Sheets

font-display
============

The **`font-display`** descriptor for the `@font-face` at-rule determines how a font face is displayed based on whether and when it is downloaded and ready to use.

Syntax
------

```css
/\* Keyword values \*/
font-display: auto;
font-display: block;
font-display: swap;
font-display: fallback;
font-display: optional;
```

### Values

`auto`

The font display strategy is defined by the user agent.

`block`

Gives the font face a short block period and an infinite swap period.

`swap`

Gives the font face an extremely small block period and an infinite swap period.

`fallback`

Gives the font face an extremely small block period and a short swap period.

`optional`

Gives the font face an extremely small block period and no swap period.

**Note:** In Firefox, the preferences `gfx.downloadable_fonts.fallback_delay`
 and `gfx.downloadable_fonts.fallback_delay_short` provide the duration
 of the "short" and "extremely small" periods, respectively.

Description
-----------

The font display timeline is based on a timer that begins the moment the user agent attempts to use a given downloaded font face. The timeline is divided into the three periods below which dictate the rendering behavior of any elements using the font face:

* Font block period: If the font face is not loaded, any element attempting to use it must render an *invisible* fallback font face. If the font face successfully loads during this period, it is used normally.
* Font swap period: If the font face is not loaded, any element attempting to use it must render a fallback font face. If the font face successfully loads during this period, it is used normally.
* Font failure period: If the font face is not loaded, the user agent treats it as a failed load causing normal font fallback.
Formal definition
-----------------

|  |  |
| --- | --- |
| Related at-rule | `@font-face` |
| Initial value | `auto` |
| Computed value | as specified |

Formal syntax
-------------
```

font-display =
  auto      |
  block     |
  swap      |
  fallback  |
  optional

```

Examples
--------

### Specifying fallback font-display

```css
@font-face {
  font-family: ExampleFont;
  src:
    url(/path/to/fonts/examplefont.woff) format("woff"),
    url(/path/to/fonts/examplefont.eot) format("eot");
  font-weight: 400;
  font-style: normal;
  font-display: fallback;
}
```

Specifications
--------------

| Specification |
| --- |
| CSS Fonts Module Level 4 # font-display-desc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `font-family`
* `font-stretch`
* `font-style`
* `font-weight`
* `font-feature-settings`
* `font-variation-settings`
* `src`
* `unicode-range`


font-weight - CSS: Cascading Style Sheets

font-weight
===========

The **`font-weight`** CSS descriptor allows authors to specify font weights for the fonts specified in the `@font-face` at-rule. The `font-weight` property can separately be used to set how thick or thin characters in text should be displayed.

For a particular font family, authors can download various font faces which correspond to the different styles of the same font family, and then use the `font-weight` descriptor to explicitly specify the font face's weights. The values for the CSS descriptor is same as that of its corresponding font property.

There are generally limited weights available for a particular font family. When a specified weight doesn't exist, a nearby weight is used. Fonts lacking bold typeface are often synthesized by the user agent. To prevent this, use the `font-synthesis` shorthand property.

Syntax
------

```css
/\* Single values \*/
font-weight: normal;
font-weight: bold;
font-weight: 400;

/\* Multiple Values \*/
font-weight: normal bold;
font-weight: 300 500;
```

The `font-weight` property is described using any one of the values listed below.

### Values

`normal`

Normal font weight. Same as `400`.

`bold`

Bold font weight. Same as `700`.

`<number>`

A `<number>` value between 1 and 1000, inclusive. Higher numbers represent weights that are bolder than (or as bold as) lower numbers. Certain commonly used values correspond to common weight names, as described in the Common weight name mapping section below.

In earlier versions of the `font-weight` specification, the property accepts only keyword values and the numeric values 100, 200, 300, 400, 500, 600, 700, 800, and 900; non-variable fonts can only really make use of these set values, although fine-grained values (e.g. 451) will be translated to one of these values for non-variable fonts.

CSS Fonts Level 4 extends the syntax to accept any number between 1 and 1000, inclusive, and introduces Variable fonts, which can make use of this much finer-grained range of font weights.

### Common weight name mapping

The numerical values `100` to `900` roughly correspond to the following common weight names:

| Value | Common weight name |
| --- | --- |
| 100 | Thin (Hairline) |
| 200 | Extra Light (Ultra Light) |
| 300 | Light |
| 400 | Normal |
| 500 | Medium |
| 600 | Semi Bold (Demi Bold) |
| 700 | Bold |
| 800 | Extra Bold (Ultra Bold) |
| 900 | Black (Heavy) |

### Variable fonts

Most fonts have a particular weight which corresponds to one of the numbers in Common weight name mapping. However some fonts, called variable fonts, can support a range of weights with more or less fine granularity, and this can give the designer a much closer degree of control over the chosen weight.

For TrueType or OpenType variable fonts, the "wght" variation is used to implement varying weights.

Accessibility concerns
----------------------

People experiencing low vision conditions may have difficulty reading text set with a `font-weight` value of `100` (Thin/Hairline) or `200` (Extra Light), especially if the font has a low contrast color ratio.

* MDN Understanding WCAG, Guideline 1.4 explanations
* Understanding Success Criterion 1.4.8 | W3C Understanding WCAG 2.0
Formal definition
-----------------

|  |  |
| --- | --- |
| Related at-rule | `@font-face` |
| Initial value | `normal` |
| Computed value | as specified |

Formal syntax
-------------
```

font-weight =
  auto                         |
  <font-weight-absolute>{1,2}

<font-weight-absolute> =
  normal             |
  bold               |
  <number [1,1000]>

```

Examples
--------

### Setting normal font weight in a @font-face rule

The following finds a local Open Sans font or imports it, and allows using the font for normal font weights.

```css
@font-face {
  font-family: "Open Sans";
  src:
    local("Open Sans") format("woff2"),
    url("/fonts/OpenSans-Regular-webfont.woff") format("woff");
  font-weight: 400;
}
```

Specifications
--------------

| Specification |
| --- |
| CSS Fonts Module Level 4 # font-prop-desc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `font-display`
* `font-family`
* `font-stretch`
* `font-style`
* `font-feature-settings`
* `font-variation-settings`
* `src`
* `unicode-range descriptor`


ascent-override - CSS: Cascading Style Sheets

ascent-override
===============

The **`ascent-override`** CSS descriptor for the `@font-face` at-rule defines the ascent metric for the font. The ascent metric is the height above the baseline that CSS uses to lay out line boxes in an inline formatting context.

Syntax
------

```css
ascent-override: normal;
ascent-override: 90%;
```

### Values

`normal`

The default value. When used the metric value is obtained from the font file.

`<percentage>`

A `<percentage>` value.

Formal definition
-----------------

|  |  |
| --- | --- |
| Related at-rule | `@font-face` |
| Initial value | `normal` |
| Percentages | as specified |
| Computed value | as specified |

Formal syntax
-------------
```

ascent-override =
  [ normal | <percentage [0,∞]> ]{1,2}

```

Examples
--------

### Overriding metrics of a fallback font

The `ascent-override` property can help when overriding the metrics of a fallback font to better match those of a primary web font.

```css
@font-face {
  font-family: web-font;
  src: url("https://example.com/font.woff");
}

@font-face {
  font-family: local-font;
  src: local(Local Font);
  ascent-override: 125%;
}
```

Specifications
--------------

| Specification |
| --- |
| CSS Fonts Module Level 4 # font-metrics-override-desc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `descent-override`
* `font-display`
* `font-family`
* `font-weight`
* `font-style`
* `font-stretch`
* `font-feature-settings`
* `font-variation-settings`
* `line-gap-override`
* `src`
* `size-adjust`
* `unicode-range descriptor`


font-variation-settings - CSS: Cascading Style Sheets

font-variation-settings
=======================

The **`font-variation-settings`** CSS descriptor allows authors to specify low-level OpenType or TrueType font variations in the `@font-face` at-rule. The values for this descriptor are the same as the `font-variation-settings` property, except for the global keyword values.

Since this descriptor sets variation values on the font object in the `@font-face` at-rule and not on an entire element, only some glyphs in an element may be rendered using this descriptor.

Syntax
------

```css
/\* Use the default settings \*/
font-variation-settings: normal;

/\* Set values for OpenType axis names \*/
font-variation-settings: "xhgt" 0.7;
```

### Values

`normal`

Text is laid out using default settings.

`<string> <number>`

When rendering text, the list of OpenType axis names is passed to the text layout engine to enable or disable font features. Each setting is always a `<string>` of 4 ASCII characters, followed by a `<number>` indicating the axis value. If the `<string>` has more or fewer characters or contains characters outside the U+20 - U+7E code point range, the whole property is invalid. The `<number>` can be fractional or negative.

Formal definition
-----------------

|  |  |
| --- | --- |
| Related at-rule | `@font-face` |
| Initial value | `normal` |
| Computed value | as specified |

Formal syntax
-------------
```

font-variation-settings =
  normal                  |
  [ <string> <number> ]#

```

Examples
--------

### Setting font weight and stretch in a @font-face rule

```css
@font-face {
  font-family: "OpenTypeFont";
  src: url("open\_type\_font.woff2") format("woff2");
  font-weight: normal;
  font-style: normal;
  font-variation-settings:
    "wght" 400,
    "wdth" 300;
}
```

Specifications
--------------

| Specification |
| --- |
| CSS Fonts Module Level 4 # font-rend-desc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Other `@font-face` descriptors: `font-display`, `font-family`, `font-feature-settings`, `font-stretch`, `font-style`, `font-weight`, `src`, `unicode-range`
* Related font properties: `font-feature-settings`, `font-variation-settings`


font-feature-settings - CSS: Cascading Style Sheets

font-feature-settings
=====================

The **`font-feature-settings`** CSS descriptor allows you to define the initial settings to use for the font defined by the `@font-face` at-rule. You can further use this descriptor to control typographic font features such as ligatures, small caps, and swashes, for the font defined by `@font-face`. The values for this descriptor are the same as the `font-feature-settings` property, except for the global keyword values.

Since this descriptor sets feature values on the font object in the `@font-face` at-rule and not on an entire element, only some glyphs in an element may be rendered using this descriptor.

Syntax
------

```css
/\* Use the default settings \*/
font-feature-settings: normal;

/\* Set values for OpenType feature tags \*/
font-feature-settings: "smcp";
font-feature-settings: "smcp" on;
font-feature-settings: "swsh" 2;
```

### Values

This descriptor is specified as either the keyword `normal` or as a comma-separated list of `<feature-tag-value>` values. When rendering text, the list of OpenType `<feature-tag-value>` values are passed to the text layout engine to enable or disable font features.

`normal`

Indicates that text is laid out using default font settings. This is the default value.

`<feature-tag-value>`

Represents a space-separated tuple consisting of a tag name and an optional value.

The tag name is always a `<string>` of four ASCII characters. If the tag name has more or fewer characters or if it contains characters outside the `U+20` – `U+7E` code point range, the descriptor is invalid.

The optional value can be a positive integer or the keyword `on` or `off`. The keywords `on` and `off` are synonyms for the values `1` and `0`, respectively. If no value is set, the default is `1`. For non-boolean OpenType features (e.g., stylistic alternates), the value implies a particular glyph to be selected; for boolean features, the value turns the feature on or off.

Formal definition
-----------------

|  |  |
| --- | --- |
| Related at-rule | `@font-face` |
| Initial value | `normal` |
| Computed value | as specified |

Formal syntax
-------------
```

font-feature-settings =
  normal                |
  <feature-tag-value>#

<feature-tag-value> =
  <opentype-tag> [ <integer [0,∞]> | on | off ]?

<opentype-tag> =
  <string>

```

Examples
--------

### Enabling swash glyphs using the @font-face at-rule

In this example, the tag name `swsh` and a boolean value `1` are used as the value for the `font-feature-settings` descriptor in the `@font-face` at-rule.

#### HTML

```html
<p class="swashoff">Swash is off here</p>
<p class="swashon">Swash is on here</p>
```

#### CSS

```css
@font-face {
  font-family: MonteCarlo;
  src: url("montecarlo-regular.woff2");
}
@font-face {
  font-family: MonteCarlo2;
  src: url("montecarlo-regular.woff2");
  font-feature-settings: "swsh" 1;
}
p {
  font-size: 3rem;
  margin: 0.7rem 3rem;
}
.swashoff {
  font-family: MonteCarlo;
}
.swashon {
  font-family: MonteCarlo2;
}
```

#### Result

Line 1 shows the default ornate design of the MonteCarlo font, and line 2 shows the default glyphs being replaced with swash glyphs.

Specifications
--------------

| Specification |
| --- |
| CSS Fonts Module Level 4 # font-rend-desc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Other `@font-face` descriptors: `font-family`, `font-style`, `font-variation-settings`, `font-weight`, `src`
* Related font properties: `font-feature-settings`, `font-variant-alternates`, `font-variation-settings`


unicode-range - CSS: Cascading Style Sheets

unicode-range
=============

The **`unicode-range`** CSS descriptor sets the specific range of characters to be used from a font defined using the `@font-face` at-rule and made available for use on the current page. If the page doesn't use any character in this range, the font is not downloaded; if it uses at least one, the whole font is downloaded.

Syntax
------

```css
/\* <unicode-range> values \*/
unicode-range: U+26; /\* single code point \*/
unicode-range: U+0-7F;
unicode-range: U+0025-00FF; /\* code point range \*/
unicode-range: U+4??; /\* wildcard range \*/
unicode-range: U+0025-00FF, U+4??; /\* multiple values \*/
```

### Values

***single code point***

A single Unicode character code point, for example `U+26`.

***code point range***

A range of Unicode code points. So for example, `U+0025-00FF` means *include all characters in the range `U+0025` to `U+00FF`*.

***wildcard range***

A range of Unicode code points containing wildcard characters, that is using the `'?'` character, so for example `U+4??` means *include all characters in the range `U+400` to `U+4FF`*.

Description
-----------

The purpose of this descriptor is to allow the font resources to be segmented so that a browser only needs to download the font resource needed for the text content of a particular page. For example, a site with many localizations could provide separate font resources for English, Greek and Japanese. For users viewing the English version of a page, the font resources for Greek and Japanese fonts wouldn't need to be downloaded, saving bandwidth.

Formal definition
-----------------

|  |  |
| --- | --- |
| Related at-rule | `@font-face` |
| Initial value | `U+0-10FFFF` |
| Computed value | as specified |

Formal syntax
-------------
```

unicode-range =
  <urange>#

```

Examples
--------

### Using a different font for a single character

In this example we create a simple HTML containing a single `<div>` element, including an ampersand, that we want to style with a different font. To make it obvious, we will use a sans-serif font, *Helvetica*, for the text, and a serif font, *Times New Roman*, for the ampersand.

In the CSS we are in effect defining a completely separate `@font-face` that only includes a single character in it, meaning that only this character will be styled with this font. We could also have done this by wrapping the ampersand in a `<span>` and applying a different font just to that, but that is an extra element and rule set.

#### HTML

```html
<div>Me & You = Us</div>
```

#### CSS

```css
@font-face {
  font-family: "Ampersand";
  src: local("Times New Roman");
  unicode-range: U+26;
}

div {
  font-size: 4em;
  font-family: Ampersand, Helvetica, sans-serif;
}
```

#### Result

Specifications
--------------

| Specification |
| --- |
| CSS Fonts Module Level 4 # unicode-range-desc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `font-display`
* `font-family`
* `font-stretch`
* `font-style`
* `font-weight`
* `font-feature-settings`
* `font-variation-settings`
* `src`


size-adjust - CSS: Cascading Style Sheets

size-adjust
===========

The **`size-adjust`** CSS descriptor for the `@font-face` at-rule defines a multiplier for glyph outlines and metrics associated with this font. This makes it easier to harmonize the designs of various fonts when rendered at the same font size.

The `size-adjust` descriptor behaves in a similar fashion to the `font-size-adjust` property. It calculates an adjustment per font by matching ex heights.

Syntax
------

```css
size-adjust: 90%;
```

### Values

`<percentage>`

A `<percentage>` value with an initial value of 100%.

All metrics associated with this font are scaled by the given percentage. This includes glyph advances, baseline tables, and overrides provided by `@font-face` descriptors.

Formal definition
-----------------

|  |  |
| --- | --- |
| Related at-rule | `@font-face` |
| Initial value | `100%` |
| Percentages | as specified |
| Computed value | as specified |

Formal syntax
-------------
```

size-adjust =
  <percentage [0,∞]>

```

Examples
--------

### Overriding metrics of a fallback font

The `size-adjust` property can help when overriding the metrics of a fallback font to better match those of a primary web font.

```css
@font-face {
  font-family: web-font;
  src: url("https://example.com/font.woff");
}

@font-face {
  font-family: local-font;
  src: local(Local Font);
  size-adjust: 90%;
}
```

Specifications
--------------

| Specification |
| --- |
| CSS Fonts Module Level 5 # size-adjust-desc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `font-display` descriptor
* `font-family` descriptor
* `font-weight` descriptor
* `font-style` descriptor
* `font-stretch` descriptor
* `font-feature-settings`
* `font-variation-settings` descriptor
* `src` descriptor
* `unicode-range` descriptor
* `font-size-adjust` property


Introduction to the CSS basic box model - CSS: Cascading Style Sheets

Introduction to the CSS basic box model
=======================================

When laying out a document, the browser's rendering engine represents each element as a rectangular box according to the standard **CSS basic box model**. CSS determines the size, position, and properties (color, background, border size, etc.) of these boxes.

Every box is composed of four parts (or *areas*), defined by their respective edges: the *content edge*, *padding edge*, *border edge*, and *margin edge*.

![CSS Box model](/en-US/docs/Web/CSS/CSS_box_model/Introduction_to_the_CSS_box_model/boxmodel.png)

Content area
------------

The **content area**, bounded by the content edge, contains the "real" content of the element, such as text, an image, or a video player. Its dimensions are the *content width* (or *content-box width*) and the *content height* (or *content-box height*). It often has a background color or background image.

If the `box-sizing` property is set to `content-box` (default) and if the element is a block element, the content area's size can be explicitly defined with the `width`, `min-width`, `max-width`, `height`, `min-height`, and `max-height` properties.

Padding area
------------

The **padding area**, bounded by the padding edge, extends the content area to include the element's padding. Its dimensions are the *padding-box width* and the *padding-box height*.

The thickness of the padding is determined by the `padding-top`, `padding-right`, `padding-bottom`, `padding-left`, and shorthand `padding` properties.

Border area
-----------

The **border area**, bounded by the border edge, extends the padding area to include the element's borders. Its dimensions are the *border-box width* and the *border-box height*.

The thickness of the borders are determined by the `border-width` and shorthand `border` properties. If the `box-sizing` property is set to `border-box`, the border area's size can be explicitly defined with the `width`, `min-width`, `max-width`, `height`, `min-height`, and `max-height` properties. When there is a background (`background-color` or `background-image`) set on a box, it extends to the outer edge of the border (i.e. extends underneath the border in z-ordering). This default behavior can be altered with the `background-clip` CSS property.

Margin area
-----------

The **margin area**, bounded by the margin edge, extends the border area to include an empty area used to separate the element from its neighbors. Its dimensions are the *margin box width* and the *margin box height*.

The size of the margin area is determined by the `margin-top`, `margin-right`, `margin-bottom`, `margin-left`, and shorthand `margin` properties. When margin collapsing occurs, the margin area is not clearly defined since margins are shared between boxes.

Finally, note that for non-replaced inline elements, the amount of space taken up (the contribution to the height of the line) is determined by the `line-height` property, even though the borders and padding are still displayed around the content.

See also
--------

* Layout and the containing block
* Introducing the CSS Cascade
* Cascade, specificity, and inheritance
* CSS key concepts:
    + CSS syntax
    + At-rules
    + Comments
    + Specificity
    + Inheritance
    + Layout modes
    + Visual formatting models
    + Margin collapsing
    + Values
        - Initial values
        - Computed values
        - Used values
        - Actual values
    + Value definition syntax
    + Shorthand properties
    + Replaced elements


Mastering margin collapsing - CSS: Cascading Style Sheets

Mastering margin collapsing
===========================

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as **margin collapsing**. Note that the margins of floating and absolutely positioned elements never collapse.

Margin collapsing occurs in three basic cases:

Adjacent siblings

The margins of adjacent siblings are collapsed (except when the latter sibling needs to be cleared past floats).

No content separating parent and descendants

If there is no border, padding, inline part, block formatting context created, or *clearance* to separate the `margin-top` of a block from the `margin-top` of one or more of its descendant blocks; or no border, padding, inline content, `height`, or `min-height` to separate the `margin-bottom` of a block from the `margin-bottom` of one or more of its descendant blocks, then those margins collapse. The collapsed margin ends up outside the parent.

Empty blocks

If there is no border, padding, inline content, `height`, or `min-height` to separate a block's `margin-top` from its `margin-bottom`, then its top and bottom margins collapse.

Some things to note:

* More complex margin collapsing (of more than two margins) occurs when the above cases are combined.
* These rules apply even to margins that are zero, so the margin of a descendant ends up outside its parent (according to the rules above) whether or not the parent's margin is zero.
* When negative margins are involved, the size of the collapsed margin is the sum of the largest positive margin and the smallest (most negative) negative margin.
* When all margins are negative, the size of the collapsed margin is the smallest (most negative) margin. This applies to both adjacent elements and nested elements.
* Collapsing margins is only relevant in the vertical direction.
* Margins don't collapse in a container with `display` set to `flex` or `grid`.
Examples
--------

### HTML

```html
<p>The bottom margin of this paragraph is collapsed …</p>
<p>
  … with the top margin of this paragraph, yielding a margin of
  <code>1.2rem</code> in between.
</p>

<div>
  This parent element contains two paragraphs!
  <p>
    This paragraph has a <code>.4rem</code> margin between it and the text
    above.
  </p>
  <p>
    My bottom margin collapses with my parent, yielding a bottom margin of
    <code>2rem</code>.
  </p>
</div>

<p>I am <code>2rem</code> below the element above.</p>
```

### CSS

```css
div {
  margin: 2rem 0;
  background: lavender;
}

p {
  margin: 0.4rem 0 1.2rem 0;
  background: yellow;
}
```

### Result

See also
--------

* CSS key concepts:
    + CSS syntax
    + At-rules
    + Comments
    + Specificity
    + Inheritance
    + Box model
    + Layout modes
    + Visual formatting models
    + Values
        - Initial values
        - Computed values
        - Used values
        - Actual values
    + Value definition syntax
    + Shorthand properties
    + Replaced elements


font-display
============

The **`font-display`** descriptor for the `@font-feature-values` at-rule sets the default value of how a font face is displayed based on whether and when it is downloaded. Setting a value for the `font-display` descriptor within a `@font-feature-values` block sets the default value of the `font-display` descriptor for the `@font-face` at-rule for all the fonts with the same `font-family` value.

Syntax
------

```css
/\* Keyword values \*/
font-display: auto;
font-display: block;
font-display: swap;
font-display: fallback;
font-display: optional;
```

### Values

`auto`

The font display strategy is defined by the user agent.

`block`

Gives the font face a short block period, generally around 3 seconds, and an infinite swap period.

`swap`

Gives the font face an extremely small block period and an infinite swap period.

`fallback`

Gives the font face an extremely small block period and a short swap period.

`optional`

Gives the font face an extremely small block period and no swap period.

Description
-----------

The `font-display` descriptor for `@font-feature-values` determines the font display timeline; it does so by setting a default `font-display` value for `@font-face` for the same `font-family` name. When `font-display` is omitted in `@font-face`, the user agent first looks for the `font-display` value that has been set via `@font-feature-values` for the relevant font-family. If no value is found, the user agent uses the `auto` value for `font-display`, in which case, the user agent determines the font display strategy.

The font display timeline is based on a timer that starts when the user agent attempts to use a specific downloaded font face. The timeline is divided into three periods, as listed below. These periods dictate the rendering behavior of any element that uses the font face.

* Font **block** period: If the font face is not loaded, elements attempting to use the font are rendered with an *invisible* fallback font face. The browser blocks visible text rendering, saving a space for the to-be-displayed text based on metrics of the fallback font. During the block period, text is not visible. At the end of the block period, if the font has not loaded, the text is rendered in the fallback font.
* Font **swap** period: The swap period occurs after the block period (if there is one) and if the font face has not yet been loaded successfully. Elements attempting to use the not-yet-loaded font are rendered using the next available fallback font face. The formerly invisible fallback font face is painted onto the screen. If the font loads successfully during the swap period, the text that was rendered in the fallback font is updated — or swapped — with the newly loaded font. This step triggers a repaint.
* Font **failure** period: If the font face has not loaded by the time the swap period expires or by the time the block period expires (if there is no swap period, as is the case with `optional`), the user agent treats the font as a failed load. As a result, the content becomes visible in the fallback font.

The `font-display` descriptor allows you to set a default display policy for all `@font-face` rules, including those not under author control, such as third-party `@font-face` rules. When the `font-display` value is set via `@font-feature-values`, it becomes the default `font-display` value, and is applied to the entire font-family. However, any `font-display` value defined within individual `@font-face` blocks will override this default, but only for those blocks where the descriptor is defined.

Examples
--------

```css
@font-feature-values "Leitura" {
  font-display: swap;
  @swash {
    fancy: 1;
  }
}
```

The `font-display` descriptor in this example sets the default `font-display` value for the "Leitura" font to `swap` for all the `@font-face` blocks. Now there might be several `@font-face` blocks importing multiple font files for a single font-family. If one of those `@font-face` blocks includes a `font-display` descriptor, the specified value will be used for that specific font file only. All other blocks not including a `font-display` descriptor will default to `swap` instead of the user-agent's standard default `auto`.

Specifications
--------------

| Specification |
| --- |
| CSS Fonts Module Level 4 # descdef-font-feature-values-font-display |

Browser compatibility
---------------------

There is no browser implementing this feature.

See also
--------

* `font-display` descriptor for `@font-face` at-rule
* `CSS fonts` module


Box alignment in flexbox - CSS: Cascading Style Sheets

Box alignment in flexbox
========================

The box alignment Specification details how alignment works in various layout methods; on this page, we explore how box alignment works in the context of Flexbox. As this page aims to detail things which are specific to Flexbox and box alignment, it should be read in conjunction with the main box alignment page which details the common features of box alignment across layout methods.

Basic example
-------------

In this example, three flex items are aligned on the main axis using `justify-content` and on the cross axis using `align-items`. The first item overrides the `align-items` values set on the group by setting `align-self` to `center`.

The axes and flex-direction
---------------------------

Flexbox respects the writing mode of the document, therefore if you are working in English and set `justify-content` to `flex-end` this will align the items to the end of the flex container. If you are working with `flex-direction` set to `row`, this alignment will be in the inline direction.

However, in Flexbox you can change the main axis by setting `flex-direction` to `column`. In this case, `justify-content` will align items in the block direction. Therefore it is easiest to think about the main and cross axis when working in Flexbox like so:

* The main axis = direction set by `flex-direction` = alignment via `justify-content`
* The cross axis = runs across the main axis = alignment via `align-content`, `align-self`/`align-items`
### Main Axis Alignment

* `justify-content`
### Cross Axis Alignment

* `align-self`
* `align-items`
* `align-content`
### There is no justify-self in Flexbox

On the main axis, Flexbox deals with our content as a group. The amount of space required to lay out the items is calculated, and the leftover space is then available for distribution. The `justify-content` property controls how that leftover space is used. Set `justify-content: flex-end` and the extra space is placed before the items, `justify-content: space-around` and it is placed either side of the item in that dimension, etc.

This means that a `justify-self` property does not make sense in Flexbox as we are always dealing with moving the entire group of items around.

On the cross axis `align-self` makes sense as we potentially have additional space in the flex container in that dimension, in which a single item can be moved to the start and end.

Alignment and auto margins
--------------------------

There is a specific use case in Flexbox where we might think that a `justify-self` property is what we need, and this is when we want to split a set of flex items, perhaps to create a split navigation pattern. For this use case, we can use an `auto` margin. A margin set to `auto` will absorb all available space in its dimension. This is how centering a block with auto margins works. By setting the left and right margin to `auto`, both sides of our block try to take up all of the available space and so push the box into the center.

By setting a `margin` of `auto` on one item in a set of flex items all aligned to start, we can create a split navigation. This works well with Flexbox and the alignment properties. As soon as there is no space available for the auto margin, the item behaves in the same way as all the other flex items and shrinks to try to fit into space.

The `gap` properties
--------------------

* `row-gap`
* `column-gap`
* `gap`
### Creating fixed size gaps between items

On the main axis, the `column-gap` property creates fixed size gaps between adjacent items.

On the cross axis the `row-gap` property creates spacing between adjacent flex lines, therefore `flex-wrap` must also be set to `wrap` for this to have any effect.

Reference
---------

### CSS Properties

* `justify-content`
* `align-content`
* `place-content`
* `justify-items`
* `align-items`
* `place-items`
* `align-self`
* `row-gap`
* `column-gap`
* `gap`
### Glossary Entries

* Cross axis
* Main axis
Guides
------

* Alignment in flexbox
External Resources
------------------

* CSS Grid, Flexbox and Box Alignment
* Thoughts on partial implementations of Box Alignment


Box alignment in multi-column layout - CSS: Cascading Style Sheets

Box alignment in multi-column layout
====================================

The box alignment specification details how alignment works in various layout methods; on this page we explore how Box Alignment works in the context of multi-column Layout. As this page aims to detail things which are specific to Multi-column Layout and Box Alignment, it should be read in conjunction with the main box alignment page which details the common features of Box Alignment across layout methods.

In multi-column layout the alignment container is the content box of the multicol container. The alignment subject is the column box. The properties which apply to multi-column layouts are detailed below.

**Note:** Multi-column layout predates the box alignment specification. And the properties listed here, while specified for Multicol, may not be supported in browsers.

align-content and justify-content
---------------------------------

The `align-content` property applies to the block axis and `justify-content` to the inline axis. Any spacing added to the columns due to use of space distribution will be added to the gap between the columns, therefore making the gap larger than might be specified by the `column-gap` property.

Using a value of `justify-content` other than `normal` or `stretch` will cause column boxes to display at the `column-width` specified on the multicol container, and the remaining space distributed according to the value of justify-content.

column-gap
----------

The `column-gap` property was specified in earlier versions of the multiple-column layout specification, and has now been unified with the gap properties for other layout methods in box alignment. While other layout methods treat the initial value of column-gap as 0 multicol treats it as 1em, as in general you would not want to have no gap between columns.

Reference
---------

### CSS Properties

* `justify-content`
* `align-content`
* `column-gap`
### Glossary Entries

* Alignment subject
* Alignment container
* Fallback alignment


Box alignment for block, absolutely positioned, and table layouts - CSS: Cascading Style Sheets

Box alignment for block, absolutely positioned, and table layouts
=================================================================

The box alignment specification details how alignment works in various layout methods. In this page we explore how box alignment works in the context of block layout, including floated, positioned, and table elements. As this page aims to detail things which are specific to block layout and box alignment, it should be read in conjunction with the main box alignment page, which details the common features of box alignment across layout methods.

**Note:** At the time of writing (May 2018), there is no real support for the box alignment properties in block layout. This document details how the specification expects these properties to be implemented for completeness, and is likely to change as the specification and browser implementations develop.

align-content and justify-content
---------------------------------

The `justify-content` property does not apply to block containers or table cells.

The `align-content` property applies to the block axis in order to align the contents of the box within its container. If a content distribution method such as `space-between`, `space-around` or `space-evenly` is requested then the fallback alignment will be used, as the content is treated as a single alignment subject.

justify-self
------------

The `justify-self` property is used to align an item inside its containing block on the inline axis.

This property does not apply to floated elements or table cells.

align-self
----------

The `align-self` property does not apply to block-level boxes (including floats), because there is more than one item in the block axis. It also does not apply to table cells.

### Absolutely positioned elements

The alignment container is the positioned block, accounting for the offset values of top, left, bottom, and right. The normal keyword resolves to `stretch`, unless the positioned item is a replaced element, in which case it resolves to `start`.

Aligning in these layout methods today
--------------------------------------

As we do not currently have browser support for box alignment in block layout, your options for alignment are either to use one of the existing alignment methods or, to make even a single item inside a container a flex item in order to use the alignment properties as specified in flexbox.

Alignment of blocks horizontally prior to flexbox was typically achieved by way of setting auto margins on the block. A `margin` of `auto` will absorb all available space in that dimension, therefore setting a left and right margin of auto, you can push a block into the center:

```css
.container {
  width: 20em;
  margin-left: auto;
  margin-right: auto;
}
```

In table layout, you have access to the `vertical-align` property to align the contents of a cell inside that cell.

For many use cases, turning the block container into a flex item will give you the alignment capability that you are looking for. In the example below, a container with a single item inside has been turned into a flex container for the purpose of being able to use the alignment properties.

Reference
---------

### CSS Properties

* `justify-content`
* `align-content`
* `justify-self`
* `align-self`
### Glossary Entries

* Alignment subject
* Alignment container
* Fallback alignment


Box alignment in grid layout - CSS: Cascading Style Sheets

Box alignment in grid layout
============================

The box alignment specification details how alignment works in various layout methods. On this page we explore how box alignment works in the context of CSS grid layout.

As this page aims to detail things which are specific to CSS Grid Layout and Box Alignment, it should be read in conjunction with the main box alignment page which details the common features of box alignment across layout methods.

Basic example
-------------

In this example using grid layout, there is extra space in the grid container after laying out the fixed width tracks on the inline (main) axis. This space is distributed using `justify-content`. On the block (cross) axis the alignment of the items inside their grid areas is controlled with `align-items`. The first item overrides the `align-items` value set on the group by setting `align-self` to `center`.

Grid axes
---------

As a two-dimensional layout method, when working with grid layout we always have two axes on which to align our items. We have access to all of the box alignment properties to help us achieve this.

The inline axis is the axis that corresponds to the direction that words in a sentence would run in the writing mode used. Therefore, in a horizontal language such as English or Arabic the inline direction runs horizontally. Should you be in a vertical writing mode the inline axis will run vertically.

![Inline axes are horizontal.](/en-US/docs/Web/CSS/CSS_box_alignment/Box_alignment_in_grid_layout/inline_axis.png)

To align things on the inline axis you use the properties that start with `justify-`, `justify-content`, `justify-items` and `justify-self`.

The block axis crosses the inline axis in the direction that blocks are displayed down the page — for example paragraphs in English are displayed one below the other vertically. This, therefore is the block dimension.

To align things on the block axis you use the properties that start with `align-`, `align-content`, `align-items` and `align-self`.

![The block axes are vertical.](/en-US/docs/Web/CSS/CSS_box_alignment/Box_alignment_in_grid_layout/block_axis.png)

Self alignment
--------------

* `justify-self`
* `align-self`
* `place-self`
* `justify-items`
* `align-items`
* `place-items`

These properties deal with aligning the item inside the grid area it is placed into. The properties `align-items` and `justify-items` are applied to the grid container and set the `align-self` and `justify-self` properties as a group. This means that you can set alignment for all of your grid Items at once, then override any items that need a different alignment by applying the `align-self` or `justify-self` property to the rules for the individual grid Items.

The initial value for `align-self` and `justify-self` is `stretch` so the item will stretch over the entire grid area. The exception to this rule is where the item has an intrinsic aspect ratio, for example an image. In this case the item will be aligned to `start` in both dimensions in order that the image is not distorted.

Content alignment
-----------------

* `justify-content`
* `align-content`
* `place-content`

These properties deal with aligning the tracks of the grid when there is extra space to distribute. This scenario will occur if the tracks that you have defined total less than the total width of the grid container.

Gap and legacy grid-gap properties
----------------------------------

* `row-gap`
* `column-gap`
* `gap`

The Grid specification originally contained the definition for the properties `grid-row-gap`, `grid-column-gap` and `grid-gap`. These have since been moved into the Box Alignment specification and renamed to `row-gap`, `column-gap`, and `gap`. This allows them to be used for other layout methods where a gap between items makes sense.

The updated properties have not yet been implemented in all browsers. Therefore, to use the gap properties in grid layout, you should use the `grid-row-gap`, `grid-column-gap` and `grid-gap` versions to ensure full compatibility. You could double up the properties and use both as you would for vendor prefixes.

Reference
---------

### CSS Properties

* `justify-content`
* `align-content`
* `place-content`
* `justify-items`
* `align-items`
* `place-items`
* `justify-self`
* `align-self`
* `place-self`
* `row-gap`
* `column-gap`
* `gap`
### Glossary Entries

* Cross Axis
* Main Axis
Guides
------

* Alignment in grid layout
External Resources
------------------

* CSS Grid, Flexbox and Box Alignment
* Thoughts on partial implementations of Box Alignment


Using CSS animations - CSS: Cascading Style Sheets

Using CSS animations
====================

**CSS animations** make it possible to animate transitions from one CSS style configuration to another. Animations consist of two components, a style describing the CSS animation and a set of keyframes that indicate the start and end states of the animation's style, as well as possible intermediate waypoints.

There are three key advantages to CSS animations over traditional script-driven animation techniques:

1. They're easy to use for simple animations; you can create them without even having to know JavaScript.
2. The animations run well, even under moderate system load. Simple animations can often perform poorly in JavaScript. The rendering engine can use frame-skipping and other techniques to keep the performance as smooth as possible.
3. Letting the browser control the animation sequence lets the browser optimize performance and efficiency by, for example, reducing the update frequency of animations running in tabs that aren't currently visible.
Configuring an animation
------------------------

To create a CSS animation sequence, you style the element you want to animate with the `animation` property or its sub-properties. This lets you configure the timing, duration, and other details of how the animation sequence should progress. This does **not** configure the actual appearance of the animation, which is done using the `@keyframes` at-rule as described in the Defining animation sequence using keyframes section below.

The sub-properties of the `animation` property are:

`animation-composition`

Specifies the composite operation to use when multiple animations affect the same property simultaneously. This property is not part of the `animation` shorthand property.

`animation-delay`

Specifies the delay between an element loading and the start of an animation sequence and whether the animation should start immediately from its beginning or partway through the animation.

`animation-direction`

Specifies whether an animation's first iteration should be forward or backward and whether subsequent iterations should alternate direction on each run through the sequence or reset to the start point and repeat.

`animation-duration`

Specifies the length of time in which an animation completes one cycle.

`animation-fill-mode`

Specifies how an animation applies styles to its target before and after it runs.

`animation-iteration-count`

Specifies the number of times an animation should repeat.

`animation-name`

Specifies the name of the `@keyframes` at-rule describing an animation's keyframes.

`animation-play-state`

Specifies whether to pause or play an animation sequence.

`animation-timeline`
Experimental

Specifies the timeline that is used to control the progress of a CSS animation.

`animation-timing-function`

Specifies how an animation transitions through keyframes by establishing acceleration curves.

Defining animation sequence using keyframes
-------------------------------------------

After you've configured the animation's timing, you need to define the appearance of the animation. This is done by establishing one or more keyframes using the `@keyframes` at-rule. Each keyframe describes how the animated element should render at a given time during the animation sequence.

Since the timing of the animation is defined in the CSS style that configures the animation, keyframes use a `<percentage>` to indicate the time during the animation sequence at which they take place. 0% indicates the first moment of the animation sequence, while 100% indicates the final state of the animation. Because these two times are so important, they have special aliases: `from` and `to`. Both are optional. If `from`/`0%` or `to`/`100%` is not specified, the browser starts or finishes the animation using the computed values of all attributes.

You can optionally include additional keyframes that describe intermediate steps between the start and end of the animation.

Using the animation shorthand
-----------------------------

The `animation` shorthand is useful for saving space. As an example, some of the rules we've been using through this article:

```css
p {
  animation-duration: 3s;
  animation-name: slidein;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}
```

...could be replaced by using the `animation` shorthand.

```css
p {
  animation: 3s infinite alternate slidein;
}
```

To learn more about the sequence in which different animation property values can be specified using the `animation` shorthand, see the `animation` reference page.

Setting multiple animation property values
------------------------------------------

The CSS animation longhand properties can accept multiple values, separated by commas. This feature can be used when you want to apply multiple animations in a single rule and set different durations, iteration counts, etc., for each of the animations. Let's look at some quick examples to explain the different permutations.

In this first example, there are three duration and three iteration count values. So each animation is assigned a value of duration and iteration count with the same position as the animation name. The `fadeInOut` animation is assigned a duration of `2.5s` and an iteration count of `2`, and the `bounce` animation is assigned a duration of `1s` and an iteration count of `5`.

```css
animation-name: fadeInOut, moveLeft300px, bounce;
animation-duration: 2.5s, 5s, 1s;
animation-iteration-count: 2, 1, 5;
```

In this second example, three animation names are set, but there's only one duration and iteration count. In this case, all three animations are given the same duration and iteration count.

```css
animation-name: fadeInOut, moveLeft300px, bounce;
animation-duration: 3s;
animation-iteration-count: 1;
```

In this third example, three animations are specified, but only two durations and iteration counts. In such cases where there are not enough values in the list to assign a separate one to each animation, the value assignment cycles from the first to the last item in the available list and then cycles back to the first item. So, `fadeInOut` gets a duration of `2.5s`, and `moveLeft300px` gets a duration of `5s`, which is the last value in the list of duration values. The duration value assignment now resets to the first value; `bounce`, therefore, gets a duration of `2.5s`. The iteration count values (and any other property values you specify) will be assigned in the same way.

```css
animation-name: fadeInOut, moveLeft300px, bounce;
animation-duration: 2.5s, 5s;
animation-iteration-count: 2, 1;
```

If the mismatch in the number of animations and animation property values is inverted, say there are five `animation-duration` values for three `animation-name` values, then the extra or unused animation property values, in this case, two `animation-duration` values, don't apply to any animation and are ignored.

Examples
--------

**Note:** Some older browsers (pre-2017) may need prefixes; the live examples you can click to see in your browser include the `-webkit` prefixed syntax.

### Making text slide across the browser window

This simple example styles the `<p>` element so that the text slides in from off the right edge of the browser window.

Note that animations like this can cause the page to become wider than the browser window. To avoid this problem put the element to be animated in a container, and set `overflow``:hidden` on the container.

```css
p {
  animation-duration: 3s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%;
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}
```

In this example the style for the `<p>` element specifies that the animation should take 3 seconds to execute from start to finish, using the `animation-duration` property, and that the name of the `@keyframes` at-rule defining the keyframes for the animation sequence is named "slidein".

If we wanted any custom styling on the `<p>` element to appear in browsers that don't support CSS animations, we would include it here as well; however, in this case we don't want any custom styling other than the animation effect.

The keyframes are defined using the `@keyframes` at-rule. In this case, we have just two keyframes. The first occurs at 0% (using the alias `from`). Here, we configure the left margin of the element to be at 100% (that is, at the far right edge of the containing element), and the width of the element to be 300% (or three times the width of the containing element). This causes the first frame of the animation to have the header drawn off the right edge of the browser window.

The second (and final) keyframe occurs at 100% (using the alias `to`). The left margin is set to 0% and the width of the element is set to 100%. This causes the header to finish its animation flush against the left edge of the content area.

```html
<p>
  The Caterpillar and Alice looked at each other for some time in silence: at
  last the Caterpillar took the hookah out of its mouth, and addressed her in a
  languid, sleepy voice.
</p>
```

**Note:** Reload page to see the animation.

### Adding another keyframe

Let's add another keyframe to the previous example's animation. Let's say we want the header's font size to increase as it moves from right to left for a while, then to decrease back to its original size. That's as simple as adding this keyframe:

```css
75% {
  font-size: 300%;
  margin-left: 25%;
  width: 150%;
}
```

The full code now looks like this:

```css
p {
  animation-duration: 3s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%;
  }

  75% {
    font-size: 300%;
    margin-left: 25%;
    width: 150%;
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}
```

```html
<p>
  The Caterpillar and Alice looked at each other for some time in silence: at
  last the Caterpillar took the hookah out of its mouth, and addressed her in a
  languid, sleepy voice.
</p>
```

This tells the browser that 75% of the way through the animation sequence, the header should have its left margin at 25% and the width should be 150%.

**Note:** Reload page to see the animation.

### Repeating the animation

To make the animation repeat itself, use the `animation-iteration-count` property to indicate how many times to repeat the animation. In this case, let's use `infinite` to have the animation repeat indefinitely:

```css
p {
  animation-duration: 3s;
  animation-name: slidein;
  animation-iteration-count: infinite;
}
```

Adding it to the existing code:

```css
@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%;
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}
```

```html
<p>
  The Caterpillar and Alice looked at each other for some time in silence: at
  last the Caterpillar took the hookah out of its mouth, and addressed her in a
  languid, sleepy voice.
</p>
```

### Making the animation move back and forth

That made it repeat, but it's very odd having it jump back to the start each time it begins animating. What we really want is for it to move back and forth across the screen. That's easily accomplished by setting `animation-direction` to `alternate`:

```css
p {
  animation-duration: 3s;
  animation-name: slidein;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}
```

And the rest of the code:

```css
@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%;
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}
```

```html
<p>
  The Caterpillar and Alice looked at each other for some time in silence: at
  last the Caterpillar took the hookah out of its mouth, and addressed her in a
  languid, sleepy voice.
</p>
```

### Using animation events

You can get additional control over animations — as well as useful information about them — by making use of animation events. These events, represented by the `AnimationEvent` object, can be used to detect when animations start, finish, and begin a new iteration. Each event includes the time at which it occurred as well as the name of the animation that triggered the event.

We'll modify the sliding text example to output some information about each animation event when it occurs, so we can get a look at how they work.

#### Adding the CSS

We start with creating the CSS for the animation. This animation will last for 3 seconds, be called "slidein", repeat 3 times, and alternate direction each time. In the `@keyframes`, the width and margin-left are manipulated to make the element slide across the screen.

```css
.slidein {
  animation-duration: 3s;
  animation-name: slidein;
  animation-iteration-count: 3;
  animation-direction: alternate;
}

@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%;
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}
```

#### Adding the animation event listeners

We'll use JavaScript code to listen for all three possible animation events. This code configures our event listeners; we call it when the document is first loaded in order to set things up.

```js
const element = document.getElementById("watchme");
element.addEventListener("animationstart", listener, false);
element.addEventListener("animationend", listener, false);
element.addEventListener("animationiteration", listener, false);

element.className = "slidein";
```

This is pretty standard code; you can get details on how it works in the documentation for `eventTarget.addEventListener()`. The last thing this code does is set the `class` on the element we'll be animating to "slidein"; we do this to start the animation.

Why? Because the `animationstart` event fires as soon as the animation starts, and in our case, that happens before our code runs. So we'll start the animation ourselves by setting the class of the element to the style that gets animated after the fact.

#### Receiving the events

The events get delivered to the `listener()` function, which is shown below.

```js
function listener(event) {
  const l = document.createElement("li");
  switch (event.type) {
    case "animationstart":
      l.textContent = `Started: elapsed time is ${event.elapsedTime}`;
      break;
    case "animationend":
      l.textContent = `Ended: elapsed time is ${event.elapsedTime}`;
      break;
    case "animationiteration":
      l.textContent = `New loop started at time ${event.elapsedTime}`;
      break;
  }
  document.getElementById("output").appendChild(l);
}
```

This code, too, is very simple. It looks at the `event.type` to determine which kind of animation event occurred, then adds an appropriate note to the `<ul>` (unordered list) we're using to log these events.

The output, when all is said and done, looks something like this:

* Started: elapsed time is 0
* New loop started at time 3.01200008392334
* New loop started at time 6.00600004196167
* Ended: elapsed time is 9.234000205993652

Note that the times are very close to, but not exactly, those expected given the timing established when the animation was configured. Note also that after the final iteration of the animation, the `animationiteration` event isn't sent; instead, the `animationend` event is sent.

Just for the sake of completeness, here's the HTML that displays the page content, including the list into which the script inserts information about the received events:

```html
<h1 id="watchme">Watch me move</h1>
<p>
  This example shows how to use CSS animations to make <code>H1</code>
  elements move across the page.
</p>
<p>
  In addition, we output some text each time an animation event fires, so you
  can see them in action.
</p>
<ul id="output"></ul>
```

And here's the live output.

**Note:** Reload page to see the animation.

### Animating display and content-visibility

This example demonstrates how `display` and `content-visibility` can be animated. This behavior is useful for creating entry/exit animations where you want to for example remove a container from the DOM with `display: none`, but have it fade out smoothly with `opacity` rather than disappearing immediately.

Supporting browsers animate `display` and `content-visibility` with a variation on the discrete animation type. This generally means that properties will flip between two values 50% of the way through animating between the two.

There is an exception, however, which is when animating to/from `display: none` or `content-visibility: hidden` to a visible value. In this case, the browser will flip between the two values so that the animated content is shown for the entire animation duration.

So for example:

* When animating `display` from `none` to `block` (or another visible `display` value), the value will flip to `block` at `0%` of the animation duration so it is visible throughout.
* When animating `display` from `block` (or another visible `display` value) to `none`, the value will flip to `none` at `100%` of the animation duration so it is visible throughout.

#### HTML

The HTML contains two `<p>` elements with a `<div>` in between that we will animate from `display` `none` to `block`.

```html
<p>
  Click anywhere on the screen or press any key to toggle the
  <code><div></code> between hidden and showing.
</p>

<div>
  This is a <code><div></code> element that animates between
  <code>display: none; opacity: 0</code> and
  <code>display: block; opacity: 1</code>. Neat, huh?
</div>

<p>
  This is another paragraph to show that <code>display: none; </code> is being
  applied and removed on the above <code><div> </code>. If only its
  <code>opacity</code> was being changed, it would always take up the space in
  the DOM.
</p>
```

#### CSS

```css
html {
  height: 100vh;
}

div {
  font-size: 1.6rem;
  padding: 20px;
  border: 3px solid red;
  border-radius: 20px;
  width: 480px;
  opacity: 0;
  display: none;
}

/\* Animation classes \*/

div.fade-in {
  display: block;
  animation: fade-in 0.7s ease-in forwards;
}

div.fade-out {
  animation: fade-out 0.7s ease-out forwards;
}

/\* Animation keyframes \*/

@keyframes fade-in {
  0% {
    opacity: 0;
    display: none;
  }

  100% {
    opacity: 1;
    display: block;
  }
}

@keyframes fade-out {
  0% {
    opacity: 1;
    display: block;
  }

  100% {
    opacity: 0;
    display: none;
  }
}
```

Note the inclusion of the `display` property in the keyframe animations.

#### JavaScript

Finally, we include a bit of JavaScript to set up event listeners to trigger the animations. Specifically, we add the `fade-in` class to the `<div>` when we want it to appear, and `fade-out` when we want it to disappear.

```js
const divElem = document.querySelector("div");
const htmlElem = document.querySelector(":root");

htmlElem.addEventListener("click", showHide);
document.addEventListener("keydown", showHide);

function showHide() {
  if (divElem.classList[0] === "fade-in") {
    divElem.classList.remove("fade-in");
    divElem.classList.add("fade-out");
  } else {
    divElem.classList.remove("fade-out");
    divElem.classList.add("fade-in");
  }
}
```

#### Result

The code renders as follows:

See also
--------

* `AnimationEvent`
* CSS animation tips and tricks
* Using CSS transitions


CSS animation tips and tricks - CSS: Cascading Style Sheets

CSS animation tips and tricks
=============================

CSS animations make it possible to do incredible things with the elements that make up your documents and apps. However, there are things you might want to do that aren't obvious, or clever ways to do things that you might not come up with right away. This article is a collection of tips and tricks we've found that may make your work easier, including how to run a stopped animation again.

Run an animation again
----------------------

The CSS Animations specification doesn't offer a way to run an animation again. There's no magic `resetAnimation()` method on elements, and you can't even just set the element's `animation-play-state` to `"running"` again. Instead, you have to use clever tricks to get a stopped animation to replay.

Here's one way to do it that we feel is stable and reliable enough to suggest to you.

### HTML

First, let's define the HTML for a `<div>` we wish to animate and a button that will play (or replay) the animation.

```html
<div class="box"></div>

<div class="runButton">Click me to run the animation</div>
```

### CSS

Now we'll define the animation itself using CSS. Some CSS that's not important (the style of the "Run" button itself) isn't shown here, for brevity.
```

.runButton {
  cursor: pointer;
  width: 300px;
  border: 1px solid black;
  font-size: 16px;
  text-align: center;
  margin-top: 12px;
  padding-top: 2px;
  padding-bottom: 4px;
  color: white;
  background-color: darkgreen;
  font:
    14px "Open Sans",
    "Arial",
    sans-serif;
}
```

```css
@keyframes colorchange {
  0% {
    background: yellow;
  }
  100% {
    background: blue;
  }
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

.changing {
  animation: colorchange 2s;
}
```

There are two classes here. The `"box"` class is the basic description of the box's appearance, without any animation information included. The animation details are included in the `"changing"` class, which says that the `@keyframes` named `"colorchange"` should be used over the course of two seconds to animate the box.

Note that because of this, the box doesn't start with any animation effects in place, so it won't be animating.

### JavaScript

Next we'll look at the JavaScript that does the work. The meat of this technique is in the `play()` function, which is called when the user clicks on the "Run" button.

```js
function play() {
  document.querySelector(".box").className = "box";
  requestAnimationFrame((time) => {
    requestAnimationFrame((time) => {
      document.querySelector(".box").className = "box changing";
    });
  });
}
```

This looks weird, doesn't it? That's because the only way to play an animation again is to remove the animation effect, let the document recompute styles so that it knows you've done that, then add the animation effect back to the element. To make that happen, we have to be creative.

Here's what happens when the `play()` function gets called:

1. The box's list of CSS classes is reset to `"box"`. This has the effect of removing any other classes currently applied to the box, including the `"changing"` class that handles animation. In other words, we're removing the animation effect from the box. However, changes to the class list don't take effect until the style recomputation is complete and a refresh has occurred to reflect the change.
2. To be sure that the styles are recalculated, we use `window.requestAnimationFrame()`, specifying a callback. Our callback gets executed just before the next repaint of the document. The problem for us is that because it's before the repaint, the style recomputation hasn't actually happened yet!
3. Our callback cleverly calls `requestAnimationFrame()` a second time! This time, the callback is run before the next repaint, which is after the style recomputation has occurred. This callback adds the `"changing"` class back onto the box, so that the repaint will start the animation once again.

Of course, we also need to add an event handler to our "Run" button so it'll actually do something:

```js
document.querySelector(".runButton").addEventListener("click", play, false);
```

### Result

Stopping an animation
---------------------

Removing the `animation-name` applied to an element will make it jump or cut to its next state. If instead you'd like the animation to complete and then come to a stop you have to try a different approach. The main tricks are:

1. Make your animation as self-contained as possible. This means you should not rely on `animation-direction: alternate`. Instead you should explicitly write a keyframe animation that goes through the full animation in one forward repetition.
2. Use JavaScript and clear the animation being used when the `animationiteration` event fires.

The following demo shows how you'd achieve the aforementioned JavaScript technique:

```css
.slidein {
  animation-duration: 5s;
  animation-name: slidein;
  animation-iteration-count: infinite;
}

.stopped {
  animation-name: none;
}

@keyframes slidein {
  0% {
    margin-left: 0%;
  }
  50% {
    margin-left: 50%;
  }
  100% {
    margin-left: 0%;
  }
}
```

```html
<h1 id="watchme">Click me to stop</h1>
```

```js
const watchme = document.getElementById("watchme");

watchme.className = "slidein";
const listener = (e) => {
  watchme.className = "slidein stopped";
};
watchme.addEventListener("click", () =>
  watchme.addEventListener("animationiteration", listener, false),
);
```

Demo https://jsfiddle.net/morenoh149/5ty5a4oy/

See also
--------

* Using CSS transitions
* `Window.requestAnimationFrame()`


Using CSS math functions - CSS: Cascading Style Sheets

Using CSS math functions
========================

**CSS math functions** allow a property value - such as the `height`, `animation-duration`, or `font-size` of an element - to be written as a mathematical expression.

Without using any math, the built-in CSS units like `rem`, `vw`, and `%` are often flexible enough to style HTML elements to achieve a particular user experience.

However, there are cases where we might feel limited by expressing an element's style using a single value and unit. Consider the following examples:

1. We want to set the height of a content area to be "the height of the viewport minus the height of a navbar."
2. We want to add the width of two elements together to define the width of a third element.
3. We want to prevent a variable `font-size` of some text from growing beyond a certain size.

In all of these cases, we need to rely on math to achieve the desired outcomes. One solution could be to rely on mathematical functions defined by JavaScript, and dynamically set element styles based on results calculated by our scripts.

In many instances, including in the examples above, **we can instead utilize math functions built directly into CSS**. This solution is often simpler to implement and faster for the browser to execute than using JavaScript.

In total, developers can use a combination of nearly two dozen CSS math functions in their stylesheets. In this guide, we'll exemplify four of the more commonly-used, and introduce those more advanced.

`calc()`: Basic math operations
-------------------------------

In the first two of our three examples above, we want to set the style of an element according to the result of an addition or subtraction operation. This is exactly one of the use cases for `calc()`.

The **`calc()`** function lets you specify CSS property values using **addition, subtraction, multiplication, and division**. It is often used to combine two CSS values that have different units, such as `%` and `px`.

The `calc()` math function takes a mathematical expression as a parameter and returns the result of that expression, e.g.:

```css
property: calc(expression);
```

### `calc()` Example

Click on the play icon below to see the `calc()` example in the code playground and try it for yourself.
```

<div class="calc1">
  <code>width: calc(10px + 100px);</code>
</div>
<div class="calc2">
  <code>width: calc(2em * 5);</code>
</div>
<div class="calc3">
  <code>width: calc(100% - 32px);</code>
</div>
<div class="calc4">
  <code>width: calc(var(--predefined-width) - calc(16px * 2));</code>
</div>
```

```css
div {
  background-color: black;
  margin: 4px 0;
  width: 100%;
}

div > code {
  display: block;
  background-color: red;
  color: white;
  height: 48px;
}

.calc1 > code {
  /\* Output width: `110px` \*/
  width: calc(10px + 100px);
}

.calc2 > code {
  /\* Output width: `10em` \*/
  width: calc(2em * 5);
}

.calc3 > code {
  /\* Output width: Depends on the container's width \*/
  width: calc(100% - 32px);
}

.calc4 > code {
  --predefined-width: 100%;
  /\* Output width: Depends on the container's width \*/
  width: calc(var(--predefined-width) - calc(16px * 2));
}
```

`min()`: Finding the minimum value in a set
-------------------------------------------

There are cases where we don't want the value of a CSS property to exceed a certain number. Say, for example, we want the width of our content container to be the smaller of "the full width of our screen" and "500 pixels." In those cases, we can use the CSS math function `min()`.

The `min()` math function takes a set of comma-separated values as arguments and returns the smallest of those values, e.g.:

```css
property: min(<first value>, <second value>, <third value>, ...);
```

This function is often used to compare two CSS values that have different units, such as `%` and `px`.

### `min()` Example

Click on the play icon below to see the `min()` example in the code playground and try it for yourself.
```

<div class="min1">
  <code>width: min(9999px, 50%);</code>
</div>
<div class="min2">
  <code>width: min(9999px, 100%);</code>
</div>
<div class="min3">
  <code>width: min(120px, 150px, 90%);</code>
</div>
<div class="min4">
  <code>width: min(80px, 90%);</code>
</div>
```

```css
div {
  background-color: black;
  margin: 4px 0;
  width: 100%;
}

div > code {
  display: block;
  background-color: darkblue;
  color: white;
  height: 48px;
}

.min1 > code {
  /\* Output width: Depends on the container's width; \*/
  /\* on this page, likely to be `50%` of the container's width \*/
  width: min(9999px, 50%);
}

.min2 > code {
  /\* Output width: Depends on the container's width; \*/
  /\* on this page, likely to be `100%` of the container's width \*/
  width: min(9999px, 100%);
}

.min3 > code {
  /\* Output width: Depends on the container's width; \*/
  /\* on this page, likely to be `120px` of the container's width \*/
  width: min(120px, 150px, 90%);
}

.min4 > code {
  /\* Output width: Depends on the container's width; \*/
  /\* on this page, likely to be `80px` of the container's width \*/
  width: min(80px, 90%);
}
```

`max()`: Finding the maximum value in a set
-------------------------------------------

Similar to `min()`, sometimes we don't want the value of a CSS property to go below a certain number. For example, we might want the width of our content container to be the *larger* of "the full width of our screen" and "500 pixels." In those cases, we can use the CSS math function `max()`.

The `max()` math function takes a set of comma-separated values as arguments and returns the largest of those values, e.g.:

```css
property: max(<first value>, <second value>, <third value>, ...);
```

This function is often used to compare two CSS values that have different units, such as `%` and `px`.

Notice the similarities and differences between the examples for `min()` and `max()`.

### `max()` Example

Click on the play icon below to see the `max()` example in the code playground and try it for yourself.
```

<div class="max1">
  <code>width: max(50px, 50%);</code>
</div>
<div class="max2">
  <code>width: max(50px, 100%);</code>
</div>
<div class="max3">
  <code>width: max(20px, 50px, 90%);</code>
</div>
<div class="max4">
  <code>width: max(80px, 80%);</code>
</div>
```

```css
div {
  background-color: black;
  margin: 4px 0;
  width: 100%;
  height: 48px;
}

div > code {
  display: block;
  background-color: darkmagenta;
  color: white;
  height: 48px;
}

.max1 > code {
  /\* Output width: Depends on the container's width; \*/
  /\* on this page, likely to be `50%` of the container's width \*/
  width: max(50px, 50%);
}

.max2 > code {
  /\* Output width: Depends on the container's width; \*/
  /\* on this page, likely to be `100%` of the container's width \*/
  width: max(50px, 100%);
}

.max3 > code {
  /\* Output width: Depends on the container's width; \*/
  /\* on this page, likely to be `90%` of the container's width \*/
  width: max(20px, 50px, 90%);
}

.max4 > code {
  /\* Output width: Depends on the container's width; \*/
  /\* on this page, likely to be `80%` of the container's width \*/
  width: max(80px, 80%);
}
```

`clamp()`: Constraining a value between two values
--------------------------------------------------

We can combine the functions of `min()` and `max()` by using `clamp()`. The `clamp()` math function takes a minimum value, the value to be clamped, and the maximum value as arguments, e.g.:

```css
property: clamp(<minimum value>, <value to be clamped>, <maximum value>);
```

* If the value to be clamped is less than the passed minimum value, the function will return the minimum value.
* If the value to be clamped is greater than the passed maximum value, the function will return the maximum value.
* If the value to be clamped is between the passed minimum and maximum values, the function will return the original value to be clamped.

This function is often used to compare two CSS values that have different units, such as `%` and `px`.

### `clamp()` Example

Click on the play icon below to see the `clamp()` example in the code playground and try it for yourself.
```

<div class="clamp1">
  <code>width: clamp(10%, 1px, 90%);</code>
</div>
<div class="clamp2">
  <code>width: clamp(10%, 9999px, 90%);</code>
</div>
<div class="clamp3">
  <code>width: clamp(125px, 1px, 250px);</code>
</div>
<div class="clamp4">
  <code>width: clamp(25px, 9999px, 150px);</code>
</div>
```

```css
div {
  background-color: black;
  margin: 4px 0;
  width: 100%;
  height: 48px;
}

div > code {
  display: block;
  background-color: darkgreen;
  color: white;
  height: 48px;
}

.clamp1 > code {
  /\* Output width: Depends on the container's width; \*/
  /\* on this page, likely to be `20%` of the container's width \*/
  width: clamp(20%, 1px, 80%);
}

.clamp2 > code {
  /\* Output width: Depends on the container's width; \*/
  /\* on this page, likely to be `90%` of the container's width \*/
  width: clamp(10%, 9999px, 90%);
}

.clamp3 > code {
  /\* Output width: `125px` \*/
  width: clamp(125px, 1px, 250px);
}

.clamp4 > code {
  /\* Output width: `150px` \*/
  width: clamp(25px, 9999px, 150px);
}
```

Advanced CSS Math Functions
---------------------------

When laying out and styling DOM elements, the four basic math functions `calc()`, `min()`, `max()`, and `clamp()` are often sufficient. However, for advanced uses like mathematics learning materials, 3D visualizations, or CSS animations, you may consider using:

* Stepped value functions
    + `round()`: calculates a **value given a rounding strategy**
    + `mod()`: calculates the **remainder** of a division operation with the **same sign as the divisor**
    + `rem()`: calculates the **remainder** of a division operation with the **same sign as the dividend**
* Trigonometric functions
    + `sin()`: calculates the **trigonometric sine** of a number
    + `cos()`: calculates the **trigonometric cosine** of a number
    + `tan()`: calculates the **trigonometric tangent** of a number
    + `asin()`: calculates the **trigonometric inverse** sine of a number
    + `acos()`: calculates the **trigonometric inverse** cosine of a number
    + `atan()`: calculates the **trigonometric inverse** tangent of a number
    + `atan2()`: calculates the **trigonometric inverse** tangent given two numbers
* Exponential functions
    + `pow()`: calculates a number **raised to the power** of another number
    + `sqrt()`: calculates the **square root** of a number
    + `hypot()`: calculates the **square root of the sum of the squares** of the given numbers
    + `log()`: calculates the **logarithm** of a number (with `e` as the default base)
    + `exp()`: calculates **`e` raised to the power** of another number
* Sign functions
    + `abs()`: calculates the **absolute value** of a number
    + `sign()`: calculates the **sign (positive, negative, or zero)** of a number
Final thoughts
--------------

* You can use CSS math functions to create responsive user interfaces without writing any JavaScript code.
* CSS math functions can sometimes be used instead of CSS media queries to define layout breakpoints.
* In 2023, members of the Interop Project selected "CSS Math Functions" as a focus area of improvement. This means that browser vendors are working together to ensure that CSS math functions perform the same across browsers and devices.