Coordinate systems - CSS: Cascading Style Sheets

Coordinate systems
==================

When specifying the location of a pixel in a graphics context (just like when specifying coordinate systems in algebra), its position is defined relative to a fixed point in the context. This fixed point is called the origin. The position is specified as the number of pixels offset from the origin along each dimension of the context.

This guide describes the standard coordinate systems used by the CSS object model. These are generally only different in terms of where their origin is located.

Dimensions
----------

In the coordinate systems used by web technologies, convention dictates that the horizontal offset is called the *x-coordinate*, where a negative value indicates a position to the left of the origin and a positive value is to the right of the origin. The *y-coordinate* specifies the vertical offset, with a negative value being above the origin and a positive value being below the origin.

On the web, the default origin is the *top*-left corner of a given context (with positive y-coordinate values being below the origin). Note that this is unlike most mathematical models, where the origin is at the *bottom*-left corner, with positive y-coordinate values being above the origin.

When using the third dimension to layer objects from front to back, we use the z-axis. The z-axis runs from the viewer to the screen's surface. The CSS z-index attribute affects where positioned elements sit on this axis, giving the effect of moving away from or toward the viewer.

**Note:** It's actually possible to change the definitions and orientations of these coordinate systems using CSS properties such as `transform`. However, we'll only talk about the standard coordinate system for now.

Standard CSSOM coordinate systems
---------------------------------

 There are four standard coordinate systems used by the CSS object model.
 To help visualize the main systems, the following diagram shows a monitor with a browser window that contains content scrolled outside of the viewport.
 Page content that is scrolled outside of the viewport is shown as semi-transparent above the browser window to indicate where the origin for "page" coordinates would be.
 The origin of the "client", "page", and "viewport" coordinates systems are highlighted.

![Diagram of a computer monitor with a browser window containing content outside of the viewport. Labels show the origin for page, screen, and viewport coordinates.](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems/css-coords.svg)

### Offset

Coordinates specified using the "offset" model use the top-left corner of the element being examined, or on which an event has occurred.

For example, when a mouse event occurs, the position of the mouse as specified in the event's `offsetX` and `offsetY` properties are given relative to the top-left corner of the node to which the event has been delivered. The origin is inset by the distances specified by `padding-left` and `padding-top`.

### Viewport

The "viewport" (or "client") coordinate system uses as its origin the top-left corner of the viewport or browsing context in which the event occurred. This is the entire viewing area in which the document is presented.

 On a desktop computer, for example, the `MouseEvent.clientX` and `MouseEvent.clientY` properties indicate the position of the mouse cursor at the moment the event occurred, relative to the top-left corner of the `window`.
 When using a stylus or a pointer, the `Touch.clientX` and `Touch.clientY` coordinates in a `touch event` are relative to the same origin.

The top-left corner of the window is always (0, 0), regardless of the content of the document or any scrolling that may have been done. In other words, scrolling the document will change the viewport coordinates of a given position within the document.

### Page

 The "page" coordinate system gives the position of a pixel relative to the top-left corner of the entire rendered `Document`.
 That means that a point in an element within the document will have the same coordinates after the user scrolls horizontally or vertically in the document unless the element moves via layout changes.

 Mouse events' `pageX` and `pageY` properties provide the position of the mouse at the time the event was generated, given relative to the top-left corner of the document.
 `Touch.pageX` and `Touch.pageY` coordinates in a `touch event` are relative to the same origin.

### Screen

 Finally, we come to the "screen" model where the origin is the top-left corner of the user's screen space.
 Each point in this coordinate system represents a single logical pixel, and so values increment and decrement by integer values along each axis.
 The position of a given point within a document will change if the containing window is moved, for example, or if the user's screen geometry changes (by changing display resolution or by adding or removing monitors to their system).

 The `MouseEvent.screenX` and `MouseEvent.screenY` properties give the coordinates of a mouse event's position relative to the screen's origin.
 `Touch.screenX` and `Touch.screenY` coordinates in a `touch event` are relative to the same origin.

Example
-------

 Let's take a look at an example that logs mouse coordinates in an element.
 Whenever the mouse enters, moves around inside, or exits the inner box, the events are handled by logging the current mouse coordinates in each of the four available systems.

### JavaScript

 For the JavaScript, the code sets up the event handlers on the inner box by calling `addEventListener()` for each of the types `mouseenter`, `mousemove`, and `mouseleave`.
 For each of the events, we're calling the `setCoords()` function which sets the inner text of the `<p>` element with the coordinates for each system.

```js
const log = document.querySelector(".log");
const inner = document.querySelector(".inner");

function setCoords(e) {
  log.innerText = `
 Offset X/Y: ${e.offsetX}, ${e.offsetY}
 Viewport X/Y: ${e.clientX}, ${e.clientY}
 Page X/Y: ${e.pageX}, ${e.pageY}
 Screen X/Y: ${e.screenX}, ${e.screenY}`;
}

inner.addEventListener("mousemove", setCoords);
inner.addEventListener("mouseenter", setCoords);
inner.addEventListener("mouseleave", setCoords);
```

### HTML

The HTML contains a `<p>` with the `"log"` class, which displays the data from the mouse events.

```html
<div class="outer">
  <div class="inner">
    <p class="log">Mouse over this section to view coordinates</p>
  </div>
</div>
```

### CSS

 The class `"outer"` for the containing box is intentionally too wide to view the effects of mouse coordinates when the content is scrolled.
 The `"inner"` paragraph is where mouse events are tracked and logged.

```css
.outer {
  width: 1000px;
}

.inner {
  font-family: monospace;
  position: relative;
  width: 500px;
  height: 150px;
  top: 25px;
  left: 100px;
  background-color: darkblue;
  color: white;
  cursor: crosshair;
  user-select: none;
}

.log {
  position: relative;
  width: 100%;
  text-align: center;
}
```

### Result

Here you can see the results in action. As you mouse in and around the blue box, watch the values of the mouse's X and Y coordinates change in the various coordinate systems.

See also
--------

* Using CSS transforms: how to alter a coordinate system
* Coordinates of a `Mouse event`:
    + `MouseEvent.offsetX` and `MouseEvent.offsetY`
    + `MouseEvent.clientX` and `MouseEvent.clientY`
    + `MouseEvent.pageX` and `MouseEvent.pageY`
    + `MouseEvent.screenX` and `MouseEvent.screenY`
* Coordinates of a `Touch event`:
    + `Touch.clientX` and `Touch.clientY`
    + `Touch.pageX` and `Touch.pageY`
    + `Touch.screenX` and `Touch.screenY`


Using multiple backgrounds - CSS: Cascading Style Sheets

Using multiple backgrounds
==========================

You can apply **multiple backgrounds** to elements. These are layered atop one another with the first background you provide on top and the last background listed in the back. Only the last background can include a background color.

Specifying multiple backgrounds is easy:

```css
.myclass {
  background:
    background1,
    background2,
    /\* …, \*/ backgroundN;
}
```

You can do this with both the shorthand `background` property and the individual properties thereof except for `background-color`. That is, the following background properties can be specified as a list, one per background: `background`, `background-attachment`, `background-clip`, `background-image`, `background-origin`, `background-position`, `background-repeat`, `background-size`.

Example
-------

In this example, three backgrounds are stacked: the Firefox logo, an image of bubbles, and a linear gradient:

### HTML

```html
<div class="multi-bg-example"></div>
```

### CSS

```css
.multi-bg-example {
  width: 100%;
  height: 400px;
  background-image: url(firefox.png), url(bubbles.png), linear-gradient(to right, rgb(30
          75 115 / 100%), rgb(255 255 255 / 0%));
  background-repeat: no-repeat, no-repeat, no-repeat;
  background-position:
    bottom right,
    left,
    right;
}
```

### Result

(If image does not appear in CodePen, click the 'Tidy' button in the CSS section)

As you can see here, the Firefox logo (listed first within `background-image`) is on top, directly above the bubbles graphic, followed by the gradient (listed last) sitting underneath all previous 'images'. Each subsequent sub-property (`background-repeat` and `background-position`) applies to the corresponding backgrounds. So the first listed value for `background-repeat` applies to the first (frontmost) background, and so forth.

See also
--------

* Using CSS gradients


Box-shadow generator - CSS: Cascading Style Sheets

Box-shadow generator
====================

This tool lets you construct CSS `box-shadow` effects, to add box shadow effects to your CSS objects.

The box-shadow generator enables you to add one or more box shadows to an element.

On opening the tool, you'll find a rectangle in the top-right section of the tool. That's the element you're going to be applying shadows to. When this element is selected (as it is, when you first load the page) you can apply some basic styling to it:

* Set the element's `color` using the color picker tool.
* Give the element a `border` using the "border" checkbox.
* Use the sliders to set the element's `top`, `left`, `width`, and `height` properties.

To add a box shadow, click the "+" button at the top-left. This adds a shadow, and lists it in the column on the left. Now you can set the values of the new shadow:

* Set the shadow's `color` using the color picker tool.
* Set the shadow to be inset using the "inset" checkbox.
* Use the sliders to set the element's position, blur, and spread.

To add another shadow, click "+" again. Now any values you set will apply to this new shadow. Change the order in which these two shadows are applied using the ↑ and ↓ buttons at the top-left. Select the first shadow again by clicking it in column on the left. To update the element's own styles, select it by clicking the button labelled "element" along the top.

You can add `::before` and `::after` pseudo-elements to the element, and give them box shadows as well. To switch between the element and its pseudo-elements, use the buttons along the top labeled "element", ":before", and ":after".

The box at the bottom-right contains the CSS for the element and any `before::` or `::after` pseudo-elements.

See also
--------

Border-image generator

This interactive tool lets you visually create border images (the `border-image` property).

Border-radius generator

This interactive tool lets you visually create rounded corners (the `border-radius` property).


Border-radius generator - CSS: Cascading Style Sheets

Border-radius generator
=======================

This tool can be used to generate CSS `border-radius` effects.

See also
--------

Border-image generator

This interactive tool lets you visually create border images (the `border-image` property).

