Mastering wrapping of flex items - CSS: Cascading Style Sheets

Mastering wrapping of flex items
================================

Flexbox was designed as a single dimensional layout, meaning that it deals with laying out items as a row or as a column — but not both at once. There is however the ability to wrap flex items onto new lines, creating new rows if `flex-direction` is `row` and new columns if `flex-direction` is `column`. In this guide I will explain how this works, what it is designed for and what situations really require CSS Grid Layout rather than flexbox.

Making things wrap
------------------

The initial value of the `flex-wrap` property is `nowrap`. This means that if you have a set of flex items that are too wide for their container, they will overflow it. If you want to cause them to wrap once they become too wide you must add the `flex-wrap` property with a value of `wrap`, or use the shorthand `flex-flow` with values of `row wrap` or `column wrap`.

Items will then wrap in the container. In the next example I have ten items all with a `flex-basis` of `160px` and the ability to grow and shrink. Once the first row gets to a point where there is not enough space to place another 160 pixel item, a new flex line is created for the items and so on until all of the items are placed. As the items can grow, they will expand larger than 160 px in order to fill each row completely. If there is only one item on the final line it will stretch to fill the entire line.

We can see the same thing happening with columns. The container will need to have a height in order that the items will start wrapping and creating new columns, and items will stretch taller to fill each column completely.

Wrapping and flex-direction
---------------------------

Wrapping works as you might expect when combined with `flex-direction`. If `flex-direction` is set to `row-reverse` then the items will start from the end edge of the container and lay themselves out in reverse ordered lines.

Note that the reversing is only happening in the inline, row direction. We start on the right then go onto the second line and again start from the right. We aren't reversing in both directions, starting from the bottom coming up the container!

Single-dimensional layout explained
-----------------------------------

As we have seen from the above examples if our items are allowed to grow and shrink, when there are fewer items in the last row or column then those items grow to fill the available space.

There is no method in flexbox to tell items in one row to line up with items in the row above — each flex line acts like a new flex container. It deals with space distribution across the main axis. If there is only one item, and that item is allowed to grow, it will fill the axis just as if you had a single item flex container.

If you want layout in two dimensions then you probably want Grid Layout. We can compare our wrapped row example above with the CSS Grid version of that layout to see the difference. The following live sample uses CSS Grid Layout to create a layout that has as many columns of at least 160 pixels as will fit, distributing the extra space between all columns. However, in this case the items stay in their grid and don't stretch out when there are fewer of them on the final row.

This is the difference between one and two-dimensional layout. In a one dimensional method like flexbox, we only control the row or column. In two dimensional layout like grid we control both at the same time. If you want the space distribution row by row, use flexbox. If you don't, use Grid.

How do flexbox-based grid systems work?
---------------------------------------

Typically flexbox-based grid systems work by taking flexbox back to the familiar world of float-based layouts. If you assign percentage widths to flex items — either as `flex-basis` or by adding a width to the item itself leaving the value of `flex-basis` as `auto` — you can get the impression of a two dimensional layout. You can see this working in the example below.

Here I have set `flex-grow` and `flex-shrink` to `0` to make inflexible flex items and I'm then controlling flexibility using percentages, just like we used to do in float layouts.

If you need flex items to line up in the cross axis, controlling the width in this way will achieve that. In most cases however, adding widths to flex items in this way demonstrates that you would probably be better served by switching to grid layout for that component.

Creating gutters between items
------------------------------

To create gaps or gutters between flex items, use the `gap` property.

The gap property in CSS is a shorthand for `row-gap` and `column-gap`, specifying the size of gutters, which is the space between rows and columns within grid, flex, and multi-column layouts.

In Flexbox, the `gap` property is applied to the flex container. It creates a fixed space between adjacent flex items. However, the `gap` property is not the only thing that can put space between items. Margins, paddings, `justify-content`, and `align-content` can also increase the size of the gutter, affecting the actual size of the gap.

To see how the `gap` property differs from `margin` in both axes, try changing the `gap` value in the container `.box` and adding a `margin` value to the `.box > *` rule in the stylesheet below. Click the Reset button to revert to the previous values.

Collapsed items
---------------

The flexbox specification details what should happen if a flex item is collapsed by setting `visibility: collapse` on an item. See the MDN documentation for the `visibility` property. The specification describes the behavior as follows:

>
> "Specifying visibility:collapse on a flex item causes it to become a collapsed flex item, producing an effect similar to visibility:collapse on a table-row or table-column: the collapsed flex item is removed from rendering entirely, but leaves behind a "strut" that keeps the flex line's cross-size stable. Thus, if a flex container has only one flex line, dynamically collapsing or uncollapsing items may change the flex container's main size, but is guaranteed to have no effect on its cross size and won't cause the rest of the page's layout to "wobble". Flex line wrapping is re-done after collapsing, however, so the cross-size of a flex container with multiple lines might or might not change." - Collapsed items
>
>
>

This behavior is useful if you want to target flex items using JavaScript to show and hide content for example. The example in the specification demonstrates one such pattern.

In the following live example, I have a non-wrapped flex container. The third item has more content than the others yet is set to `visibility: collapse`; therefore, the flex container is retaining a *strut* of the height required to display this item. If you remove `visibility: collapse` from the CSS or change the value to `visible`, you will see the item appear, and the space is redistributed between non-collapsed items; the height of the flex container should not change.

**Note:** Use Firefox for the below two examples as Chrome and Safari treat collapse as hidden.

When dealing with multiple-line flex containers however you need to understand that the wrapping is re-done *after* collapsing. So the browser needs to re-do the wrapping behavior to account for the new space that the collapsed item has left in the inline direction.

This means that items might end up on a different line to the one they started on. In the case of an item being shown and hidden it could well cause the items to end up in a different row.

I have created this behavior in the next live example. You can see how the stretching changes row based on the location of the collapsed item. If you add more content to the second item, it changes row once it gets long enough. That top row then only becomes as tall as a single line of text.

If this causes a problem for your layout it may require a rethinking of the structure, for example putting each row into a separate flex container in order that they can't shift rows.

### Using `visibility: hidden` and `display: none`

 In previous live example, try using `visibility: hidden` or `display: none` instead of `visiblity: collapse`. Using `visibility: hidden`, the item is made invisible but the box is kept in the formatting structure, so it still behaves as if it were part of the layout.
 When you use `display: none`, the item is completely removed from the formatting structure. Not only is it invisible but the structure is removed as well. This means counters ignore it and things like transitions do not run.


Consistent list indentation - CSS: Cascading Style Sheets

Consistent list indentation
===========================

One of the most common style changes made to lists is a change in the indentation distance—that is, how far the list items are pushed over to the right. This article will help you understand indenting list items so that list item markers are visible.

To understand why this is the case, and more importantly how to avoid the problem altogether, it's necessary to examine the details of list construction.

Making a List
-------------

### The stand-alone list item

First, we consider the pure list item, not nested in a list of items. When using the HTML `<li>` element, the browser sets the `display` value to `list-item`. Whether list items not nested in a list are provided a marker (otherwise known as a "bullet") depends on the browser. We can remove that bullet with `list-style-type``: none`.

```css
li {
  border: 1px dashed red;
}
li:nth-of-type(n + 4) {
  list-style-type: none;
}
```

```
li {
  width: 15em;
}
```

```
<p>Default bullets depend on the browser:</p>
<li>A list item</li>
<li>A list item</li>
<li>A list item</li>
<p>These list items have their bullets removed:</p>
<li>A list item</li>
<li>A list item</li>
<li>A list item</li>
```

That dotted red border represents the outer edges of the content area of each list item. At this point, the list items have no padding or borders.

### List items nested in a list

Now we wrap these in a parent element; in this case, we'll wrap them in an unordered list (i.e., `<ul>`). According to the CSS box model, the list items' boxes must be displayed within the parent element's content area.

```css
ul {
  border: 1px dashed blue;
}
li {
  border: 1px dashed red;
  list-style-type: none;
}
```

```
body {
  width: 15em;
}
```

```
<ul>
  <li>A list item</li>
  <li>A list item</li>
  <li>A list item</li>
</ul>
```

The dotted blue border shows us the edges of the `<ul>` element's content area. That parent comes with both margin and padding. Browsers set the following default styles on unordered lists:

```css
ul {
  /\* user-agent styles \*/
  display: block;
  list-style-type: disc;
  margin-block-start: 1em;
  margin-block-end: 1em;
  padding-inline-start: 40px;
}
```

### Default bullet position

Now we put the list item markers back in. Since this is an unordered list, the list items inherit `list-style-type: disc;` browser styles, which are filled-circle "bullets," from their `<ul>` parent.

```css
li {
  border: 1px dashed red;
}
ul {
  border: 1px dotted blue;
}
ul:last-of-type {
  list-style-position: inside;
}
```

```
ul {
  width: 15em;
}
```

```
<p>These default to <code>list-style-position: outside</code>.</p>
<ul>
  <li>A list item</li>
  <li>A list item</li>
  <li>A list item</li>
</ul>
<p>These have <code>list-style-position: inside</code> set.</p>
<ul>
  <li>A list item</li>
  <li>A list item</li>
  <li>A list item</li>
</ul>
```