Box-shadow generator

This interactive tool lets you visually create shadows behind elements (the `box-shadow` property).


Border-image generator - CSS: Cascading Style Sheets

Border-image generator
======================

This tool can be used to generate CSS `border-image` values.

See also
--------

Border-radius generator

This interactive tool lets you visually create rounded corners (the `border-radius` property).

Box-shadow generator

This interactive tool lets you visually create shadows behind elements (the `box-shadow` property).


Resizing background images with background-size - CSS: Cascading Style Sheets

Resizing background images with background-size
===============================================

The **`background-size`** CSS property lets you resize the background image of an element, overriding the default behavior of tiling the image at its full size by specifying the width and/or height of the image. By doing so, you can scale the image upward or downward as desired.

Tiling a large image
--------------------

Let's consider a large image, a 2982x2808 Firefox logo image. We want (for some reason likely involving horrifyingly bad site design) to tile four copies of this image into a 300x300-pixel element. To do this, we can use a fixed `background-size` value of 150 pixels.

### HTML

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

### CSS

```css
.tiledBackground {
  background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png);
  background-size: 150px;
  width: 300px;
  height: 300px;
  border: 2px solid;
  color: pink;
}
```

### Result

Stretching an image
-------------------

You can also specify both the horizontal and vertical sizes of the image, like this:

```css
background-size: 300px 150px;
```

The result looks like this:

![Firefox logo stretched](/en-US/docs/Web/CSS/CSS_backgrounds_and_borders/Resizing_background_images/stretched_firefox_logo.png)

Scaling an image up
-------------------

On the other end of the spectrum, you can scale an image up in the background. Here we scale a 32x32 pixel favicon to 300x300 pixels:

![MDN Logo scaled](/en-US/docs/Web/CSS/CSS_backgrounds_and_borders/Resizing_background_images/scaled_mdn_logo.png)

```css
.square2 {
  background-image: url(favicon.png);
  background-size: 300px;
  width: 300px;
  height: 300px;
  border: 2px solid;
  text-shadow: white 0px 0px 2px;
  font-size: 16px;
}
```

As you can see, the CSS is actually essentially identical, save the name of the image file.

Special values: `contain` and `cover`
-------------------------------------

In addition to `<length>` values, the `background-size` CSS property offers two special size values, `contain` and `cover`. Let's take a look at these.

### `contain`

The `contain` value specifies that, regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container. Try resizing the example below to see this in action.

#### HTML

```html
<div class="bgSizeContain">
  <p>Try resizing this element!</p>
</div>
```

#### CSS

```css
.bgSizeContain {
  background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png);
  background-size: contain;
  width: 160px;
  height: 160px;
  border: 2px solid;
  resize: both;
  overflow: scroll;
}
```

#### Result

### `cover`

The `cover` value specifies that the background image should be sized so that it is as small as possible while ensuring that both dimensions are greater than or equal to the corresponding size of the container. Try resizing the example below to see this in action.

#### HTML

```html
<div class="bgSizeCover">
  <p>Try resizing this element!</p>
</div>
```

#### CSS

```css
.bgSizeCover {
  background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png);
  background-size: cover;
  width: 160px;
  height: 160px;
  border: 2px solid;
  resize: both;
  overflow: scroll;
}
```

#### Result

See also
--------

* `background-size`
* `background`
* Scaling of SVG backgrounds


Understanding z-index - CSS: Cascading Style Sheets

Understanding z-index
=====================

In the most basic cases, HTML pages can be considered two-dimensional, because text, images, and other elements are arranged on the page without overlapping. In this case, there is a single rendering flow, and all elements are aware of the space taken by others. The `z-index` attribute lets you adjust the order of the layering of objects when rendering content.

>
> *In CSS 2.1, each box has a position in three dimensions. In addition to their horizontal and vertical positions, boxes lie along a "z-axis" and are formatted one on top of the other. Z-axis positions are particularly relevant when boxes overlap visually.*
>
>
>

(from CSS 2.1 Section 9.9.1 - Layered presentation)

This means that CSS style rules allow you to position boxes on layers in addition to the default rendering layer (layer 0). The position on an imaginary z-axis of each layer is expressed as an integer representing the stacking order for rendering. Greater numbers mean closer to the observer. Control the position on this z-axis with the CSS `z-index` property.

Using `z-index` appears extremely easy: a single property assigned a single integer number with an easy-to-understand behavior. When `z-index` is applied to complex hierarchies of HTML elements, its behavior can be hard to understand or predict. This is due to complex stacking rules. In fact, a dedicated section has been reserved in the CSS specification CSS-2.1 Appendix E to explain these rules better.

This guide will try to explain those rules, with some simplification and several examples.

Articles
--------

1. Stacking without the z-index property: The stacking rules that apply when `z-index` is not used.
2. Stacking floating elements: How floating elements are handled with stacking.
3. Using z-index: How to use `z-index` to change default stacking.
4. Stacking context: Notes on the stacking context.
Examples
--------

1. Stacking context example 1: 2-level HTML hierarchy, `z-index` on the last level
2. Stacking context example 2: 2-level HTML hierarchy, `z-index` on all levels
3. Stacking context example 3: 3-level HTML hierarchy, `z-index` on the second level


Stacking context - CSS: Cascading Style Sheets

Stacking context
================

**Stacking context** is a three-dimensional conceptualization of HTML elements along an imaginary z-axis relative to the user, who is assumed to be facing the viewport or the webpage. HTML elements occupy this space in priority order based on element attributes.

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

In the previous article of this guide, Using z-index, we showed that the rendering order of certain elements is influenced by their `z-index` value. This occurs because these elements have special properties which cause them to form a *stacking context*.

A stacking context is formed, anywhere in the document, by any element in the following scenarios:

* Root element of the document (`<html>`).
* Element with a `position` value `absolute` or `relative` and `z-index` value other than `auto`.
* Element with a `position` value `fixed` or `sticky` (sticky for all mobile browsers, but not older desktop browsers).
* Element with a `container-type` value `size` or `inline-size` set, intended for container queries.
* Element that is a child of a flex container, with `z-index` value other than `auto`.
* Element that is a child of a `grid` container, with `z-index` value other than `auto`.
* Element with an `opacity` value less than `1` (See the specification for opacity).
* Element with a `mix-blend-mode` value other than `normal`.
* Element with any of the following properties with value other than `none`:
    + `transform`
    + `filter`
    + `backdrop-filter`
    + `perspective`
    + `clip-path`
    + `mask` / `mask-image` / `mask-border`
* Element with an `isolation` value `isolate`.
* Element with a `will-change` value specifying any property that would create a stacking context on non-initial value (see this post).
* Element with a `contain` value of `layout`, or `paint`, or a composite value that includes either of them (i.e. `contain: strict`, `contain: content`).
* Element placed into the top layer and its corresponding `::backdrop`. Examples include fullscreen and popover elements.

Within a stacking context, child elements are stacked according to the same rules explained just above. Importantly, the `z-index` values of its child stacking contexts only have meaning in this parent. Stacking contexts are treated atomically as a single unit in the parent stacking context.

In summary:

* Stacking contexts can be contained in other stacking contexts, and together create a hierarchy of stacking contexts.
* Each stacking context is completely independent of its siblings: only descendant elements are considered when stacking is processed.
* Each stacking context is self-contained: after the element's contents are stacked, the whole element is considered in the stacking order of the parent stacking context.

**Note:** The hierarchy of stacking contexts is a subset of the hierarchy of HTML elements because only certain elements create stacking contexts. We can say that elements that do not create their own stacking contexts are *assimilated* by the parent stacking context.

Example
-------

![Example of stacking rules modified using z-index](/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index/Stacking_context/understanding_zindex_04.png)

In this example, every positioned element creates its own stacking context, because of their positioning and `z-index` values. The hierarchy of stacking contexts is organized as follows:

* Root
    + DIV #1
    + DIV #2
    + DIV #3
        - DIV #4
        - DIV #5
        - DIV #6

It is important to note that DIV #4, DIV #5 and DIV #6 are children of DIV #3, so stacking of those elements is completely resolved within DIV #3. Once stacking and rendering within DIV #3 is completed, the whole DIV #3 element is passed for stacking in the root element with respect to its sibling's DIV.

DIV #4 is rendered under DIV #1 because DIV #1's z-index (5) is valid within the stacking context of the root element, while DIV #4's z-index (6) is valid within the stacking context of DIV #3. So, DIV #4 is under DIV #1, because DIV #4 belongs to DIV #3, which has a lower z-index value.

For the same reason DIV #2 (`z-index`: 2) is rendered under DIV#5 (`z-index`: 1) because DIV #5 belongs to DIV #3, which has a higher z-index value.

DIV #3's z-index is 4, but this value is independent from z-index of DIV #4, DIV #5 and DIV #6, because it belongs to a different stacking context.

An easy way to figure out the *rendering order* of stacked elements along the z-axis is to think of it as a "version number" of sorts, where child elements are minor version numbers underneath their parent's major version numbers. This way we can easily see how an element with a z-index of 1 (DIV #5) is stacked above an element with a z-index of 2 (DIV #2), and how an element with a z-index of 6 (DIV #4) is stacked below an element with a z-index of 5 (DIV #1).

In our example (sorted according to the final rendering order):

* Root
    + DIV #2: (`z-index`: 2)
    + DIV #3: (`z-index`: 4)
        - DIV #5: (`z-index`: 1), stacked under an element (`z-index`: 4), which results in a rendering order of 4.1
        - DIV #6: (`z-index`: 3), stacked under an element (`z-index`: 4), which results in a rendering order of 4.3
        - DIV #4: (`z-index`: 6), stacked under an element (`z-index`: 4), which results in a rendering order of 4.6
    + DIV #1: (`z-index`: 5)
### HTML

```html
<div id="div1">
  <h1>Division Element #1</h1>
  <code>
    position: relative;<br />
    z-index: 5;
  </code>
</div>

<div id="div2">
  <h1>Division Element #2</h1>
  <code>
    position: relative;<br />
    z-index: 2;
  </code>
</div>

<div id="div3">
  <div id="div4">
    <h1>Division Element #4</h1>
    <code>
      position: relative;<br />
      z-index: 6;
    </code>
  </div>

  <h1>Division Element #3</h1>
  <code>
    position: absolute;<br />
    z-index: 4;
  </code>

  <div id="div5">
    <h1>Division Element #5</h1>
    <code>
      position: relative;<br />
      z-index: 1;
    </code>
  </div>

  <div id="div6">
    <h1>Division Element #6</h1>
    <code>
      position: absolute;<br />
      z-index: 3;
    </code>
  </div>
</div>
```

### CSS

```css
\* {
  margin: 0;
}
html {
  padding: 20px;
  font:
    12px/20px Arial,
    sans-serif;
}
div {
  opacity: 0.7;
  position: relative;
}
h1 {
  font: inherit;
  font-weight: bold;
}
#div1,
#div2 {
  border: 1px dashed #696;
  padding: 10px;
  background-color: #cfc;
}
#div1 {
  z-index: 5;
  margin-bottom: 190px;
}
#div2 {
  z-index: 2;
}
#div3 {
  z-index: 4;
  opacity: 1;
  position: absolute;
  top: 40px;
  left: 180px;
  width: 330px;
  border: 1px dashed #900;
  background-color: #fdd;
  padding: 40px 20px 20px;
}
#div4,
#div5 {
  border: 1px dashed #996;
  background-color: #ffc;
}
#div4 {
  z-index: 6;
  margin-bottom: 15px;
  padding: 25px 10px 5px;
}
#div5 {
  z-index: 1;
  margin-top: 15px;
  padding: 5px 10px;
}
#div6 {
  z-index: 3;
  position: absolute;
  top: 20px;
  left: 180px;
  width: 150px;
  height: 125px;
  border: 1px dashed #009;
  padding-top: 125px;
  background-color: #ddf;
  text-align: center;
}
```

Result
------

See also
--------

* Stacking without the z-index property: The stacking rules that apply when `z-index` is not used.
* Stacking floating elements: How floating elements are handled with stacking.
* Using z-index: How to use `z-index` to change default stacking.
* Stacking context example 1: 2-level HTML hierarchy, `z-index` on the last level
* Stacking context example 2: 2-level HTML hierarchy, `z-index` on all levels
* Stacking context example 3: 3-level HTML hierarchy, `z-index` on the second level
* Top layer


Stacking context example 1 - CSS: Cascading Style Sheets

Stacking context example 1
==========================

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

Let's start with a basic example. In the root stacking context, there are two relatively positioned `<div>` elements (DIV #1 and DIV #3) without `z-index` properties. Inside DIV #1, there is an absolutely positioned DIV #2, while in DIV #3, there is an absolutely positioned DIV #4, both without `z-index` properties.

The only stacking context is the root context. Without `z-index` values, elements are stacked in order of occurrence.

![Stacking context example 1](/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index/Stacking_context_example_1/understanding_zindex_05a.png)

If DIV #2 is assigned a positive (non-zero and non-auto) z-index value, it is rendered above all the other DIVs.

![Stacking context example 1](/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index/Stacking_context_example_1/understanding_zindex_05b.png)

Then if DIV #4 is also assigned a positive z-index greater than DIV #2's z-index, it is rendered above all the other DIVs including DIV #2.

![Stacking context example 1](/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index/Stacking_context_example_1/understanding_zindex_05c.png)

In this last example you can see that DIV #2 and DIV #4 are not siblings, because they belong to different parents in the HTML elements' hierarchy. Even so, stacking of DIV #4 with respect of DIV #2 can be controlled through `z-index`. It happens that, since DIV #1 and DIV #3 are not assigned any z-index value, they do not create a stacking context. This means that all their content, including DIV #2 and DIV #4, belongs to the same root stacking context.

In terms of stacking contexts, DIV #1 and DIV #3 are assimilated into the root element, and the resulting hierarchy is the following:

* Root stacking context
    + DIV #2 (`z-index`: 1)
    + DIV #4 (`z-index`: 2)

**Note:** DIV #1 and DIV #3 are not translucent. It is important to remember that assigning an opacity less than 1 to a positioned element implicitly creates a stacking context, just like adding a `z-index` value. And this example shows what happens when a parent element does not create a stacking context.

Example
-------

### HTML

```html
<div id="div1">
  <br /><span class="bold">DIV #1</span> <br />position: relative;
  <div id="div2">
    <br /><span class="bold">DIV #2</span> <br />position: absolute;
    <br />z-index: 1;
  </div>
</div>

<br />

<div id="div3">
  <br /><span class="bold">DIV #3</span> <br />position: relative;
  <div id="div4">
    <br /><span class="bold">DIV #4</span> <br />position: absolute;
    <br />z-index: 2;
  </div>
</div>
```

### CSS

```css
.bold {
  font-family: Arial;
  font-size: 12px;
  font-weight: bold;
}

#div1,
#div3 {
  height: 80px;
  position: relative;
  border: 1px dashed #669966;
  background-color: #ccffcc;
  padding-left: 5px;
}

#div2 {
  opacity: 0.8;
  z-index: 1;
  position: absolute;
  width: 150px;
  height: 200px;
  top: 20px;
  left: 170px;
  border: 1px dashed #990000;
  background-color: #ffdddd;
  text-align: center;
}

#div4 {
  opacity: 0.8;
  z-index: 2;
  position: absolute;
  width: 200px;
  height: 80px;
  top: 65px;
  left: 50px;
  border: 1px dashed #000099;
  background-color: #ddddff;
  text-align: left;
  padding-left: 10px;
}
```

Result
------

See also
--------

* Stacking without the z-index property: The stacking rules that apply when `z-index` is not used.
* Stacking floating elements: How floating elements are handled with stacking.
* Using z-index: How to use `z-index` to change default stacking.
* Stacking context: Notes on the stacking context.
* Stacking context example 2: 2-level HTML hierarchy, `z-index` on all levels
* Stacking context example 3: 3-level HTML hierarchy, `z-index` on the second level


Stacking floating elements - CSS: Cascading Style Sheets

Stacking floating elements
==========================

For floating elements, the stacking order is a bit different. Floating elements are placed between non-positioned elements and positioned elements:

1. The background and borders of the root element.
2. Descendant non-positioned elements, in order of appearance in the HTML.
3. *Floating elements*.
4. Descendant positioned elements, in order of appearance in the HTML.

See types of positioning for an explanation of positioned and non-positioned elements.