Visually, the markers are *outside* the content area of the `<ul>`, but that's not the important part here. What's key is that the markers are placed outside the "principal box" of the `<li>` elements, not the `<ul>`. They're sort of like appendages to the list items, hanging outside the content-area of the `<li>` but still attached to the `<li>`.

This is why, in every modern browser, markers are placed outside any border set for an `<li>` element when the value of `list-style-position` defaults to or is explicitly set to `outside`. When we changed it to `inside`, the markers were brought inside the `<li>`'s content, as though they're an inline box placed at the very beginning of the `<li>`.

Default indentation
-------------------

As noted above, all browsers provide the `<ul>` parent both margin and padding. While user agents CSS differ somewhat, they all include:

```css
ul,
ol {
  /\* user-agent styles \*/
  display: block;
  list-style-type: disc;
  margin-block-start: 1em;
  margin-block-end: 1em;
  padding-inline-start: 40px;
}
ol {
  list-style-type: decimal;
}
li {
  display: list-item;
  text-align: match-parent;
}
::marker {
  unicode-bidi: isolate;
  font-variant-numeric: tabular-nums;
  text-transform: none;
}
```

All browsers set `padding-inline-start` to 40 pixels for the `<ul>` element by default. In left-to-right languages, like English, this is the left *padding*. Any padding set in the author style sheets (that's your stylesheet) takes precedence.

If you want to be explicit, set the following in your style sheets to ensure, unless otherwise overridden, the list items in the main content area of your document, contained in the `<main>` section, are properly indented:

```css
:where(main ol, main ul) {
  margin-inline-start: 0;
  padding-inline-start: 40px;
}
```

And always nest your `<li>` elements in a `<ul>` or `<ol>`.


CSS selectors and combinators - CSS: Cascading Style Sheets

CSS selectors and combinators
=============================

CSS selectors are used to define a pattern of the elements that you want to select for applying a set of CSS rules on the selected elements. Combinators define the relationship between the selectors. Using various selectors and combinators, you can precisely select and style the desired elements based on their type, attributes, state, or relationship to other elements.

Types of selectors
------------------

There are over 80 selectors and combinators. CSS selectors can be grouped into the following categories based on the type of elements they can select.

### Basic selectors

The type selector selects all elements that have the given node name. For example, `div` will select all `<div>` elements and `input` will match any `<input>` element. The universal selector, denoted with an asterisk (`*`), is a special type selector that selects all elements.

The class selector selects all elements that have the given `class` attribute denoted by the class name prefixed with a period (`.`). For example, `.index` will match any element that has `class="index"`. The ID selector selects an element based on the value of its `id` attribute. The selector is the `id` prefixed with a "number sign" (U+0023, `#`). For example, `#toc` will match the element that has `id="toc"`. Both `class` and `id` are global attributes. There should be only one element with a given `id` in a document; but if there is more than one, the ID selector will match all the elements with that `id`.

When combining a type or universal selector with a class or id selector to create a compound selector, the type or universal selector must precede the class or id.

#### CSS

In this example, we declare four simple selectors and one compound selector using the four basic selector types, as described above.

```css
\* {
  font-style: italic;
}
p {
  color: red;
}
.myClass {
  text-decoration: underline;
}
#myId {
  font-family: monospace;
}
p.myClass#myId {
  font-size: 1.5rem;
}
```

#### HTML

```html
<p class="myClass" id="myId">I match everything.</p>
<p>I match the universal and type selectors only.</p>
```

#### Result

Combinators
-----------

Using CSS combinators, we can combine selectors to select DOM nodes based on their relationship to other elements within the document node tree. This combining of selectors with combinators creates complex selectors.

### Descendant combinator

The descendant combinator, denoted with one or more spaces, selects nodes that are descendants of the first element. For example, `div span` will match all `<span>` elements that are inside a `<div>` element.

### Child combinator

The child combinator is more specific than the descendant combinator. Denoted with the greater than character (`>`), the child combinator selects nodes that are direct children of the first element. Comparing with our previous example, `div > span` will match only the `<span>` elements that are direct children of a `<div>` element.

### Subsequent-sibling combinator

In addition to descendant selectors, CSS also enables selecting elements based on their siblings. The subsequent-sibling combinator, denoted with a tilde (`~`), selects siblings. Given `A ~ B`, all elements matching `B` will be selected if they are preceded by `A`, provided both `A` and `B` share the same parent. For example, `h2 ~ p` will match all `<p>` elements that follow an h2, immediately or not.

### Next-sibling combinator

The next-sibling combinator, denoted by the plus symbol (`+`), is similar to the subsequent-sibling. However, given `A + B`, it only matches `B` if `B` is immediately preceded by `A`, with both sharing the same parent. Amending our previous example, `h2 + p` will match only the single `<p>` element that *immediately* follows an `<h2>` element.

### Column combinator

There is also a column combinator, denoted by two pipe characters (`||`), which, when supported, selects nodes that belong to a column. For example, `col || td` will match all `<td>` elements that belong to the scope of the `<col>`.

### Namespace separator

The namespace separator is another combinator that is generally used in conjunction with the `@namespace` at-rule. This combinator is denoted by a single pipe character (`|`). It enables limiting type selectors and the universal selector to a specific namespace. For example, by defining a namespace such as `@namespace SVG url('http://www.w3.org/2000/svg');`, you can include selectors that target elements nested in an SVG namespace only. Declaring `SVG|a` would match links within SVGs and not those in the rest of the document. Namespacing can be useful to target MathML, SVG, or other XML-based content within your HTML.

#### CSS

In this example, we declare five relative selectors using simple selectors combined with combinators.

```css
h2 + p ~ p {
  font-style: italic;
}
h2 + p + p {
  color: red;
}
.myClass + p {
  text-decoration: underline;
}
#myId > .myClass {
  outline: 3px dashed red;
}
> p {
  font-size: 1.1rem;
}
```

#### HTML

```html
<h2 class="myClass" id="myId">
  No selectors match. <span class="myClass">This span has an outline</span> as
  it is both myClass and a child of #myId.
</h2>
<p>The first paragraph is underlined. All the paragraphs are 1.1rem.</p>
<p>
  The second paragraph is red. This and the following paragraphs are italic.
</p>
<p>The third paragraph is NOT red. It is italic and 1.1rem.</p>
<p class="myClass">
  Does not have an outline; this is a sibling of H2, not a child. It is italic
  and 1.1rem.
</p>
```

#### Result

### Creating complex selectors with CSS nesting

The above complex selectors can also be defined using simple selectors, combinators, and CSS nesting, with or without the `&` nesting selector.

#### CSS

In this example, we replicate the same five relative selectors using simple selectors combined with combinators, but this time with CSS nesting.

```css
h2 {
  & + p {
    & ~ p {
      font-style: italic;
    }
    & + p {
      color: red;
    }
  }
}
.myClass {
  & + p {
    text-decoration: underline;
  }
}
#myId {
  & > .myClass {
    outline: 3px dashed red;
  }
}
> p {
  font-size: 1.1rem;
}
```

#### HTML

```html
<h2 class="myClass" id="myId">
  No selectors match. <span class="myClass">This span has an outline</span> as
  it is both myClass and a child of #myId.
</h2>
<p>The first paragraph is underlined. All the paragraphs are 1.1rem.</p>
<p>
  The second paragraph is red. This and the following paragraphs are italic.
</p>
<p>The third paragraph is NOT red. It is italic and 1.1rem.</p>
<p class="myClass">
  Does not have an outline; this is a sibling of H2, not a child. It is italic
  and 1.1rem.
</p>
```

#### Result

Attribute selectors
-------------------

Attribute selectors select all elements that, depending on how the selector is written, either have the given attribute or have the given attribute with a substring value match.
 For example, `[type]` will match all elements that have the `type` attribute set (to any value), and `[type="submit"]` will match `<input type="submit">` and `<button type="submit">`, or any element with `type="submit"` set, even though this attribute-value pair is only supported on `<input>` and `<button>` elements. The match is case-insensitive.

The case sensitivity of the attribute depends on the language. Generally, in HTML, if an attribute is enumerated, the value in the selector is case-insensitive, even if the value is not one of the enumerated values or if the attribute is not a valid value for the element on which it is set. For non-enumerated attributes, like `class`, `id`, or any `data-*` attribute, or for non-HTML attributes, like `role` or `aria-*` attributes, the value match is case-sensitive; the match can be made case-insensitive with a case-insensitive modifier (`i`).

Pseudo-class selectors
----------------------

 The CSS selectors module defines over 60 pseudo-classes. Pseudo-classes are simple selectors, prefixed with a colon (`:`), that allow the selection of elements based on state information that is not contained in the document tree. `pseudo-classes` can be used to style an element based on its *state*.
 For example, the `:target` simple selector targets element of a URL containing a fragment identifier, and the `a:visited` compound selector matches all `<a>` elements that have been visited by a user.

The pseudo-classes can be categorized as element display state, input, linguistic, location, resource state, time-dimensional, tree-structural, user action, and functional.

Multiple pseudo-classes can be combined to create compound selectors. When combining a pseudo-class into a compound selector with a type or universal selector, the pseudo-class must follow the type selector or universal selector, if present.

Pseudo-element selectors
------------------------

Not all CSS selectors are defined in the CSS selectors module. CSS pseudo-element selectors are defined in the CSS pseudo-elements module.

CSS pseudo-elements, prefixed with two colons (`::`), represent entities that are not included in HTML. For example, the simple `::marker` selector selects list item bullets, and the compound selector `p::first-line` matches the first line of all `<p>` elements.

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

| Specification |
| --- |
| Selectors Level 4  |
| CSS Pseudo-Elements Module Level 4  |

See the pseudo-classes and pseudo-elements specification tables for details on those.

See also
--------

* Selector list
* CSS selector structure
* Specificity
* CSS nesting module


Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets

Using the :target pseudo-class in selectors
===========================================

When a URL points at a specific piece of a document, it can be difficult for the user to notice. Find out how you can use some simple CSS to draw attention to the target of a URL and improve the user's experience.

Picking a Target
----------------

The pseudo-class `:target` is used to style the target element of a URL containing a fragment identifier. For example, the URL `https://developer.mozilla.org/en-US/docs/Web/CSS#reference` contains the fragment identifier `#reference`. In HTML, identifiers are found as the values of either `id` or `name` attributes, since the two share the same namespace. Thus, the example URL would point to the heading "reference" in that document.

Suppose you wish to style any `h2` element that is the target of a URL, but do not want any other kind of element to get a target style. This is simple enough:

```css
h2:target {
  outline: 2px solid;
}
```

It's also possible to create styles that are specific to a particular fragment of the document. This is done using the same identifying value that is found in the URI. Thus, to add a background color to the `#reference` fragment, we would write:

```css
#reference:target {
  background-color: yellow;
}
```

Targeting all elements
----------------------

If the intent is to create a "blanket" style that will apply to all targeted elements, then the universal selector comes in handy:

```css
:target {
  color: red;
}
```

Example
-------

In the following example, there are five links that point to elements in the same document. Selecting the "First" link, for example, will cause `<h1 id="one">` to become the target element. Note that the document may jump to a new scroll position, since target elements are placed on the top of the browser window if possible.

```html
<h4 id="one">…</h4>
<p id="two">…</p>
<div id="three">…</div>
<a id="four">…</a> <em id="five">…</em>

<a href="#one">First</a>
<a href="#two">Second</a>
<a href="#three">Third</a>
<a href="#four">Fourth</a>
<a href="#five">Fifth</a>
```

Conclusion
----------

In cases where a fragment identifier points to a portion of the document, readers may become confused about which part of the document they're supposed to be reading. By styling the target of a URI, reader confusion can be reduced or eliminated.

See also
--------

* `:target`


CSS selector structure - CSS: Cascading Style Sheets

CSS selector structure
======================

The CSS selector represents a particular pattern of element or elements in a tree structure. The term "selector" can refer to a simple selector, a compound selector, or a complex selector. When included in the `:has()` pseudo-class as a parameter, these selectors are referred to as relative selectors, representing elements relative to one or more anchor elements.

These selectors can be combined into a comma-separated selector list. If any selector in a non-forgiving selector list is invalid, the entire selector list is invalidated.

### Simple selector

A **simple selector** is a selector with a single component, such as a single type selector, attribute selector, or pseudo-class, that's not used in combination with or contains any other selector component or combinator. A given element is said to match a simple selector when that simple selector accurately describes the element. Any selector that contains a single basic selector, attribute selector, pseudo-class, or pseudo-element selector is a simple selector.

```css
#myId {
}

[pattern\*="\d"] {
}
```

### Compound selector

A **compound selector** is a sequence of simple selectors that are not separated by a combinator. A compound selector represents a set of simultaneous conditions on a single element. A given element is said to match a compound selector when the element matches all the simple selectors in the compound selector.

```css
a#selected {
}

[type="checkbox"]:checked:focus {
}
```

In a compound selector, the type selector or universal selector must come first in the sequence of selectors. Only one type selector or universal selector is allowed in the sequence. As whitespace represents the descendant combinator, no whitespace is allowed between the simple selectors that make up a compound selector.

### Complex selector

A **complex selector** is a sequence of one or more simple and/or compound selectors that are separated by combinators, including the white space descendant combinator.

A complex selector represents a set of simultaneous conditions on a set of elements.

```css
a#selected > .icon {
}

.box h2 + p {
}
```

Selectors can be read from right to left. For example, `a#selected > .icon` matches all elements with a class of `icon` that are the direct children of the `<a>` element with the id `selected`. The selector `.box h2 + p` matches the first `<p>`s to come immediately after any `<h2>` elements that are descendants of any element with the class of `box`.

### Relative selector

A **relative selector** is a selector representing an element relative to one or more anchor elements preceded by a combinator. Relative selectors that don't begin with an explicit combinator have an implied descendant combinator.

```css
+ div#topic > #reference {
}

> .icon {
}

dt:has(+ img) ~ dd {
}
```

### Selector list

A **selector list** is a comma-separated list of simple, compound, and/or complex selectors. A given element is said to match a selector list when the element matches any (at least one) of the selectors in that selector list.

```css
#main,
article.heading {
}
```

If any selector in a non-forgiving selector list is invalid, the entire selector list is invalidated.

```css
#main,
:bad-pseudoclass,
.validClass {
  /\* `:bad-pseudoclass` is invalid, invalidating this style block \*/
}
```

The `:is()` and `:where()` pseudo-classes can be used to construct forgiving selector lists.

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

| Specification |
| --- |
| Selectors Level 4  |

See also
--------

* CSS selectors and combinators
* Forgiving selector list
* `Document.querySelector()`
* `Document.querySelectorAll()`
* CSS selectors module
* CSS pseudo-elements module


hsl() - CSS: Cascading Style Sheets

hsl()
=====

The **`hsl()`** functional notation expresses an sRGB color according to its *hue*, *saturation*, and *lightness* components. An optional *alpha* component represents the color's transparency.

**Note:** The legacy `hsla()` syntax is an alias for `hsl()`, accepting the same parameters and behaving in the same way.

Try it
------

Defining *complementary colors* with `hsl()` can be done with a single formula, as they are positioned on the same diameter of the color wheel. If `θ` is the hue angle of a color, its complementary one will have `180deg - θ` as its hue angle.

Syntax
------

```css
hsl(120deg 75% 25%)
hsl(120deg 75% 25% / 60%)
```

The function also accepts a legacy syntax in which all values are separated with commas.

### Values

Functional notation: `hsl(H S L[ / A])`

`H`

A `<number>`, an `<angle>`, or the keyword `none`, which represents the hue angle. More details on this type can be found on the `<hue>` reference.

`S`

A `<percentage>` or the keyword `none`, which represents saturation. Here `100%` is completely saturated, while `0%` is completely unsaturated (gray).

`L`

A `<percentage>` or the keyword `none`, which represents lightness. Here `100%` is white, `0%` is black, and `50%` is "normal".

`A` Optional

An `<alpha-value>` or the keyword `none`, where the number `1` corresponds to `100%` (full opacity).

**Note:** This functional notation serializes to sRGB values, and the values of the red, green, blue components may be rounded in serialization.

**Note:** See Missing color components for the effect of `none`.

### Formal syntax
```

<hsl()> =
  <legacy-hsl-syntax>  |
  <modern-hsl-syntax>

<legacy-hsl-syntax> =
  hsl( <hue> , <percentage> , <percentage> , <alpha-value>? )

<modern-hsl-syntax> =
  hsl( [ <hue> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? )

<hue> =
  <number>  |
  <angle>

<alpha-value> =
  <number>      |
  <percentage>

```

Examples
--------

### Using hsl() with conic-gradient()

The `hsl()` function works well with `conic-gradient()` as both deal with angles.
```

<div></div>
```

#### CSS

```css
div {
  width: 100px;
  height: 100px;
  background: conic-gradient(
    hsl(360 100% 50%),
    hsl(315 100% 50%),
    hsl(270 100% 50%),
    hsl(225 100% 50%),
    hsl(180 100% 50%),
    hsl(135 100% 50%),
    hsl(90 100% 50%),
    hsl(45 100% 50%),
    hsl(0 100% 50%)
  );
  clip-path: circle(closest-side);
}
```

#### Result

### Legacy syntax: comma-separated values

For legacy reasons, the `hsl()` function accepts a form in which all values are separated using commas.

#### HTML

```html
<div class="space-separated"></div>
<div class="comma-separated"></div>
```

#### CSS

```css
div {
  width: 100px;
  height: 50px;
  margin: 1rem;
}

div.space-separated {
  background-color: hsl(0 100% 50% / 50%);
}

div.comma-separated {
  background-color: hsl(0, 100%, 50%, 0.5);
}
```

#### Result

### Legacy syntax: hsla()

The legacy `hsla()` syntax is an alias for `hsl()`.

#### HTML

```html
<div class="hsl"></div>
<div class="hsla"></div>
```

#### CSS

```css
div {
  width: 100px;
  height: 50px;
  margin: 1rem;
}

div.hsl {
  background-color: hsl(0 100% 50% / 50%);
}

div.hsla {
  background-color: hsla(0, 100%, 50%, 0.5);
}
```

#### Result

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

| Specification |
| --- |
| CSS Color Module Level 4 # the-hsl-notation |

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

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

See also
--------

* List of all color notations
* `<hue>` data type
* Color picker tool on MDN
* Color picker by Lea Verou


oklch() - CSS: Cascading Style Sheets

oklch()
=======

The **`oklch()`** functional notation expresses a given color in the Oklch color space. It has the same L axis as `oklab()`, but uses polar coordinates C (Chroma) and H (Hue).

Syntax
------

```css
oklch(40.1% 0.123 21.57)
oklch(59.69% 0.156 49.77)
oklch(59.69% 0.156 49.77 / .5)
```

### Values

Functional notation: `oklch(L C H[ / A])`

`L`

A `<number>` between `0` and `1`, a `<percentage>` between `0%` and `100%`, or the keyword `none`, where the number `0` corresponds to `0%` (black) and the number `1` corresponds to `100%` (white). `L` specifies the perceived lightness.

`C`

A `<number>`, a `<percentage>`, or the keyword `none`, where `0%` is `0` and `100%` is the number `0.4`. It is a measure of the chroma (roughly representing the "amount of color"). Its minimum useful value is `0`, while the maximum is theoretically unbounded (but in practice does not exceed `0.5`).

`H`

A `<number>`, an `<angle>`, or the keyword `none`, which represents the hue angle. More details on this type can be found on the `<hue>` reference.

`A` Optional

An `<alpha-value>` or the keyword `none`, where the number `1` corresponds to `100%` (full opacity).

**Note:** See Missing color components for the effect of `none`.

### Formal syntax
```

<oklch()> =
  oklch( [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ <hue> | none ] [ / [ <alpha-value> | none ] ]? )

<hue> =
  <number>  |
  <angle>

<alpha-value> =
  <number>      |
  <percentage>

```

Examples
--------

### Adjusting the lightness, chroma, and hue of a color

The following example shows the effect of varying the `L` (lightness), `C` (chroma), and `H` (hue) values of the `oklch()` color function.

#### HTML

```html
<div data-color="blue"></div>
<div data-color="blue-light"></div>

<div data-color="red"></div>
<div data-color="red-chroma"></div>

<div data-color="green"></div>
<div data-color="green-hue"></div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
```

```css
[data-color="blue"] {
  background-color: oklch(60% 0.4 240);
}
[data-color="blue-light"] {
  background-color: oklch(90% 0.4 240);
}

[data-color="red"] {
  background-color: oklch(100% 0.4 30);
}
[data-color="red-chroma"] {
  background-color: oklch(100% 0.3 40);
}

[data-color="green"] {
  background-color: oklch(60% 0.57 161);
}
[data-color="green-hue"] {
  background-color: oklch(60% 0.57 181);
}
```

#### Result

### Adjusting the alpha value of a color

 The following example shows the effect of varying the `A` (alpha) value of the `oklch()` color function.
 The `red` and `red-alpha` elements overlap the `#background-div` element to demonstrate the effect of opacity.
 Giving `A` a value of `0.4` makes the color 40% opaque.

#### HTML

```html
<div id="background-div">
  <div data-color="red"></div>
  <div data-color="red-alpha"></div>
</div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
#background-div {
  background-color: oklch(100% 0.57 217);
  width: 150px;
  height: 40px;
}
```

```css
[data-color="red"] {
  background-color: oklch(50% 0.5 20);
}
[data-color="red-alpha"] {
  background-color: oklch(50% 0.5 20 / 0.4);
}
```

#### Result

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

| Specification |
| --- |
| CSS Color Module Level 4 # ok-lab |

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

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

See also
--------

* List of all color notations
* `<hue>` data type
* A perceptual color space for image processing
* OKLCH in CSS


lab() - CSS: Cascading Style Sheets

lab()
=====

The **`lab()`** functional notation expresses a given color in the CIE L\*a\*b\* color space. Lab represents the entire range of color that humans can see.

Syntax
------

```css
lab(29.2345% 39.3825 20.0664);
lab(52.2345% 40.1645 59.9971);
lab(52.2345% 40.1645 59.9971 / .5);
```

### Values

Functional notation: `lab(L a b[ / A])`

`L`

A `<number>` between `0` and `100`, a `<percentage>` between `0%` and `100%`, or the keyword `none`, which specifies the CIE Lightness. Here the number `0` corresponds to `0%` (black) and the number `100` corresponds to `100%` (white).

`a`

A `<number>` between `-125` and `125`, a `<percentage>` between `-100%` and `100%`, or the keyword `none`, which specifies the distance along the `a` axis in the CIELAB colorspace, that is how green/red the color is.

`b`

A `<number>` between `-125` and `125`, a `<percentage>` between `-100%` and `100%`, or the keyword `none`, which specifies the distance along the `b` axis in the CIELAB colorspace, that is how blue/yellow the color is.

`A` Optional

An `<alpha-value>` or the keyword `none`, where the number `1` corresponds to `100%` (full opacity).

**Note:** Usually when percentage values have a numeric equivalent in CSS, `100%` is equal to the number `1`.
 This case is notable where `100%` is equal to the number `100` for the `L` value and `125` for the `a` and `b` values.

**Note:** See Missing color components for the effect of `none`.

### Formal syntax
```

<lab()> =
  lab( [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? )

<alpha-value> =
  <number>      |
  <percentage>

```

Examples
--------

### Adjusting lightness and color axes with lab()

The following example shows the effect of varying the lightness, a-axis, and b-axis values of the `lab()` function.

#### HTML

```html
<div data-color="red"></div>
<div data-color="red-a"></div>

<div data-color="green"></div>
<div data-color="green-b"></div>

<div data-color="blue"></div>
<div data-color="blue-light"></div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
```

```css
[data-color="red"] {
  background-color: lab(100 125 125);
}
[data-color="red-a"] {
  background-color: lab(100 110 125);
}

[data-color="green"] {
  background-color: lab(75% -120 125);
}
[data-color="green-b"] {
  background-color: lab(75% -120 10);
}

[data-color="blue"] {
  background-color: lab(0 -120 -120);
}
[data-color="blue-light"] {
  background-color: lab(70 -120 -120);
}
```

#### Result

### Adjusting opacity with lab()

 The following example shows the effect of varying the `A` (alpha) value of the `lab()` functional notation.
 The `red` and `red-alpha` elements overlap the `#background-div` element to demonstrate the effect of opacity.
 Giving `A` a value of `0.4` makes the color 40% opaque.

#### HTML

```html
<div id="background-div">
  <div data-color="red"></div>
  <div data-color="red-alpha"></div>
</div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
#background-div {
  background-color: lightblue;
  width: 150px;
  height: 40px;
}
```

```css
[data-color="red"] {
  background-color: lab(100 125 125);
}
[data-color="red-alpha"] {
  background-color: lab(100 125 125 / 0.4);
}
```

#### Result

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

| Specification |
| --- |
| CSS Color Module Level 4 # lab-colors |

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

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

See also
--------

* The `<color>` data type for a list of all color notations
* LCH colors in CSS: what, why, and how?
* Safari Technology Preview 122 release notes: includes `lab()` and `lch()` colors


hwb() - CSS: Cascading Style Sheets

hwb()
=====

The **`hwb()`** functional notation expresses an sRGB color according to its hue, whiteness, and blackness. An optional alpha component represents the color's transparency.

Try it
------

Syntax
------

```css
hwb(194 0% 0%) /\* #00c3ff \*/
hwb(194 0% 0% / .5) /\* #00c3ff with 50% opacity \*/
```

### Values

Functional notation: `hwb(H W B[ / A])`

`H`

A `<number>`, an `<angle>`, or the keyword `none`, which represents the hue angle. More details on this type can be found on the `<hue>` reference.

`W`, `B`

Each as a `<percentage>` or the keyword `none`, which represent whiteness and blackness, respectively. They specify the amount of white and black to mix in, from `0%` (no whiteness or blackness) to `100%` (full whiteness or blackness).

If `W + B = 100%`, it defines some shade of gray. If `W + B > 100%`, `W` and `B` are effectively normalized as `W / (W + B)` and `B / (W + B)`, respectively.

`A` Optional

An `<alpha-value>` or the keyword `none`, where the number `1` corresponds to `100%` (full opacity).

**Note:** This functional notation serializes to sRGB values, and the values of the red, green, blue components may be rounded in serialization.

**Note:** See Missing color components for the effect of `none`.

### Formal syntax
```

<hwb()> =
  hwb( [ <hue> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? )

<hue> =
  <number>  |
  <angle>

<alpha-value> =
  <number>      |
  <percentage>

```

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

| Specification |
| --- |
| CSS Color Module Level 4 # the-hwb-notation |

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

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

See also
--------

* `<color>`: For a list of all color notations
* `<hue>`: the data type representing a hue angle of a color


color() - CSS: Cascading Style Sheets

color()
=======

The **`color()`** functional notation allows a color to be specified in a particular, specified colorspace rather than the implicit sRGB colorspace that most of the other color functions operate in.

Support for a particular colorspace can be detected with the `color-gamut` CSS media feature.

Syntax
------

```css
color(display-p3 1 0.5 0);
color(display-p3 1 0.5 0 / .5);
```

### Values

Functional notation: `color(colorspace c1 c2 c3[ / A])`

`colorspace`

An `<ident>` denoting one of the predefined color spaces: `srgb`, `srgb-linear`, `display-p3`, `a98-rgb`, `prophoto-rgb`, `rec2020`, `xyz`, `xyz-d50`, and `xyz-d65`.

`c1`, `c2`, `c3`

`<number>` between 0 and 1, a `<percentage>` or the keyword `none`, which provide the component values in the color space.

`A` Optional

An `<alpha-value>` or the keyword `none`, where the number `1` corresponds to `100%` (full opacity).

**Note:** See Missing color components for the effect of `none`.

### Formal syntax
```

<color()> =
  color( <colorspace-params> [ / [ <alpha-value> | none ] ]? )

<colorspace-params> =
  <predefined-rgb-params>  |
  <xyz-params>

<alpha-value> =
  <number>      |
  <percentage>

<predefined-rgb-params> =
  <predefined-rgb> [ <number> | <percentage> | none ]{3}

<xyz-params> =
  <xyz-space> [ <number> | <percentage> | none ]{3}

<predefined-rgb> =
  srgb          |
  srgb-linear   |
  display-p3    |
  a98-rgb       |
  prophoto-rgb  |
  rec2020

<xyz-space> =
  xyz      |
  xyz-d50  |
  xyz-d65

```

Examples
--------

### Using predefined colorspaces with color()

The following example shows the effect of varying the lightness, a-axis, and b-axis values of the `color()` function.

#### HTML

```html
<div data-color="red-a98-rgb"></div>
<div data-color="red-prophoto-rgb"></div>
<div data-color="green-srgb-linear"></div>
<div data-color="green-display-p3"></div>
<div data-color="blue-rec2020"></div>
<div data-color="blue-srgb"></div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
```

```css
[data-color="red-a98-rgb"] {
  background-color: color(a98-rgb 1 0 0);
}
[data-color="red-prophoto-rgb"] {
  background-color: color(prophoto-rgb 1 0 0);
}
[data-color="green-srgb-linear"] {
  background-color: color(srgb-linear 0 1 0);
}
[data-color="green-display-p3"] {
  background-color: color(display-p3 0 1 0);
}
[data-color="blue-rec2020"] {
  background-color: color(rec2020 0 0 1);
}
[data-color="blue-srgb"] {
  background-color: color(srgb 0 0 1);
}
```

#### Result

### Using the xyz colorspace with color()

The following example shows how to use the `xyz` colorspace to specify a color.

#### HTML

```html
<div data-color="red"></div>
<div data-color="green"></div>
<div data-color="blue"></div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
```

```css
[data-color="red"] {
  background-color: color(xyz 45 20 0);
}

[data-color="green"] {
  background-color: color(xyz-d50 0.3 80 0.3);
}

[data-color="blue"] {
  background-color: color(xyz-d65 5 0 50);
}
```

#### Result

### Using color-gamut media queries with color()

This example shows how to use the `color-gamut` media query to detect support for a particular colorspace and use that colorspace to specify a color.

#### HTML

```html
<div></div>
<div></div>
<div></div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
```

```css
@media (color-gamut: p3) {
  div {
    background-color: color(display-p3 1 0 0);
  }
}

@media (color-gamut: srgb) {
  div:nth-child(2) {
    background-color: color(srgb 1 0 0);
  }
}

@media (color-gamut: rec2020) {
  div:nth-child(3) {
    background-color: color(rec2020 1 0 0);
  }
}
```

#### Result

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

| Specification |
| --- |
| CSS Color Module Level 4 # color-function |

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

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

See also
--------

* The `<color>` data type for a list of all color notations
* `color-gamut` media feature
* Wide Gamut Color in CSS with Display-p3


device-cmyk() - CSS: Cascading Style Sheets

device-cmyk()
=============

The **`device-cmyk()`** functional notation is used to express CMYK colors in a device dependent way, specifying the cyan, magenta, yellow, and black components.

This approach to color is useful when creating material to be output to a particular printer, when the output for particular ink combinations is known. CSS processors may attempt to approximate the color, however the end result is likely to be different to the printed result.

Syntax
------

```css
device-cmyk(0 81% 81% 30%);
device-cmyk(0 81% 81% 30% / .5);
device-cmyk(0 81% 81% 30% / .5, rgb(178 34 34));
```

### Values

Functional notation: `device-cmyk(C M Y K[ / A][, color])`

`C`, `M`, `Y`, `K`

`<number>` or `<percentage>` values providing the cyan, magenta, yellow, and black components of CMYK color.

`A` Optional

An `<alpha-value>`, where the number `1` corresponds to `100%` (full opacity).

`color` Optional

An optional fallback `<color>` to use if the user agent does not know how to translate the CMYK color to RGB.

### Formal syntax
```

<device-cmyk()> =
  <legacy-device-cmyk-syntax>  |
  <modern-device-cmyk-syntax>

<legacy-device-cmyk-syntax> =
  device-cmyk( <number>#{4} )

<modern-device-cmyk-syntax> =
  device-cmyk( <cmyk-component>{4} [ / [ <alpha-value> | none ] ]? )

<cmyk-component> =
  <number>      |
  <percentage>  |
  none

<alpha-value> =
  <number>      |
  <percentage>

```

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

| Specification |
| --- |
| CSS Color Module Level 5 # device-cmyk |

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

There is no browser implementing this feature.


oklab() - CSS: Cascading Style Sheets

oklab()
=======

The **`oklab()`** functional notation expresses a given color in the Oklab color space, which attempts to mimic how color is perceived by the human eye. The `oklab()` works with a Cartesian coordinate system on the Oklab color space, the a- and b-axes. If you want a polar color system, chroma and hue, use `oklch()`.

Oklab is a perceptual color space and is useful to:

* Transform an image to grayscale, without changing its lightness.
* Modify the saturation of colors, while keeping user perception of hue and lightness
* Create smooth and uniform gradients of colors (when interpolated manually, for example, in a `<canvas>` element).

The function `oklab()` can represent any color from the Oklab color space that is wider than RGB and include wide gamut and P3 colors.

Syntax
------

```css
oklab(40.1% 0.1143 0.045);
oklab(59.69% 0.1007 0.1191);
oklab(59.69% 0.1007 0.1191 / 0.5);
```

### Values

Functional notation: `oklab(L a b[ / A])`

`L`

A `<number>` between `0` and `1`, a `<percentage>` between `0%` and `100%`, or the keyword `none`, where the number `0` corresponds to `0%` (black) and the number `1` corresponds to `100%` (white). `L` specifies the perceived lightness.

`a`

A `<number>` between `-0.4` and `0.4`, a `<percentage>` between `-100%` and `100%`, or the keyword `none`. It specifies the distance along the `a` axis in the Oklab colorspace, that is, how green or red the color is.

`b`

A `<number>` between `-0.4` and `0.4`, a `<percentage>` between `-100%` and `100%`, or the keyword `none`. It specifies the distance along the `b` axis in the Oklab colorspace, that is, how blue or yellow the color is.

`A` Optional

An `<alpha-value>` or the keyword `none`, where the number `1` corresponds to `100%` (full opacity).

**Note:** See Missing color components for the effect of `none`.

### Formal syntax
```

<oklab()> =
  oklab( [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? )

<alpha-value> =
  <number>      |
  <percentage>

```

Examples
--------

### Adjusting the lightness and axes with oklab()

The following example shows the effect of varying the lightness, a-axis, and b-axis values of the `oklab()` function.

#### HTML

```html
<div data-color="blue"></div>
<div data-color="blue-light"></div>

<div data-color="red"></div>
<div data-color="red-a"></div>

<div data-color="green"></div>
<div data-color="green-b"></div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
```

```css
[data-color="blue"] {
  background-color: oklab(0.5 -0.3 -0.4);
}
[data-color="blue-light"] {
  background-color: oklab(0.7 -0.3 -0.4);
}

[data-color="red"] {
  background-color: oklab(100% 0.4 0.4);
}
[data-color="red-a"] {
  background-color: oklab(100% 0.2 0.4);
}

[data-color="green"] {
  background-color: oklab(100% -100% 0.4);
}
[data-color="green-b"] {
  background-color: oklab(100% -100% 0.6);
}
```

#### Result

### Adjusting opacity with oklab()

 The following example shows the effect of varying the `A` (alpha) value of the `oklab()` function.
 The `red` and `red-alpha` elements overlap the `#background-div` element to demonstrate the effect of opacity.
 Giving the `red-alpha` element an opacity of `0.4` makes it appear more transparent than the `red` element.

#### HTML

```html
<div id="background-div">
  <div data-color="red"></div>
  <div data-color="red-alpha"></div>
</div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
#background-div {
  background-color: lightblue;
  width: 150px;
  height: 40px;
}
```

```css
[data-color="red"] {
  background-color: oklab(0.628 0.225 0.126);
}
[data-color="red-alpha"] {
  background-color: oklab(0.628 0.225 0.126 / 0.4);
}
```

#### Result

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

| Specification |
| --- |
| CSS Color Module Level 4 # ok-lab |

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

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

See also
--------

* The `<color>` data type for a list of all color notations
* `oklch()`: Another functional notation using the same color space as `oklab()` but in a polar coordinate system
* A perceptual color space for image processing on bottosson.github.io (2023)
* OKLAB color wheel on observablehq.com


color-contrast() - CSS: Cascading Style Sheets

color-contrast()
================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`color-contrast()`** functional notation takes a `color` value and compares it to a list of other `color` values, selecting the one with the highest contrast from the list.

Syntax
------

```css
color-contrast(wheat vs tan, sienna, #d2691e)
color-contrast(#008080 vs olive, var(--myColor), #d2691e)
```

### Values

Functional notation: `color-contrast(color vs color-list)`

`color`

Any valid `<color>`.

`vs`

A literal token as a component of the syntax.

`color-list`

A comma-separated list of at least two color values to compare with the first value.

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

| Specification |
| --- |
| CSS Color Module Level 6 # colorcontrast |

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

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


color-mix() - CSS: Cascading Style Sheets

color-mix()
===========

The **`color-mix()`** functional notation takes two `<color>` values and returns the result of mixing them in a given colorspace by a given amount.

Syntax
------

```css
color-mix(in lch, plum, pink);
color-mix(in lch, plum 40%, pink);
color-mix(in srgb, #34c9eb 20%, white);
color-mix(in hsl longer hue, hsl(120 100% 50%) 20%, white);
```

### Values

Functional notation: `color-mix(method, color1[ p1], color2[ p2])`

`method`

A `<color-interpolation-method>` specifying the interpolation color space.

`color1`, `color2`

`<color>` values to mix.

`p1`, `p2` Optional

`<percentage>` values between `0%` and `100%`, specifying the amount of each color to mix. They are normalized as follows:

* If both `p1` and `p2` are omitted, then `p1 = p2 = 50%`.
* If `p1` is omitted, then `p1 = 100% - p2`.
* If `p2` is omitted, then `p2 = 100% - p1`.
* If `p1 = p2 = 0%`, the function is invalid.
* If `p1 + p2 ≠ 100%`, then `p1' = p1 / (p1 + p2)` and `p2' = p2 / (p1 + p2)`, where `p1'` and `p2'` are the normalization results.

### Formal syntax
```

<color-mix()> =
  color-mix( <color-interpolation-method> , [ <color> && <percentage [0,100]>? ]#{2} )

<color-interpolation-method> =
  in [ <rectangular-color-space> | <polar-color-space> <hue-interpolation-method>? ]

<rectangular-color-space> =
  srgb          |
  srgb-linear   |
  display-p3    |
  a98-rgb       |
  prophoto-rgb  |
  rec2020       |
  lab           |
  oklab         |
  xyz           |
  xyz-d50       |
  xyz-d65

<polar-color-space> =
  hsl    |
  hwb    |
  lch    |
  oklch

<hue-interpolation-method> =
  [ shorter | longer | increasing | decreasing ] hue

```

Examples
--------

### Mixing two colors

In a supporting browser, the items have more blue, and therefore less white, as a higher percentage of `#34c9eb` is mixed in. When no value is given, the percentage defaults to 50%.

#### HTML

```html
<ul>
  <li>0%</li>
  <li>25%</li>
  <li>50%</li>
  <li>75%</li>
  <li>100%</li>
  <li></li>
</ul>
```

#### CSS
```

ul {
  display: flex;
  list-style-type: none;
  font-size: 150%;
  gap: 10px;
  border: 2px solid;
  padding: 10px;
}

li {
  padding: 10px;
  flex: 1;
  box-sizing: border-box;
  font-family: monospace;
  outline: 1px solid #34c9eb;
  text-align: center;
}
```

```css
li:nth-child(1) {
  background-color: color-mix(in srgb, #34c9eb 0%, white);
}

li:nth-child(2) {
  background-color: color-mix(in srgb, #34c9eb 25%, white);
}

li:nth-child(3) {
  background-color: color-mix(in srgb, #34c9eb 50%, white);
}

li:nth-child(4) {
  background-color: color-mix(in srgb, #34c9eb 75%, white);
}

li:nth-child(5) {
  background-color: color-mix(in srgb, #34c9eb 100%, white);
}

li:nth-child(6) {
  background-color: color-mix(in srgb, #34c9eb, white);
}
```

#### Result

### Using hue interpolation in color-mix()

 When using shorter hue interpolation, the resulting hue angle is halfway between the input angles when taking the shortest route around the color wheel.
 The longer hue interpolation method results in a hue angle which is the midpoint when taking the longer route around the color wheel.
 For more information, see `<hue-interpolation-method>`.

```html
<div class="color-one">color one</div>
<div class="color-two">color two</div>
<div class="shorter">mixed shorter</div>
<div class="longer">mixed longer</div>
```

#### CSS
```

body {
  display: flex;
  flex-wrap: wrap;
}
div {
  border: 1px solid;
  font: bold 150% monospace;
  height: 100px;
  margin: 10px 5%;
  width: 30%;
}
```

```css
.color-one {
  background-color: hsl(10 100% 50%);
}
.color-two {
  background-color: hsl(60 100% 50%);
}
.shorter {
  background-color: color-mix(
    in hsl shorter hue,
    hsl(10 100% 50%),
    hsl(60 100% 50%)
  );
}
.longer {
  background-color: color-mix(
    in hsl longer hue,
    hsl(10 100% 50%),
    hsl(60 100% 50%)
  );
}
```

#### Result

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

| Specification |
| --- |
| CSS Color Module Level 5 # color-mix |

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

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

See also
--------

* `<color>`
* `<color-interpolation-method>`
* `<hue>`


light-dark() - CSS: Cascading Style Sheets

light-dark()
============

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`light-dark()`** CSS `<color>` function enables setting two colors for a property - returning one of the two colors options by detecting if the developer has set a light or dark color scheme or the user has requested light or dark color theme - without needing to encase the theme colors within a `prefers-color-scheme` media feature query.
 Users are able to indicate their color-scheme preference through their operating system settings (e.g. light or dark mode) or their user agent settings. The `light-dark()` function enables providing two color values where any `<color>` value is accepted. The `light-dark()` CSS color function returns the first value if the user's preference is set to `light` or if no preference is set and the second value if the user's preference is set to `dark`.

To enable support for the `light-dark()` color function, the `color-scheme` must have a value of `light dark`, usually set on the `:root` pseudo-class.

```css
:root {
  color-scheme: light dark;
}
body {
  color: light-dark(#333b3c, #efefec);
  background-color: light-dark(#efedea, #223a2c);
}
```

Syntax
------

```css
/\* Named color values \*/
color: light-dark(black, white);

/\* RGB color values \*/
color: light-dark(rgb(0 0 0), rgb(255 255 255));

/\* Custom properties \*/
color: light-dark(var(--light), var(--dark));
```

### Values

Functional notation: `light-dark(light-color, dark-color)`

`light-color`

`<color>` value to be set for light `color-scheme`.

`dark-color`

`<color>` value to be set for dark `color-scheme`.

### Formal syntax
```

<light-dark()> =
  light-dark( <color> , <color> )

```

Example
-------

### Setting colors based on color scheme

By default, in supporting browsers, the color returned by the `light-dark()` color function depends on the user preference set through an operating system's settings (e.g., light or dark mode) or from a user agent setting. You can also change this setting in the browser's developer tools.

#### HTML

We include three sections to enable targeting light colors, dark colors, and the colors selected based on the user's preferred color scheme.

```html
<h1><code>light-dark()</code> CSS function</h1>
<section>
  <h2>Automatic</h2>
  <p>This section will react to the users system or user agent setting.</p>
</section>
<section class="light">
  <h2>Light</h2>
  <p>
    This section will be light due to the <code>color-scheme: light;</code>.
  </p>
</section>
<section class="dark">
  <h2>Dark</h2>
  <p>This section will be dark due to the <code>color-scheme: dark;</code>.</p>
</section>
```

#### CSS

We include colors for both light and dark themes. We also define `color-scheme` for the document on the `:root` to enable the `light-dark()` color function for the entire document.

```css
:root {
  /\* this has to be set to switch between light or dark \*/
  color-scheme: light dark;

  --light-bg: ghostwhite;
  --light-color: darkslategray;
  --light-code: tomato;

  --dark-bg: darkslategray;
  --dark-color: ghostwhite;
  --dark-code: gold;
}
\* {
  background-color: light-dark(var(--light-bg), var(--dark-bg));
  color: light-dark(var(--light-color), var(--dark-color));
}
code {
  color: light-dark(var(--light-code), var(--dark-code));
}
```

In addition to enabling the `light-dark()` function, the `color-scheme` property enables overriding a user's color scheme for document sections. Forcing a page section to only use a light or dark color scheme can be done by setting the `color-scheme` property to `light` or `dark`.

**Note:** Generally this should not be done, we are using it here for demonstation purposes. If the user has made a preference, you generally should not override their preferences.

```css
.light {
  /\* forces light color-scheme \*/
  color-scheme: light;
}
.dark {
  /\* forces dark color-scheme \*/
  color-scheme: dark;
}
```

```
section {
  padding: 0.8rem;
}
```

#### Result

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

| Specification |
| --- |
| CSS Color Module Level 5 # light-dark |

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

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

See also
--------

* `color-scheme`
* `<color>`
* CSS color module


rgb() - CSS: Cascading Style Sheets

rgb()
=====

The **`rgb()`** functional notation expresses a color according to its red, green, and blue components. An optional alpha component represents the color's transparency.

**Note:** The legacy `rgba()` syntax is an alias for `rgb()`, accepting the same parameters and behaving in the same way.

Try it
------

Syntax
------

```css
rgb(255 255 255)
rgb(255 255 255 / 50%)
```

The function also accepts a legacy syntax in which all values are separated with commas.

### Values

Functional notation: `rgb(R G B[ / A])`

`R`, `G`, `B`

Each as a `<number>` between `0` and `255`, a `<percentage>` between `0%` and `100%`, or the keyword `none`, which represent the red, green, and blue channels, respectively.

`A` Optional

An `<alpha-value>` or the keyword `none`, where the number `1` corresponds to `100%` (full opacity).

**Note:** This functional notation serializes to sRGB values, and the values of the red, green, blue components may be rounded in serialization.

**Note:** See Missing color components for the effect of `none`.

### Formal syntax
```

<rgb()> =
  <legacy-rgb-syntax>  |
  <modern-rgb-syntax>

<legacy-rgb-syntax> =
  rgb( <percentage>#{3} , <alpha-value>? )  |
  rgb( <number>#{3} , <alpha-value>? )

<modern-rgb-syntax> =
  rgb( [ <number> | <percentage> | none ]{3} [ / [ <alpha-value> | none ] ]? )

<alpha-value> =
  <number>      |
  <percentage>

```

Examples
--------

### Legacy syntax: comma-separated values

For legacy reasons, the `rgb()` function accepts a form in which all values are separated using commas.

#### HTML

```html
<div class="space-separated"></div>
<div class="comma-separated"></div>
```

#### CSS

```css
div {
  width: 100px;
  height: 50px;
  margin: 1rem;
}

div.space-separated {
  background-color: rgb(255 0 0 / 50%);
}

div.comma-separated {
  background-color: rgb(255, 0, 0, 0.5);
}
```

#### Result

### Legacy syntax: rgba()

The legacy `rgba()` syntax is an alias for `rgb()`.

#### HTML

```html
<div class="rgb"></div>
<div class="rgba"></div>
```

#### CSS

```css
div {
  width: 100px;
  height: 50px;
  margin: 1rem;
}

div.rgb {
  background-color: rgb(255 0 0 / 50%);
}

div.rgba {
  background-color: rgba(255 0 0 / 0.5);
}
```

#### Result

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

| Specification |
| --- |
| CSS Color Module Level 4 # rgb-functions |

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

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

See also
--------

* The `<color>` data type for a list of all color notations


lch() - CSS: Cascading Style Sheets

lch()
=====

The **`lch()`** functional notation expresses a given color in the LCH color space. It has the same L axis as `lab()`, but uses polar coordinates C (Chroma) and H (Hue).

Syntax
------

```css
lch(29.2345% 44.2 27);
lch(52.2345% 72.2 56.2);
lch(52.2345% 72.2 56.2 / .5);
```

### Values

Functional notation: `lch(L C H[ / A])`

`L`

A `<number>` between `0` and `100`, a `<percentage>` between `0%` and `100%`, or the keyword `none`, which specifies the CIE Lightness. Here the number `0` corresponds to `0%` (black) and the number `100` corresponds to `100%` (white).

`C`

A `<number>`, a `<percentage>`, or the keyword `none`, where `0%` is `0` and `100%` is the number `150`. It is a measure of the chroma (roughly representing the "amount of color"). Its minimum useful value is `0`, while its maximum is theoretically unbounded (but in practice does not exceed `230`).

`H`

A `<number>`, an `<angle>`, or the keyword `none`, which represents the hue angle. More details on this type can be found on the `<hue>` reference.

`A` Optional

An `<alpha-value>` or the keyword `none`, where the number `1` corresponds to `100%` (full opacity).

**Note:** Usually when percentage values have a numeric equivalent in CSS, `100%` is equal to the number `1`.
 This case is notable where `100%` is equal to the number `100` for the `L` value and `150` for the `C` value.

**Note:** See Missing color components for the effect of `none`.

### Formal syntax
```

<lch()> =
  lch( [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ <hue> | none ] [ / [ <alpha-value> | none ] ]? )

<hue> =
  <number>  |
  <angle>

<alpha-value> =
  <number>      |
  <percentage>

```

Examples
--------

### Adjusting lightness, chroma, and hue with lch()

The following example shows the effect of varying the `L` (lightness), `C` (chroma), and `H` (hue) values of the `lch()` functional notation.

#### HTML

```html
<div data-color="blue"></div>
<div data-color="blue-light"></div>

<div data-color="red"></div>
<div data-color="red-chroma"></div>

<div data-color="green"></div>
<div data-color="green-hue"></div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
```

```css
[data-color="blue"] {
  background-color: lch(0% 100 240);
}
[data-color="blue-light"] {
  background-color: lch(100% 100 240);
}

[data-color="red"] {
  background-color: lch(50% 130 20);
}
[data-color="red-chroma"] {
  background-color: lch(100% 30 20);
}

[data-color="green"] {
  background-color: lch(50% 132 130);
}
[data-color="green-hue"] {
  background-color: lch(50% 132 180);
}
```

#### Result

### Adjusting opacity with lch()

 The following example shows the effect of varying the `A` (alpha) value of the `lch()` functional notation.
 The `red` and `red-alpha` elements overlap the `#background-div` element to demonstrate the effect of opacity.
 Giving `A` a value of `0.4` makes the color 40% opaque.

#### HTML

```html
<div id="background-div">
  <div data-color="red"></div>
  <div data-color="red-alpha"></div>
</div>
```

#### CSS
```

div {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 5px;
  display: inline-block;
  border: 1px solid black;
}
#background-div {
  background-color: lch(100% 100 240);
  width: 150px;
  height: 40px;
}
```

```css
[data-color="red"] {
  background-color: lch(50% 130 20);
}
[data-color="red-alpha"] {
  background-color: lch(50% 130 20 / 0.4);
}
```

#### Result

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

| Specification |
| --- |
| CSS Color Module Level 4 # lab-colors |

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

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

See also
--------

* List of all color notations
* `<hue>` data type
* LCH colors in CSS: what, why, and how?


Grid template areas - CSS: Cascading Style Sheets

Grid template areas
===================

In the previous guide, we looked at grid lines and how to position items against those lines. When you use CSS grid layout, you always have lines, and this can be a straightforward way to place items on your grid. However, there is an alternate method to use for positioning items on the grid which you can use alone or in combination with line-based placement. This method involves placing our items using named template areas, and we will find out exactly how this method works. You will see very quickly why we sometimes call this the ascii-art method of grid layout!

Naming a grid area
------------------

You have already encountered the `grid-area` property. This is the property that can take as a value all four of the lines used to position a grid area.

```css
.box1 {
  grid-area: 1 / 1 / 4 / 2;
}
```

What we are doing here when defining all four lines, is defining the area by specifying the lines that enclose that area.

![The Grid Area defined by lines](/en-US/docs/Web/CSS/CSS_grid_layout/Grid_template_areas/4_area.png)

We can also define an area by giving it a name and then specify the location of that area in the value of the `grid-template-areas` property. You can choose what you would like to name your area. For example, if I wish to create the layout shown below I can identify four main areas.

* a header
* a footer
* a sidebar
* the main content

![An image showing a simple two column layout with header and footer](/en-US/docs/Web/CSS/CSS_grid_layout/Grid_template_areas/4_layout.png)

With the `grid-area` property I can assign each of these areas a name. This will not yet create any layout, but we now have named areas to use in a layout.

```css
.header {
  grid-area: hd;
}
.footer {
  grid-area: ft;
}
.content {
  grid-area: main;
}
.sidebar {
  grid-area: sd;
}
```

Having defined these names I then create my layout. This time, instead of placing my items using line numbers specified on the items themselves, I create the whole layout on the grid container.

```css
.wrapper {
  display: grid;
  grid-template-columns: repeat(9, 1fr);
  grid-auto-rows: minmax(100px, auto);
  grid-template-areas:
    "hd hd hd hd hd hd hd hd hd"
    "sd sd sd main main main main main main"
    "ft ft ft ft ft ft ft ft ft";
}
```

```
\* {
  box-sizing: border-box;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
  max-width: 940px;
  margin: 0 auto;
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}
```

```html
<div class="wrapper">
  <div class="header">Header</div>
  <div class="sidebar">Sidebar</div>
  <div class="content">Content</div>
  <div class="footer">Footer</div>
</div>
```

Using this method we do not need to specify anything at all on the individual grid items, everything happens on our grid container. We can see the layout described as the value of the `grid-template-areas` property.

Leaving a grid cell empty
-------------------------

We have completely filled our grid with areas in this example, leaving no white space. However you can leave grid cells empty with this method of layout. To leave a cell empty use the full stop character, '`.`'. If I want to only display the footer directly under the main content I would need to leave the three cells underneath the sidebar empty.

```css
.header {
  grid-area: hd;
}
.footer {
  grid-area: ft;
}
.content {
  grid-area: main;
}
.sidebar {
  grid-area: sd;
}
```

```
\* {
  box-sizing: border-box;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
  max-width: 940px;
  margin: 0 auto;
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}
```

```css
.wrapper {
  display: grid;
  grid-template-columns: repeat(9, 1fr);
  grid-auto-rows: minmax(100px, auto);
  grid-template-areas:
    "hd hd hd hd hd hd hd hd hd"
    "sd sd sd main main main main main main"
    ". . . ft ft ft ft ft ft";
}
```

```html
<div class="wrapper">
  <div class="header">Header</div>
  <div class="sidebar">Sidebar</div>
  <div class="content">Content</div>
  <div class="footer">Footer</div>
</div>
```

In order to make the layout neater I can use multiple `.` characters. As long as there is at least one white space between the full stops it will be counted as one cell. For a complex layout there is a benefit to having the rows and columns neatly aligned. It means that you can actually see, right there in the CSS, what this layout looks like.

Spanning multiple cells
-----------------------

In our example each of the areas spans multiple grid cells and we achieve this by repeating the name of that grid area multiple times with white space between. You can add extra white space in order to keep your columns neatly lined up in the value of `grid-template-areas`. You can see that I have done this in order that the `hd` and `ft` line up with `main`.

The area that you create by chaining the area names must be rectangular, at this point there is no way to create an L-shaped area. The specification does note that a future level might provide this functionality. You can however span rows just as easily as columns. For example we could make our sidebar span down to the end of the footer by replacing the `.` with `sd`.

```css
.header {
  grid-area: hd;
}
.footer {
  grid-area: ft;
}
.content {
  grid-area: main;
}
.sidebar {
  grid-area: sd;
}
```

```
\* {
  box-sizing: border-box;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
  max-width: 940px;
  margin: 0 auto;
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}
```

```css
.wrapper {
  display: grid;
  grid-template-columns: repeat(9, 1fr);
  grid-auto-rows: minmax(100px, auto);
  grid-template-areas:
    "hd hd hd hd hd hd hd hd hd"
    "sd sd sd main main main main main main"
    "sd sd sd ft ft ft ft ft ft";
}
```

```
<div class="wrapper">
  <div class="header">Header</div>
  <div class="sidebar">Sidebar</div>
  <div class="content">Content</div>
  <div class="footer">Footer</div>
</div>
```

The value of `grid-template-areas` must show a complete grid, otherwise it is invalid (and the property is ignored). This means that you must have the same number of cells for each row, if empty with a full stop character demonstrating that the cell is to be left empty. You will also create an invalid grid if your areas are not rectangular.

Redefining the grid using media queries
---------------------------------------

As our layout is now contained in one part of the CSS, this makes it very easy to make changes at different breakpoints. You can do this by redefining the grid, the position of items on the grid, or both at once.

When doing this, define the names for your areas outside of any media queries. That way the content area would always be called `main` no matter where on the grid it is placed.

For our layout above, we might like to have a very simple layout at narrow widths, defining a single column grid and stacking up our items.
```

\* {
  box-sizing: border-box;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
  max-width: 940px;
  margin: 0 auto;
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}
```

```css
.header {
  grid-area: hd;
}
.footer {
  grid-area: ft;
}
.content {
  grid-area: main;
}
.sidebar {
  grid-area: sd;
}

.wrapper {
  display: grid;
  grid-auto-rows: minmax(100px, auto);
  grid-template-columns: 1fr;
  grid-template-areas:
    "hd"
    "main"
    "sd"
    "ft";
}
```

We can then redefine that layout inside media queries to go to our two columns layout, and perhaps take it to a three column layout if the available space is even wider. Note that for the wide layout I keep my nine column track grid, I redefine where items are placed using `grid-template-areas`.

```css
@media (min-width: 500px) {
  .wrapper {
    grid-template-columns: repeat(9, 1fr);
    grid-template-areas:
      "hd hd hd hd hd hd hd hd hd"
      "sd sd sd main main main main main main"
      "sd sd sd ft ft ft ft ft ft";
  }
}
@media (min-width: 700px) {
  .wrapper {
    grid-template-areas:
      "hd hd hd hd hd hd hd hd hd"
      "sd sd main main main main main ft ft";
  }
}
```

```
<div class="wrapper">
  <div class="header">Header</div>
  <div class="sidebar">Sidebar</div>
  <div class="content">Content</div>
  <div class="footer">Footer</div>
</div>
```

Using `grid-template-areas` for UI elements
-------------------------------------------

Many of the grid examples you will find online make the assumption that you will use grid for main page layout, however grid can be just as useful for small elements as those larger ones. Using `grid-template-areas` can be especially nice as it is easy to see in the code what your element looks like.

### Media object example

As a very simple example we can create a "media object". This is a component with space for an image or other media on one side and content on the other. The image might be displayed on the right or left of the box.

![Images showing an example media object design](/en-US/docs/Web/CSS/CSS_grid_layout/Grid_template_areas/4_media_objects.png)

Our grid is a two-column track grid, with the column for the image sized at `1fr` and the text `3fr`. If you wanted a fixed width image area, then you could set the image column as a pixel width, and assign the text area `1fr`. A single column track of `1fr` would then take up the rest of the space.

We give the image area a grid area name of `img` and the text area `content`, then we can lay those out using the `grid-template-areas` property.

```css
\* {
  box-sizing: border-box;
}

.media {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
  max-width: 400px;
  display: grid;
  grid-template-columns: 1fr 3fr;
  grid-template-areas: "img content";
  margin-bottom: 1em;
}

.media .image {
  grid-area: img;
  background-color: #ffd8a8;
}

.media .text {
  grid-area: content;
  padding: 10px;
}
```

```html
<div class="media">
  <div class="image"></div>
  <div class="text">
    This is a media object example. We can use grid-template-areas to switch
    around the image and text part of the media object.
  </div>
</div>
```

### Displaying the image on the other side of the box

We might want to be able to display our box with the image the other way around. To do this, we redefine the grid to put the `1fr` track last, and flip the values in `grid-template-areas`.

```css
\* {
  box-sizing: border-box;
}

.media {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
  max-width: 400px;
  display: grid;
  grid-template-columns: 1fr 3fr;
  grid-template-areas: "img content";
  margin-bottom: 1em;
}

.media.flipped {
  grid-template-columns: 3fr 1fr;
  grid-template-areas: "content img";
}

.media .image {
  grid-area: img;
  background-color: #ffd8a8;
}

.media .text {
  grid-area: content;
  padding: 10px;
}
```

```html
<div class="media flipped">
  <div class="image"></div>
  <div class="text">
    This is a media object example. We can use grid-template-areas to switch
    around the image and text part of the media object.
  </div>
</div>
```

Grid definition shorthands
--------------------------

Having looked at various ways of placing items on our grids and many of the properties used to define grid, this is a good time to take a look at a couple of shorthands that are available for defining the grid and many things about it all in one line of CSS.

These can quickly become difficult to read for other developers, or even your future self. However they are part of the specification and it is likely you will come across them in examples or in use by other developers, even if you choose not to use them.

Before using any shorthand it is worth remembering that shorthands not only enable the setting of many properties in one go, they also act to **reset things** to their initial values that you do not, or cannot set in the shorthand. Therefore if you use a shorthand, be aware that it may reset things you have applied elsewhere.

The two shorthands for the grid container are the Explicit Grid Shorthand `grid-template` and the Grid Definition Shorthand `grid`.

### `grid-template`

The `grid-template` property sets the following properties:

* `grid-template-rows`
* `grid-template-columns`
* `grid-template-areas`

The property is referred to as the Explicit Grid Shorthand because it is setting those things that you control when you define an explicit grid, and not those which impact any implicit row or column tracks that might be created.

The following code creates a layout using `grid-template` that is the same as the layout created earlier in this guide.

```css
.wrapper {
  display: grid;
  grid-template:
    "hd hd hd hd hd hd hd hd hd" minmax(100px, auto)
    "sd sd sd main main main main main main" minmax(100px, auto)
    "ft ft ft ft ft ft ft ft ft" minmax(100px, auto)
    / 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
}
```

The first value is our `grid-template-areas` value but we also declare the size of the row at the end of each row. This is what the `minmax(100px, auto)` is doing.

Then after `grid-template-areas` we have a forward slash, after that is an explicit track listing of column tracks.

### `grid`

The `grid` shorthand goes a step further and also sets properties used by the implicit grid. So you will be setting:

* `grid-template-rows`
* `grid-template-columns`
* `grid-template-areas`
* `grid-auto-rows`
* `grid-auto-columns`
* `grid-auto-flow`

You can use this syntax in the exact same way as the `grid-template` shorthand, just be aware than when doing so you will reset the other values set by the property.

```css
.wrapper {
  display: grid;
  grid:
    "hd hd hd hd hd hd hd hd hd" minmax(100px, auto)
    "sd sd sd main main main main main main" minmax(100px, auto)
    "ft ft ft ft ft ft ft ft ft" minmax(100px, auto)
    / 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
}
```

We will revisit the other functionality offered by this shorthand later in these guides when we take a look at auto placement and the grid-auto-flow property.

If you have worked through these initial guides you now should be in a position to create grid layouts using line-based placement or named areas. Take some time to build some common layout patterns using grid, while there are lots of new terms to learn, the syntax is relatively straightforward. As you develop examples, you are likely to come up with some questions and use cases for things we haven't covered yet. In the rest of these guides we will be looking at some more of the detail included in the specification – in order that you can begin to create advanced layouts with it.