**Note:** If an `opacity` value is applied to a non-positioned element (i.e., DIV #4 in the example below), something strange happens: the background and border of that block pop up above the floating blocks and the positioned blocks. This is due to a peculiar part of the specification: applying an `opacity` value creates a new stacking context (see What No One Told You About Z-Index).

Example
-------

You can see in this example that the background and border of the non-positioned element (DIV #4) is completely unaffected by floating elements, but the content is affected. This happens according to standard float behavior which can be shown with a rule added to the above list:

1. The background and borders of the root element.
2. Descendant non-positioned elements, in order of appearance in the HTML.
3. Floating elements.
4. *Descendant non-positioned inline elements*.
5. Descendant positioned elements, in order of appearance in the HTML.
### HTML

```html
<div id="abs1"><strong>DIV #1</strong><br />position: absolute;</div>

<div id="flo1"><strong>DIV #2</strong><br />float: left;</div>

<div id="flo2"><strong>DIV #3</strong><br />float: right;</div>

<br />

<div id="sta1"><strong>DIV #4</strong><br />no positioning</div>

<div id="abs2"><strong>DIV #5</strong><br />position: absolute;</div>

<div id="rel1"><strong>DIV #6</strong><br />position: relative;</div>
```

### CSS

```css
div {
  padding: 10px;
  text-align: center;
}

strong {
  font-family: sans-serif;
}

#abs1 {
  position: absolute;
  width: 150px;
  height: 200px;
  top: 10px;
  right: 140px;
  border: 1px dashed #900;
  background-color: #fdd;
}

#sta1 {
  height: 100px;
  border: 1px dashed #996;
  background-color: #ffc;
  margin: 0px 10px 0px 10px;
  text-align: left;
}

#flo1 {
  margin: 0px 10px 0px 20px;
  float: left;
  width: 150px;
  height: 200px;
  border: 1px dashed #090;
  background-color: #cfc;
}

#flo2 {
  margin: 0px 20px 0px 10px;
  float: right;
  width: 150px;
  height: 200px;
  border: 1px dashed #090;
  background-color: #cfc;
}

#abs2 {
  position: absolute;
  width: 150px;
  height: 100px;
  top: 80px;
  left: 100px;
  border: 1px dashed #990;
  background-color: #fdd;
}

#rel1 {
  position: relative;
  border: 1px dashed #996;
  background-color: #cff;
  margin: 0px 10px 0px 10px;
  text-align: left;
}
```

Result
------

See also
--------

* Stacking without the z-index property: The stacking rules that apply when `z-index` is not used.
* Using z-index: How to use `z-index` to change default stacking.
* Stacking context: Notes on the stacking context.
* Stacking context example 1: 2-level HTML hierarchy, z-index on the last level
* Stacking context example 2: 2-level HTML hierarchy, z-index on all levels
* Stacking context example 3: 3-level HTML hierarchy, z-index on the second level


Using z-index - CSS: Cascading Style Sheets

Using z-index
=============

The first article of this guide, Stacking without the z-index property, explains how stacking is arranged by default. If you want to create a custom stacking order, you can use the `z-index` property on a positioned element.

The `z-index` property can be specified with an integer value (positive, zero, or negative), which represents the position of the element along an imaginary z-axis. If you are not familiar with the term 'z-axis', imagine the page as a stack of layers, each one having a number. Layers are rendered in numerical order, with larger numbers above smaller numbers (*X* represents an arbitrary positive integer):

| Layer | Description |
| --- | --- |
| Bottom layer | Farthest from the observer |
| Layer -X | Layers with negative `z-index` values |
| Layer 0 | Default rendering layer |
| Layer X | Layers with positive `z-index` values |
| Top layer | Closest to the observer |

**Note:**

* When no `z-index` property is specified, elements are rendered on the default rendering layer (Layer 0).
* If several elements share the same `z-index` value (i.e., they are placed on the same layer), stacking rules explained in the section Stacking without the z-index property apply.

Example
-------

In this example, the layers' stacking order is rearranged using `z-index`. The `z-index` of DIV #5 has no effect since it is not a positioned element.

### HTML

```html
<div id="abs1">
  <strong>DIV #1</strong>
  <br />position: absolute; <br />z-index: 5;
</div>

<div id="rel1">
  <strong>DIV #2</strong>
  <br />position: relative; <br />z-index: 3;
</div>

<div id="rel2">
  <strong>DIV #3</strong>
  <br />position: relative; <br />z-index: 2;
</div>

<div id="abs2">
  <strong>DIV #4</strong>
  <br />position: absolute; <br />z-index: 1;
</div>

<div id="sta1">
  <strong>DIV #5</strong>
  <br />no positioning <br />z-index: 8;
</div>
```

### CSS

```css
div {
  padding: 10px;
  opacity: 0.7;
  text-align: center;
}

strong {
  font-family: sans-serif;
}

#abs1 {
  z-index: 5;
  position: absolute;
  width: 150px;
  height: 350px;
  top: 10px;
  left: 10px;
  border: 1px dashed #900;
  background-color: #fdd;
}

#rel1 {
  z-index: 3;
  height: 100px;
  position: relative;
  top: 30px;
  border: 1px dashed #696;
  background-color: #cfc;
  margin: 0px 50px 0px 50px;
}

#rel2 {
  z-index: 2;
  height: 100px;
  position: relative;
  top: 15px;
  left: 20px;
  border: 1px dashed #696;
  background-color: #cfc;
  margin: 0px 50px 0px 50px;
}

#abs2 {
  z-index: 1;
  position: absolute;
  width: 150px;
  height: 350px;
  top: 10px;
  right: 10px;
  border: 1px dashed #900;
  background-color: #fdd;
}

#sta1 {
  z-index: 8;
  height: 70px;
  border: 1px dashed #996;
  background-color: #ffc;
  margin: 0px 50px 0px 50px;
}
```

Result
------

See also
--------

* Stacking without the z-index property: The stacking rules that apply when `z-index` is not used.
* Stacking floating elements: How floating elements are handled with stacking.
* Stacking context: Notes on the stacking context.
* Stacking context example 1: 2-level HTML hierarchy, z-index on the last level
* Stacking context example 2: 2-level HTML hierarchy, z-index on all levels
* Stacking context example 3: 3-level HTML hierarchy, z-index on the second level


Stacking context example 3 - CSS: Cascading Style Sheets

Stacking context example 3
==========================

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

This last example shows problems that arise when mixing several positioned elements in a multi-level HTML hierarchy and when `z-index` values are assigned using class selectors.

Let's take as an example a three-level hierarchical menu made from several positioned `div` elements. Second-level and third-level `div` elements appear when a user hovers or clicks on their parents. Usually this kind of menu is script-generated either client-side or server-side, so style rules are assigned with a class selector instead of the id selector.

If the three menu levels partially overlap, then managing stacking could become a problem.

The first-level menu is only relatively positioned, so no stacking context is created.

The second-level menu is absolutely positioned inside the parent element. In order to put it above all first-level menus, the `z-index` property is used. The problem is that for each second-level menu, a stacking context is created and each third-level menu belongs to the context of its parent.

So a third-level menu will be stacked under the following second-level menus, because all second-level menus share the same z-index value and the default stacking rules apply.

To better understand the situation, here is the stacking context hierarchy (the three dots "..." represent multiple repetition of the previous line):

* Root stacking context
    + LEVEL #1
        - LEVEL #2 (`z-index`: 1)
            * LEVEL #3
            * …
            * LEVEL #3
        - LEVEL #2 (`z-index`: 1)
        - …
        - LEVEL #2 (`z-index`: 1)
    + LEVEL #1
    + …
    + LEVEL #1

This problem can be avoided by removing overlapping between different level menus, or by using individual (and different) z-index values assigned through the id selector instead of class selector, or by flattening the HTML hierarchy.

**Note:** In the source code you will see that second-level and third level menus are made of several `div` elements contained in an absolutely positioned container. This is useful to group and position all of them at once.

Example
-------

### HTML

```html
<div class="lev1">
  <span class="bold">LEVEL #1</span>

  <div id="container1">
    <div class="lev2">
      <br /><span class="bold">LEVEL #2</span> <br />z-index: 1;

      <div id="container2">
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
        <div class="lev3"><span class="bold">LEVEL #3</span></div>
      </div>
    </div>

    <div class="lev2">
      <br /><span class="bold">LEVEL #2</span> <br />z-index: 1;
    </div>
    <div class="lev2">
      <br /><span class="bold">LEVEL #2</span> <br />z-index: 1;
    </div>
    <div class="lev2">
      <br /><span class="bold">LEVEL #2</span> <br />z-index: 1;
    </div>
  </div>
</div>

<div class="lev1">
  <span class="bold">LEVEL #1</span>
</div>

<div class="lev1">
  <span class="bold">LEVEL #1</span>
</div>

<div class="lev1">
  <span class="bold">LEVEL #1</span>
</div>
```

### CSS

```css
div {
  font: 12px Arial;
}

span.bold {
  font-weight: bold;
}

div.lev1 {
  width: 250px;
  height: 70px;
  position: relative;
  border: 2px outset #669966;
  background-color: #ccffcc;
  padding-left: 5px;
}

#container1 {
  z-index: 1;
  position: absolute;
  top: 30px;
  left: 75px;
}

div.lev2 {
  opacity: 0.9;
  width: 200px;
  height: 60px;
  position: relative;
  border: 2px outset #990000;
  background-color: #ffdddd;
  padding-left: 5px;
}

#container2 {
  z-index: 1;
  position: absolute;
  top: 20px;
  left: 110px;
}

div.lev3 {
  z-index: 10;
  width: 100px;
  position: relative;
  border: 2px outset #000099;
  background-color: #ddddff;
  padding-left: 5px;
}
```

Result
------

See also
--------

* Stacking without the z-index property: The stacking rules that apply when `z-index` is not used.
* Stacking floating elements: How floating elements are handled with stacking.
* Using z-index: How to use `z-index` to change default stacking.
* Stacking context: Notes on the stacking context.
* Stacking context example 1: 2-level HTML hierarchy, `z-index` on the last level
* Stacking context example 2: 2-level HTML hierarchy, `z-index` on all levels

**Note:** The sample image looks wrong - with the second level 2 overlapping the level 3 menus - because level 2 has opacity, which creates a new stacking context.
 Basically, this whole sample page is incorrect and misleading.


Stacking context example 2 - CSS: Cascading Style Sheets

Stacking context example 2
==========================

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

This is a very simple example, but it is the key for understanding the concept of *stacking context*. There are the same four DIVs of the previous example, but now `z-index` properties are assigned on both levels of the hierarchy.

You can see that DIV #2 (`z-index`: 2) is above DIV #3 (`z-index`: 1), because they both belong to the same stacking context (the root one), so z-index values rule how elements are stacked.

What can be considered strange is that DIV #2 (`z-index`: 2) is above DIV #4 (`z-index`: 10), despite their z-index values. The reason is that they do not belong to the same stacking context. DIV #4 belongs to the stacking context created by DIV #3, and as explained previously DIV #3 (and all its content) is under DIV #2.

To better understand the situation, this is the stacking context hierarchy:

* Root stacking context
    + DIV #2 (`z-index`: 2)
    + DIV #3 (`z-index`: 1)
        - DIV #4 (`z-index`: 10)

**Note:** It is worth remembering that the HTML hierarchy is different from the stacking context hierarchy. In the stacking context hierarchy, elements that do not create a stacking context are collapsed on their parent.

Example
-------

### HTML

```html
<div id="div1">
  <br />
  <span class="bold">DIV #1</span><br />
  position: relative;
  <div id="div2">
    <br />
    <span class="bold">DIV #2</span><br />
    position: absolute;<br />
    z-index: 2;
  </div>
</div>

<br />

<div id="div3">
  <br />
  <span class="bold">DIV #3</span><br />
  position: relative;<br />
  z-index: 1;
  <div id="div4">
    <br />
    <span class="bold">DIV #4</span><br />
    position: absolute;<br />
    z-index: 10;
  </div>
</div>
```

### CSS

```css
div {
  font: 12px Arial;
}

span.bold {
  font-weight: bold;
}

#div2 {
  z-index: 2;
}
#div3 {
  z-index: 1;
}
#div4 {
  z-index: 10;
}

#div1,
#div3 {
  height: 80px;
  position: relative;
  border: 1px dashed #669966;
  background-color: #ccffcc;
  padding-left: 5px;
}

#div2 {
  opacity: 0.8;
  position: absolute;
  width: 150px;
  height: 200px;
  top: 20px;
  left: 170px;
  border: 1px dashed #990000;
  background-color: #ffdddd;
  text-align: center;
}

#div4 {
  opacity: 0.8;
  position: absolute;
  width: 200px;
  height: 70px;
  top: 65px;
  left: 50px;
  border: 1px dashed #000099;
  background-color: #ddddff;
  text-align: left;
  padding-left: 10px;
}
```

Result
------

See also
--------

* Stacking without the z-index property: The stacking rules that apply when `z-index` is not used.
* Stacking floating elements: How floating elements are handled with stacking.
* Using z-index: How to use `z-index` to change default stacking.
* Stacking context: Notes on the stacking context.
* Stacking context example 1: 2-level HTML hierarchy, `z-index` on the last level
* Stacking context example 3: 3-level HTML hierarchy, `z-index` on the second level


Stacking without the z-index property - CSS: Cascading Style Sheets

Stacking without the z-index property
=====================================

When the `z-index` property is not specified on any element, elements are stacked in the following order (from bottom to top):

1. The background and borders of the root element.
2. Descendant non-positioned elements, in order of appearance in the HTML.
3. Descendant positioned elements, in order of appearance in the HTML.

See types of positioning for an explanation of positioned and non-positioned elements.

Keep in mind, when the `order` property alters rendering from the *order of appearance in the HTML* within `flex` containers, it similarly affects the order for stacking context.

Example
-------

In this example, DIV #1 through DIV #4 are positioned elements. DIV #5 is static, and so is drawn below the other four elements, even though it comes later in the HTML markup.

### HTML

```html
<div id="abs1" class="absolute">
  <strong>DIV #1</strong><br />position: absolute;
</div>
<div id="rel1" class="relative">
  <strong>DIV #2</strong><br />position: relative;
</div>
<div id="rel2" class="relative">
  <strong>DIV #3</strong><br />position: relative;
</div>
<div id="abs2" class="absolute">
  <strong>DIV #4</strong><br />position: absolute;
</div>
<div id="sta1" class="static">
  <strong>DIV #5</strong><br />position: static;
</div>
```

### CSS

```css
strong {
  font-family: sans-serif;
}

div {
  padding: 10px;
  border: 1px dashed;
  text-align: center;
}

.static {
  position: static;
  height: 80px;
  background-color: #ffc;
  border-color: #996;
}

.absolute {
  position: absolute;
  width: 150px;
  height: 350px;
  background-color: #fdd;
  border-color: #900;
  opacity: 0.7;
}

.relative {
  position: relative;
  height: 80px;
  background-color: #cfc;
  border-color: #696;
  opacity: 0.7;
}

#abs1 {
  top: 10px;
  left: 10px;
}

#rel1 {
  top: 30px;
  margin: 0px 50px 0px 50px;
}

#rel2 {
  top: 15px;
  left: 20px;
  margin: 0px 50px 0px 50px;
}

#abs2 {
  top: 10px;
  right: 10px;
}

#sta1 {
  background-color: #ffc;
  margin: 0px 50px 0px 50px;
}
```

Result
------

See also
--------

* Stacking floating elements: How floating elements are handled with stacking.
* Using z-index: How to use `z-index` to change default stacking.
* Stacking context: Notes on the stacking context.
* Stacking context example 1: 2-level HTML hierarchy, z-index on the last level
* Stacking context example 2: 2-level HTML hierarchy, z-index on all levels
* Stacking context example 3: 3-level HTML hierarchy, z-index on the second level


Shapes from images - CSS: Cascading Style Sheets

Shapes from images
==================

In this guide, we will take a look at how we can create a shape from an image file with an alpha channel or even from a CSS Gradient. This is a very flexible way to create shapes. Rather than drawing a path with a complex polygon in CSS, you can create the shape in a graphics program and then use the path created by the pixels less opaque than a threshold value.

Creating shapes from images
---------------------------

To use an image for creating a shape, the image needs to have an Alpha Channel, an area that is not fully opaque. The `shape-image-threshold` property is used to set a threshold for this opacity. Pixels that are more opaque than this value will be used to calculate the area of the shape.

In the example below, there is an image of a star with a solid red area and an area that is fully transparent. The path to the image file is used as the value for the `shape-outside` property. The content now wraps around the star shape.

You can use `shape-margin` to move the text away from the shape, giving a margin around the created shape and the text.

CORS compatibility
------------------

Something that you will run into when creating shapes from an image is that the image you use must be CORS compatible. An image hosted on the same domain as your site should work, however, if your images are hosted on a different domain such as on a CDN you should ensure that they are sending the correct headers to enable them to be used for Shapes. Due to this requirement for CORS-compatible images, if you are previewing your file locally without using a local web server, your shape will not work.

### Is it a CORS issue?

DevTools can help you to identify CORS errors. In Chrome the Console will alert you to CORS problems. In Firefox if you inspect the property you will be alerted to the fact that the image could not be loaded. This should alert you to the fact that your image cannot be used as the source of a shape due to CORS.

Setting a threshold
-------------------

The `shape-image-threshold` property enables the creation of shapes from areas which are not fully transparent. If the value of `shape-image-threshold` is `0.0` (which is the initial value) then the area must be fully transparent. If the value is `1.0` then it is fully opaque. Values in between mean that you can set a semi-transparent area as the defining area.

In the example below I am using a similar image to the initial example, however, in this image the background of the star is not fully transparent, it has a 20% opacity as created in my graphics program. If I set `shape-image-threshold` to `0.3` then I see the shape, if I set it to something smaller than `0.2` I do not get the shape.

Using images with generated content
-----------------------------------

In the above example, I have both used the image as the value of `shape-outside` and also added it to the page. Many demos do this as it helps to show the shape we are following, however, the `shape-outside` property is not related to the image that is displayed on the page and so you do not need to display an image to use an image to create a shape.

You do need something to float, but that could be some generated content as in the below example. I am floating generated content and using a larger star image to shape my content without displaying any image on the page.

Creating shapes using a gradient
--------------------------------

Because a CSS gradient is treated as an image, you can use a gradient to generate a shape by having transparent or semi-transparent areas as part of the gradient.

The next example uses generated content. The content has been floated, giving it a background image of a linear gradient. I am using that same value as the value of `shape-outside`. The linear gradient goes from purple to transparent. By changing the value of `shape-image-threshold`, you can decide how transparent the pixels need to be that create the shape. You can play with that value in the example below to see how the diagonal line will move across the shape depending on that value.

You could also try removing the background image completely, thus using the gradient purely to create the shape and not displaying it on the page at all.

The next example uses a radial gradient with an ellipse, once again using a transparent part of the gradient to create the shape.

You can experiment directly in these live examples to see how changing the gradient will change the path of your shape.


Basic shapes - CSS: Cascading Style Sheets

Basic shapes
============

CSS Shapes can be defined using the `<basic-shape>` type, and in this guide I'll explain how each of the different values accepted by this type work. They range from simple circles to complex polygons.

Before looking at shapes, it is worth understanding two pieces of information that go together to make these shapes possible:

* The `<basic-shape>` type
* The reference box
The <basic-shape> type
----------------------

The `<basic-shape>` type is used as the value for all of our basic shapes. This type uses Functional Notation: the type of shape is followed by parenthese, inside of which are additional values used to describe the shape.

The arguments which are accepted vary depending on the shape that you are creating. We will cover these in the examples below.

The reference box
-----------------

Understanding the reference box used by CSS Shapes is important when using basic shapes, as it defines each shape's coordinate system. You have already met the reference box in the guide on creating shapes from Box Values, which directly uses the reference box to create the shape.

The Firefox Shapes Inspector helpfully shows the reference box in use when you inspect a shape. In the screenshot below I have created a circle, using `shape-outside: circle(50%)`. The floated element has 20 pixels of padding, border and margin applied, and the Shapes Inspector highlights these reference boxes. When using a basic shape, the reference box used by default is the margin-box. You can see in the screenshot that the shape is being defined with reference to that part of the Box Model.

![An imaged clipped into a circle floated left, with a paragraph of text. The left edge of the text is circular abutting the clipped shape on the outside of the margin with the margin following the shape clipping.](/en-US/docs/Web/CSS/CSS_shapes/Basic_shapes/shapes-reference-box.png)

You can add the various box values after your basic shape definition. Therefore the default behavior is as if you have defined.

```css
.shape {
  shape-outside: circle(50%) margin-box;
}
```

You can therefore change this in order that your shape uses the different parts of the box model, for example to use the border.

```css
.shape {
  shape-outside: circle(50%) border-box;
}
```

What is worth noting is that the `margin-box` will clip the shape, therefore shapes created in reference to other shapes which extend past the margin box will have the shape clipped to the margin box. We will see this in the following examples of basic shapes.

For an excellent description of references boxes as they apply to CSS Shapes, see Understanding Reference Boxes for CSS Shapes.

inset()
-------

The `inset()` type defines a rectangle, which may not seem very useful as floating an item will give you a rectangular shape around it. However the `inset()` types enables the definition of offsets, thus pulling the content in over the shape.

Therefore `inset()` takes four values for the top, right, bottom and left values plus a final value for `border-radius`. The below CSS creates a rectangular shape inset from the reference box of the floated element 20 pixels from the top and bottom and 10 pixels from the left and right, with a border-radius value of 10 pixels.

```css
.shape {
  float: left;
  shape-outside: inset(20px 10px 20px 10px round 10px);
}
```

Using the same rules as we use for the margin shorthand, you can set more than one offset at once. If there is only one value, it applies to all sides. If there are two values, the top and bottom offsets are set to the first value and the right and left offsets are set to the second. If there are three values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third. If there are four values, they apply to the top, right, bottom, and left, respectively. So, the above rules could also be described as:

```css
.shape {
  float: left;
  shape-outside: inset(20px 10px round 10px);
}
```

In the example below we have an `inset()` shape used to pull content over the floated element. Change the offset values to see how the shape changes.

You can also add the Box Value that you wish to use as a reference box. In the example below change the reference box from `margin-box` to `border-box`, `padding-box` or `content-box` to see how the reference box used as the starting point before offsets are calculated changes.

circle()
--------

The `circle()` value for `shape-outside` can accept two possible arguments. The first is the `shape-radius`.

Both `circle()` and `ellipse()` values for `shape-outside` are specified as accepting this argument of `<shape-radius>`. This argument can be a length or percentage but can also be one of the keywords `closest-side` or `farthest-side`.

The keyword **`closest-side`** uses the length from the center of the shape to the closest side of the reference box. For circles, this is the closest side in any dimension. For ellipses, this is the closest side in the radius dimension.

The keyword **`farthest-side`** uses the length from the center of the shape to the farthest side of the reference box. For circles, this is the farthest side in any dimension. For ellipses, this is the farthest side in the radius dimension.

The second argument is a `position`. If omitted this will be set to `center`. However you can use any valid position here to indicate the position of the center of the circle.

Our circle therefore accepts one radius value, which may be a length, a percentage or the closest-side or farthest side keyword then optionally the keyword **at** followed by a position value.

In the below example I have created a circle on an item with a width of 100 pixels, plus a margin of 20 pixels. This gives a total width for the reference box of 140 pixels. I have given a value of 50% for the shape-radius value which means that our radius is 70px. I have then set the position value to 30%.

In the live example you can play with increasing or decreasing the size of the circle by changing the size of the radius, moving the circle around with the position value, or setting a reference box as we did for `inset()`.

As an additional example, if you use the keywords `top left` for position, you can make a quarter circle shape in the top left corner of the page. The example below uses generated content to create a quarter circle shape for text to flow around.

### The shape will be clipped by the margin box

When describing Reference Boxes I explained that the margin-box will clip the shape. You can see this by moving the center of our circle towards the content by setting the position to 60%. The center of the circle is now nearer the content and the circle extends past the margin-box. This means that the extension becomes clipped and squared off.

```css
img {
  float: left;
  shape-outside: circle(50% at 60%);
}
```

![The circle shape is clipped by the margin box](/en-US/docs/Web/CSS/CSS_shapes/Basic_shapes/shapes-circle-clipped.png)

ellipse()
---------

An ellipse is essentially a squashed circle and so `ellipse()` acts in a very similar way to `circle()` except that we have to specify two radii x and y in that order.

These may then be followed by position values as with `circle()` to move the center of the ellipse around. In the example below we have an ellipse with an x radius of 40%, a y radius of 50% and the position being left. This means that the center of the ellipse is on the left edge of the box giving us a half ellipse shape to wrap our text around. You can change these values to see how the ellipse changes.

The keyword values of `closest-side` and `farthest-side` are useful to create a quick ellipse based on the size of the floated element reference box.

polygon()
---------

The final Basic Shape is the most complex and enables the creation of many side shapes by way of creating a `polygon()`. This shape accepts three or more pairs of values (a polygon must at least draw a triangle). These values are co-ordinates drawn with reference to the reference box.

In the example below I have created a shape for text to follow using the `polygon()`, you can change any of the values to see how the shape is changed.

You may well find the Firefox Shape Inspector very useful here to create your polygon shape. The screenshot below shows the shape highlighted in the tool.

![The polygon basic shape, highlighted with the Shapes Inspector.](/en-US/docs/Web/CSS/CSS_shapes/Basic_shapes/shapes-polygon.png)

Another useful resource is Clippy - a tool for creating shapes for `clip-path`, as the values for Basic Shapes are the same as those used for `clip-path`.


Overview of shapes - CSS: Cascading Style Sheets

Overview of shapes
==================

The CSS Shapes Level 1 Specification describes geometric shapes in CSS. They are, in Level 1 of the specification, designed to be applied to floated items. This article provides an overview of what you can do with shapes.

You could for example float an item left, which would cause the text to wrap round the right and bottom of the item in a rectangular fashion. If you then apply a circle shape, the text would then wrap round the line of the circle.

There are a number of ways to create these Shapes and in these guides we will find out how CSS Shapes work, and consider some ways you might like to use them.

What does the specification define?
-----------------------------------

The specification defines three new properties:

* `shape-outside` — allows definition of basic shapes
* `shape-image-threshold` — Sets an opacity threshold value. If an image is being used to define the shape, only the parts of the image that are the same opacity or greater than the threshold value are used in the shape. Any other parts are ignored.
* `shape-margin` — sets a margin around the defined shape
Defining basic shapes
---------------------

The `shape-outside` property allows us to a define a shape. It takes a variety of values, all of which define different shapes, specified in the `<basic-shape>` datatype. We can start by looking at a very simple case.

In the following example I have an image floated left. I have then applied the `shape-outside` property to it with a value of `circle(50%)`. The result is that the content now curves around the circular shape rather than following the rectangle created by the box of the image.

As in this level of the specification an element has to be floated in order to apply `<basic-shape>` to it; this has the side-effect of creating a simple fallback for many cases. If you do not have Shapes support in the browser, the user will see content flowing around the sides of a rectangular box as before. If they do have Shapes support then the visual display is enhanced.

### Basic shapes

The value `circle(50%)` is an example of a basic shape. The specification defines four `<basic-shape>` values, which are:

* `inset()`
* `circle()`
* `ellipse()`
* `polygon()`

Using the value `inset()` wraps text around a rectangular shape however you are able to add offset values, thus pulling the line boxes of any wrapping content closer to the object than would otherwise happen.

We have already seen how `circle()` creates a circular shape. An `ellipse()` is essentially a squashed circle. If none of these simple shapes do the trick you can create a `polygon()` and make the shape as complex as you want.

In our Guide to Basic Shapes we explore each of the possible Basic Shapes and how to create them.

### Shapes from the box value

Shapes can also be created around the box value. Therefore, you could create your shape on:

* `border-box`
* `padding-box`
* `content-box`
* `margin-box`

In the example below, you can change the value `border-box` to any of the other allowed values to see how the shape moves closer or further away from the box.

To explore the box values in more detail, see our guide covering Shapes from box values.

### Shapes from images

An interesting way to generate your path is to use an image with an alpha channel — the text will then wrap around the non-transparent parts of the image. This allows the overlay of wrapped content around an image, or the use of an image which is never displayed on the page purely as a method of creating a complex shape without needing to carefully map a polygon.

Note that images used in this way must be CORS compatible, otherwise `shape-outside` will act as if `none` had been given as the value, and you will get no shape.

In this next example, we have an image with a fully transparent area, and we are using an image as the URL value for `shape-outside`. The shape is created around the opaque area — the image of the balloon.

#### `shape-image-threshold`

The `shape-image-threshold` property is used to set the threshold of image transparency used to define the area of the image used for the shape. If the value of `shape-image-threshold` is `0.0` (which is the initial value) then the area must be fully transparent. If the value is `1.0` then it is fully opaque. Values in between mean that you can set a semi-transparent area as the defining area of the shape.

You can see the threshold in action if we use a gradient as the image on which to define our shape. In the example below, if you change the threshold the path that the shape takes changes based on the level of opacity you have selected.

We take a deeper look at creating shapes from images in the Shapes from Images guide.

The `shape-margin` property
---------------------------

The `shape-margin` property adds a margin to `shape-outside`. This will further shorten the line boxes of any content wrapping the shape, pushing it away from the shape itself.

In the example below we have added a `shape-margin` to a basic shape. Change the margin to push the text further away from the path the shape would take by default.

Using Generated Content as the floated item
-------------------------------------------

In the examples above, we have used images or a visible element to define the shape, meaning that you can see the shape on the page. Instead, you might want to cause some text to flow along a non-rectangular invisible line. You can do this with Shapes, however you will still need a floated item, which you can then make invisible. That could be a redundant element inserted into the document, an empty `<div>` or `<span>` perhaps, but our preference is to use generated content. This means we can keep things used for styling inside the CSS.

In this next example, we use generated content to insert an element with height and width of 150px. We can then use Basic Shapes, Box Values or even the Alpha Channel of an image to create a shape for the text to wrap around.

Relationship to `clip-path`
---------------------------

The Basic Shapes and Box values used to create Shapes are the same as those used as values for `clip-path`. Therefore if you want to create a shape using an image, and also clip away part of that image, you can use the same values.

The image below is a square image with a blue background. We have defined a shape using `shape-outside: ellipse(40% 50%);` and also used `clip-path: ellipse(40% 50%);` to clip away the same area that we have used to define the shape.

Developer Tools for Shapes
--------------------------

Along with CSS Shapes support in the browser, Firefox are shipping a Shape Path Editor in the Firefox DevTools. This tool means that you can inspect any shapes on your page, and even change the values in the live page. If your polygon isn't quite right you can use the Shapes Editor to tweak it, then copy the new value back into your CSS.

The Shape Path Editor will be enabled by default in Firefox 60 for shapes generated via `clip-path`. You can also use it to edit shapes generated via `shape-outside`, but only when you enable it via the `layout.css.shape-outside.enabled` pref.

Future CSS Shapes Features
--------------------------

The initial Shapes specification included a property `shape-inside` for creating shapes inside an element. This property, along with the possibility of creating shapes on non-floated elements, has been moved to level 2 of the specification. As the `shape-inside` property was initially in Level 1 of the specification, you may find tutorials on the web detailing both properties.


Shapes from box values - CSS: Cascading Style Sheets

Shapes from box values
======================

A straightforward way to create a shape is to use a value from the CSS Box Model. This article explains how to do this.

The box values allowable as a shape value are:

* `content-box`
* `padding-box`
* `border-box`
* `margin-box`

The `border-radius` values are also supported, this means that you can have something in your page with a curved border, and your shape can follow the created shape.

CSS box model
-------------

The values listed above correspond to the various parts of the CSS Box Model. A box in CSS has content, padding, border, and margin.

![The Box Model consists of the margin, border, padding and content boxes.](/en-US/docs/Web/CSS/CSS_shapes/From_box_values/box-model.png)

By using Box Values for Shapes we can wrap our content around the edges defined by these values. In all of the examples below I am using an element which has padding, a border, and a margin defined in order that you can see the different ways in which content will flow.

### margin-box

The `margin-box` is the shape defined by the outside margin edge and includes the corner radius of the shape, should `border-radius` have been used in defining the element.

In the example below, we have a circular purple item which is a `<div>` with a height, width, and background color. The `border-radius` property has been used to create a circle by setting `border-radius: 50%`. As the element has a margin, you can see that the content is flowing around the circular shape and the margin applied to it.

### border-box

The `border-box` value is the shape defined by the outside border edge. This shape follows all of the normal border radius shaping rules for the outside of the border. You still have a border, even if you have not used the CSS `border` property. In this case it will be the same as `padding-box`, the shape defined by the outside padding edge.

In the example below you can see how the text now follows the line created by the border. Change the border size and the content follows it.

### padding-box

The `padding-box` value defines the shape enclosed by the outside padding edge. This shape follows all of the normal border radius shaping rules for the inside of the border. If you have no padding then `padding-box` is the same as `content-box`.

### content-box

The `content-box` value defines the shape enclosed by the outside content edge. Each corner radius of this box is the larger of 0 or border-radius − border-width − padding. This Means that it is impossible to have a negative value here.

When to use box values
----------------------

Using box values is a simple way to create shapes; however, this is by nature only going to work with very simple shapes that can be defined using the well-supported `border-radius` property. The examples shown above show one such use case. You can create a circular shape using border-radius and then curve text around it.

You can create some interesting effects however with just this simple technique. In my final example of this section, I have floated two elements left and right, giving each a border-radius of 100% in the direction closest to the text.

For more complex shapes, you will need to use one of the basic shapes as a value, or define your shape from an image as covered in other guides in this section.


font-family - CSS: Cascading Style Sheets

font-family
===========

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.

* Learn more
* See full compatibility
* Report feedback
The **`font-family`** CSS descriptor sets the font family for a font specified in an `@font-face` at-rule.

 The value is used for name matching against a particular `@font-face` when styling elements using the `font-family` property.
 Any name may be used, and this overrides any name specified in the underlying font data.

Syntax
------

```css
/\* <string> values \*/
font-family: "font family";
font-family: "another font family";

/\* <custom-ident> value \*/
font-family: examplefont;
```

### Values

`<family-name>`

Specifies the name of the font family.

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

|  |  |
| --- | --- |
| Related at-rule | `@font-face` |
| Initial value | `n/a (required)` |
| Computed value | as specified |

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

font-family =
  <family-name>

<family-name> =
  <string>         |
  <custom-ident>+

```

Examples
--------

### Setting the font family name

```css
@font-face {
  font-family: "Some font family";
  src: url("some\_font\_name.ttf");
}
```

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

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

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

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

See also
--------

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


font-stretch - CSS: Cascading Style Sheets

font-stretch
============

The **`font-stretch`** CSS descriptor allows authors to specify a normal, condensed, or expanded face for the fonts specified in the `@font-face` at-rule.

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-stretch` descriptor to explicitly specify the font face's stretch. The values for the CSS descriptor is same as that of its corresponding font property.

Syntax
------

```css
/\* Single values \*/
font-stretch: ultra-condensed;
font-stretch: extra-condensed;
font-stretch: condensed;
font-stretch: semi-condensed;
font-stretch: normal;
font-stretch: semi-expanded;
font-stretch: expanded;
font-stretch: extra-expanded;
font-stretch: ultra-expanded;
font-stretch: 50%;
font-stretch: 100%;
font-stretch: 200%;

/\* multiple values \*/
font-stretch: 75% 125%;
font-stretch: condensed ultra-condensed;
```

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

### Values

`normal`

Specifies a normal font face.

`semi-condensed`, `condensed`, `extra-condensed`, `ultra-condensed`

Specifies a more condensed font face than normal, with ultra-condensed as the most condensed.

`semi-expanded`, `expanded`, `extra-expanded`, `ultra-expanded`

Specifies a more expanded font face than normal, with ultra-expanded as the most expanded.

`<percentage>`

A `<percentage>` value between 50% and 200% (inclusive). Negative values are not allowed for this property.

In earlier versions of the `font-stretch` specification, the property accepts only the nine keyword values. CSS Fonts Level 4 extends the syntax to accept a `<percentage>` value as well. This enables variable fonts to offer something more like a continuum of character widths. For TrueType or OpenType variable fonts, the "wdth" variation is used to implement varying widths.

If the font does not provide a face that exactly matches the given value, then values less than 100% map to a narrower face, and values greater than or equal to 100% map to a wider face.

### Keyword to numeric mapping

The table below shows the mapping between keyword values and numeric percentages:

| Keyword | Percentage |
| --- | --- |
| `ultra-condensed` | 50% |
| `extra-condensed` | 62.5% |
| `condensed` | 75% |
| `semi-condensed` | 87.5% |
| `normal` | 100% |
| `semi-expanded` | 112.5% |
| `expanded` | 125% |
| `extra-expanded` | 150% |
| `ultra-expanded` | 200% |

### Variable fonts

Most fonts have a particular width which corresponds to one of the keyterm values. However some fonts, called variable fonts, can support a range of stretching with more or less fine granularity, and this can give the designer a much closer degree of control over the chosen weight. For this, percentage ranges are useful.

For TrueType or OpenType variable fonts, the "wdth" variation is used to implement varying glyph widths.

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

People with dyslexia and other cognitive conditions may have difficulty reading fonts that are too condensed, 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-stretch =
  auto                   |
  <'font-stretch'>{1,2}

```

Examples
--------

### Setting a percentage range for font-stretch

The following find a local Open Sans font or import it, and allow using the font for normal, semi-condensed and semi-expanded states.

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

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-weight`
* `font-style`
* `font-feature-settings`
* `font-variation-settings`
* `src`
* `unicode-range descriptor`


descent-override - CSS: Cascading Style Sheets

descent-override
================

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

Syntax
------

```css
descent-override: normal;
descent-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
-------------
```

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

```

Examples
--------

### Overriding metrics of a fallback font

The `descent-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);
  descent-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
--------

* `ascent-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`


src - CSS: Cascading Style Sheets

src
===

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.

* Learn more
* See full compatibility
* Report feedback
The **`src`** CSS descriptor for the `@font-face` at-rule specifies the resource containing font data. It is required for the `@font-face` rule to be valid.

Syntax
------

```css
/\* <url> values \*/
src: url(https://somewebsite.com/path/to/font.woff); /\* Absolute URL \*/
src: url(path/to/font.woff); /\* Relative URL \*/
src: url("path/to/font.woff"); /\* Quoted URL \*/
src: url(path/to/svgFont.svg#example); /\* Fragment identifying font \*/

/\* <font-face-name> values \*/
src: local(font); /\* Unquoted name \*/
src: local(some font); /\* Name containing space \*/
src: local("font"); /\* Quoted name \*/
src: local("some font"); /\* Quoted name containing a space \*/

/\* <tech(<font-tech>)> values \*/
src: url(path/to/fontCOLRv1.otf) tech(color-COLRv1);
src: url(path/to/fontCOLR-svg.otf) tech(color-SVG);

/\* <format(<font-format>)> values \*/
src: url(path/to/font.woff) format("woff");
src: url(path/to/font.otf) format("opentype");

/\* Multiple resources \*/
src:
  url(path/to/font.woff) format("woff"),
  url(path/to/font.otf) format("opentype");

/\* Multiple resources with font format and technologies \*/
src:
  url("trickster-COLRv1.otf") format(opentype) tech(color-COLRv1),
  url("trickster-outline.otf") format(opentype);
```

### Values

`url()`

Specifies an external reference consisting of a `<url>()`, followed by optional hints using the `format()` and `tech()` component values that specify the format and font technology of the resource referenced by the URL. The `format()` and `tech()` components are a comma-separated list of strings of known font formats and technologies. If a user agent doesn't support the font technology or formats, it skips downloading the font resource. If no format or technology hints are supplied, the font resource is always downloaded.

`format()`

 An optional declaration that follows the `url()` value that provides a hint for the user agent on the font format.
 If the value is not supported or invalid, the browser may not download the resource, potentially saving bandwidth.
 If omitted, the browser will download the resource and then detect the format.
 If including a font source for backward-compatibility that is not in the list of defined keywords, enclose the format string in quotes.
 Possible values are described in the Font formats section below.

`tech()`
Experimental

 An optional declaration that follows the `url()` value that provides a hint for the user agent on the font technology.
 The value for `tech()` may be one of the keywords described in Font technologies.

`local(<font-face-name>)`

 Specifies the font name should the font be available on the user's device.
 Enclosing the font name in quotes is optional.

**Note:** For OpenType and TrueType fonts, `<font-face-name>` is used to match either the Postscript name or the full font name in the name table of locally available fonts. Which type of name is used varies by platform and font, so you should include both of these names to assure proper matching across platforms. Platform substitutions for a given font name must not be used.

**Note:** Locally available fonts may have been preinstalled on the user's device, or may have been actively installed by the user.

While the set of preinstalled fonts is likely to be the same for all users of a particular device, the set of user-installed fonts is not. By discovering the set of user-installed fonts, a site can therefore build a fingerprint for the device, helping the site to track users across the web.

To prevent this, user agents may ignore user-installed fonts when using `local()`.

`<font-face-name>`

 Specifies the full name or postscript name of a locally-installed font face using the `local()` component value, which uniquely identifies a single font face within a larger family.
 The name can optionally be enclosed in quotes. The font face name is not case-sensitive.

**Note:** The Local Font Access API can be used to access the user's locally installed font data — this includes higher-level details such as names, styles, and families, as well as the raw bytes of the underlying font files.

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

 The value of this descriptor is a prioritized, comma-separated list of external references or locally-installed font face names, where each resource is specified using `url()` or `local()`.
 When a font is needed, the user agent iterates over the set of references listed using the first one it can successfully activate.
 Fonts containing invalid data or local font faces that are not found are ignored and the user agent loads the next font in the list.

 If multiple `src` descriptors are set, only the last declared rule that is able to load a resource is applied.
 If the last `src` descriptor can load a resource and doesn't include a `local()` font, the browser may download external font files and ignore the local version even if there is one available on the device.

**Note:** Values within descriptors that the browser considers invalid are ignored.
 Some browsers will ignore the whole descriptor if any item is invalid, even if only one item is invalid.
 This may affect design of fallbacks.
 See Browser compatibility for more information.

As with other URLs in CSS, the URL may be relative, in which case it is resolved relative to the location of the style sheet containing the `@font-face` rule. In the case of SVG fonts, the URL points to an element within a document containing SVG font definitions. If the element reference is omitted, a reference to the first defined font is implied. Similarly, font container formats that can contain more than one font load only one of the fonts for a given `@font-face` rule. Fragment identifiers are used to indicate which font to load. If a container format lacks a defined fragment identifier scheme, a simple 1-based indexing scheme (e.g., "font-collection#1" for the first font, "font-collection#2" for the second font, etc.) is used.

If the font file is a container for multiple fonts, a fragment identifier is included to indicate the sub-font that should be used, as shown below:

```css
/\* WhichFont is the PostScript name of a font in the font file \*/
src: url(collection.otc#WhichFont);
/\* WhichFont is the element id of a font in the SVG Font file \*/
src: url(fonts.svg#WhichFont);
```

### Font formats

 The following table shows the valid font keywords and their corresponding font formats.
 To check if a font format is supported by a browser within CSS, use the `@supports` rule.

| Keyword | Font Format | Common extensions |
| --- | --- | --- |
| `collection` | OpenType Collection | .otc, .ttc |
| `embedded-opentype` | Embedded OpenType | .eot |
| `opentype` | OpenType | .otf, .ttf |
| `svg` | SVG Font (deprecated) | .svg, .svgz |
| `truetype` | TrueType | .ttf |
| `woff` | WOFF 1.0 | .woff |
| `woff2` | WOFF 2.0 | .woff2 |

**Note:**

* `format(svg)` stands for SVG fonts, and `tech(color-SVG)` stands for OpenType fonts with SVG table (also called OpenType-SVG color fonts), which are completely different.
* The `opentype` and `truetype` values are equivalent whether the font file uses cubic bezier curves (within CFF/CFF2 table) or quadratic bezier curves (within glyph table).

Older non-normalized `format()` values have the following equivalent syntax; provided as a string enclosed in quotes for backward-compatibility reasons:

| Old syntax | Equivalent syntax |
| --- | --- |
| `format("woff2-variations")` | `format(woff2) tech(variations)` |
| `format("woff-variations")` | `format(woff) tech(variations)` |
| `format("opentype-variations")` | `format(opentype) tech(variations)` |
| `format("truetype-variations")` | `format(truetype) tech(variations)` |

### Font technologies

 The following table shows valid values for the `tech()` descriptor and their corresponding font technologies.
 To check if a font technology is supported by a browser within CSS, use the `@supports` at-rule.

| Keyword | Description |
| --- | --- |
| `color-cbdt` | Color bitmap data tables |
| `color-colrv0` | Multi-colored glyphs via COLR version 0 table |
| `color-colrv1` | Multi-colored glyphs via COLR version 1 table |
| `color-sbix` | Standard bitmap graphics tables |
| `color-svg` | SVG multi-colored tables |
| `features-aat` | TrueType `morx` and `kerx` tables |
| `features-graphite` | Graphite features, namely `Silf`, `Glat` , `Gloc` , `Feat`, and `Sill` tables |
| `features-opentype` | OpenType `GSUB` and `GPOS` tables |
| `incremental` | Incremental font loading |
| `palettes` | Font palettes by means of `font-palette` to select one of many color palettes in the font |
| `variations` | Font variations in TrueType and OpenType fonts to control the font axis, weight, glyphs, etc. |

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

|  |  |
| --- | --- |
| Related at-rule | `@font-face` |
| Initial value | `n/a (required)` |
| Computed value | as specified |

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

<url> [ format( <font-format> ) ]? [ tech( <font-tech># ) ]?  |
local( <family-name> )

<font-format> = [ <string> | collection | embedded-opentype | opentype | svg | truetype | woff | woff2 ]

<font-tech> = [ <font-features-tech> | <color-font-tech> | variations | palettes | incremental-patch | incremental-range | incremental-auto ]

<font-features-tech> = [ features-opentype | features-aat | features-graphite ]

<color-font-tech> = [ color-COLRv0 | color-COLRv1 | color-SVG | color-sbix | color-CBDT ]
```

Examples
--------

### Specifying font resources using url() and local()

The example below shows how to define two font faces with the same font family. The `font-family` is named `MainText`. The first font face has a regular font, and the second one is a bold version of the same font family.

```css
/\* Defining a regular font face \*/
@font-face {
  font-family: MainText;
  src: local(Futura-Medium),
    url('FuturaMedium.woff') format("woff"),
    url('FuturaMedium.otf') format("opentype");
    format("opentype");
}

/\* Defining a different bold font face for the same family \*/
@font-face {
  font-family: MainText;
  src: local(Gill Sans Bold), /\* full font name \*/
    local(GillSans-Bold), /\* postscript name \*/
    url('GillSansBold.woff') format("woff"),
    url('GillSansBold.otf') format("opentype"),
    url("GillSansBold.svg#MyFontBold"); /\* Referencing an SVG font fragment by id \*/
  font-weight: bold;
}

/\* Using the regular font face \*/
p {
  font-family: MainText;
}

/\* Font-family is inherited, but bold fonts are used \*/
p.bold {
  font-weight: bold;
}
```

### Specifying font resources using tech() and format() values

 The following example shows how to use the `tech()` and `format()` values to specify font resources.
 A font using `color-colrv1` technology and `opentype` format is specified using the `tech()` and `format()` values.
 A color font will be activated if the user agent supports it, and an `opentype` non-color is provided as a fallback.

```css
@font-face {
  font-family: "Trickster";
  src:
    url("trickster-COLRv1.otf") format(opentype) tech(color-COLRv1),
    url("trickster-outline.otf") format(opentype);
}

/\* Using the font face \*/
p {
  font-family: "Trickster";
}
```

### Specifying fallbacks for older browsers

 Browsers should use a `@font-face` with a single `src` descriptor listing possible sources for the font.
 Since the browser will use the first resource that it is able to load, items should be specified in the order of your preference for their usage.

 Generally this means that local files should appear before remote files and that resources with `format()` or `tech()` constraints should appear before resources that don't have them (otherwise the less-constrained version would always be selected).
 For example:

```css
@font-face {
  font-family: "MgOpenModernaBold";
  src:
    url("MgOpenModernaBoldIncr.otf") format("opentype") tech(incremental),
    url("MgOpenModernaBold.otf") format(opentype);
}
```

A browser that does not support `tech()` above should ignore the first item and attempt to load the second resource.

 Some browsers do not yet ignore invalid items, and instead fail the whole `src` descriptor if any value is invalid.
 If working with these browsers you can specify multiple `src` descriptors as fallbacks.
 Note that multiple `src` descriptors are attempted in reverse-order, so at the end we have our normal descriptor with all the items.

```css
@font-face {
  font-family: "MgOpenModernaBold";
  src: url("MgOpenModernaBold.otf") format(opentype);
  src: url("MgOpenModernaBoldIncr.otf") format("opentype") tech(incremental);
  src:
    url("MgOpenModernaBoldIncr.otf") format("opentype") tech(incremental),
    url("MgOpenModernaBold.otf") format(opentype);
}
```

### Checking if the user agent supports a font

 The following example shows how to check if the user agent supports a font technology using the `@supports` rule.
 The block of CSS inside `@supports` will be applied if the user agent supports `color-COLRv1` technology.

```css
@supports font-tech(color-COLRv1) {
  @font-face {
    font-family: "Trickster";
    src: url("trickster-COLRv1.otf") format(opentype) tech(color-COLRv1);
  }

  .colored\_text {
    font-family: "Trickster";
  }
}
```

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

| Specification |
| --- |
| CSS Fonts Module Level 4 # src-desc |

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

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

See also
--------

* `@font-face`
* `@supports`
* `font-display`
* `font-family`
* `font-stretch`
* `font-style`
* `font-weight`
* `font-feature-settings`
* `font-variation-settings`
* `unicode-range`


line-gap-override - CSS: Cascading Style Sheets

line-gap-override
=================

The **`line-gap-override`** CSS descriptor for the `@font-face` at-rule defines the line-gap metric for the font. The line-gap metric is the font recommended line-gap or external leading.

Syntax
------

```css
line-gap-override: normal;
line-gap-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
-------------
```

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

```

Examples
--------

### Overriding metrics of a fallback font

The `line-gap-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);
  line-gap-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-style - CSS: Cascading Style Sheets

font-style
==========

The **`font-style`** CSS descriptor allows authors to specify font styles for the fonts specified in the `@font-face` at-rule.

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

Syntax
------

```css
font-style: normal;
font-style: italic;
font-style: oblique;
font-style: oblique 30deg;
font-style: oblique 30deg 50deg;
```

### Values

`normal`

Selects the normal version of the font-family.

`italic`

Specifies that font-face is an italicized version of the normal font.

`oblique`

Specifies that the font-face is an artificially sloped version of the normal font.

`oblique` with angle

Selects a font classified as `oblique`, and additionally specifies an angle for the slant of the text.

`oblique` with angle range

Selects a font classified as `oblique`, and additionally specifies a range of allowable angle for the slant of the text. Note that a range is only supported when the `font-style` is `oblique`; for `font-style: normal` or `italic`, no second value is allowed.

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

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

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

font-style =
  auto                                      |
  normal                                    |
  italic                                    |
  oblique [ <angle [-90deg,90deg]>{1,2} ]?

```

Examples
--------

### Specifying an italic font style

As an example, consider the garamond font family, in its normal form, we get the following result:

```css
@font-face {
  font-family: garamond;
  src: url("garamond.ttf");
}
```

![unstyled Garamond](/en-US/docs/Web/CSS/@font-face/font-style/garamondunstyled.jpg)

The italicized version of this text uses the same glyphs present in the unstyled version, but they are artificially sloped by a few degrees.

![artificially sloped garamond](/en-US/docs/Web/CSS/@font-face/font-style/garamondartificialstyle.jpg)

On the other hand, if a true italicized version of the font family exists, we can include it in the `src` descriptor and specify the font style as italic, so that it is clear that the font is italicized. True italics use different glyphs and are a bit different from their upright counterparts, having some unique features and generally have a rounded and calligraphic quality. These fonts are specially created by font designers and are **not** artificially sloped.

```css
@font-face {
  font-family: garamond;
  src: url("garamond-italic.ttf");
  font-style: italic;
}
```

![italic garamond](/en-US/docs/Web/CSS/@font-face/font-style/garamonditalic.jpg)

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-weight`
* `font-feature-settings`
* `font-variation-settings`
* `src`
* `unicode-range`