repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/learn/css | data/mdn-content/files/en-us/learn/css/building_blocks/index.md | ---
title: CSS building blocks
slug: Learn/CSS/Building_blocks
page-type: learn-module
---
{{LearnSidebar}}
This module carries on where [CSS first steps](/en-US/docs/Learn/CSS/First_steps) left off — now that you've gained familiarity with the language and its syntax, and got some basic experience using it, it's time to dive a bit deeper. This module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more.
The aim here is to provide you with a toolkit for writing competent CSS and help you understand all the essential theory, before moving on to more specific disciplines like [text styling](/en-US/docs/Learn/CSS/Styling_text) and [CSS layout](/en-US/docs/Learn/CSS/CSS_layout).
> **Callout:**
>
> #### Looking to become a front-end web developer?
>
> We have put together a course that includes all the essential information you need to
> work towards your goal.
>
> [**Get started**](/en-US/docs/Learn/Front-end_web_developer)
## Prerequisites
Before starting this module, you should have:
1. Basic familiarity with using computers, and using the Web passively (i.e., just looking at it, consuming the content).
2. A basic work environment set up as detailed in [Installing basic software](/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software), and an understanding of how to create and manage files, as detailed in [Dealing with files](/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files).
3. Basic familiarity with HTML, as discussed in the [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) module.
4. An understanding of the basics of CSS, as discussed in the [CSS first steps](/en-US/docs/Learn/CSS/First_steps) module.
> **Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as [JSBin](https://jsbin.com/) or [Glitch](https://glitch.com/).
## Guides
This module contains the following articles, which cover the most essential parts of the CSS language. Along the way you'll come across plenty of exercises to allow you to test your understanding.
- [CSS selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors)
- : There are a wide variety of CSS selectors available, allowing for fine-grained precision when selecting elements to style. In this article and its sub-articles, we'll run through the different types in great detail, seeing how they work. The sub-articles are as follows:
- [Type, class, and ID selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors)
- [Attribute selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Attribute_selectors)
- [Pseudo-classes and pseudo-elements](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements)
- [Combinators](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Combinators)
- [Cascade, specificity, and inheritance](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance)
- : The aim of this lesson is to develop your understanding of some of the most fundamental concepts of CSS — the cascade, specificity, and inheritance — which control how CSS is applied to HTML and how conflicts are resolved.
- [Cascade layers](/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers)
- : This lesson aims to introduce you to [cascade layers](/en-US/docs/Web/CSS/@layer), a more advanced feature that builds on the fundamental concepts of the [CSS cascade](/en-US/docs/Web/CSS/Cascade) and [CSS specificity](/en-US/docs/Web/CSS/Specificity).
- [The box model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model)
- : Everything in CSS has a box around it, and understanding these boxes is key to being able to create layouts with CSS, or to align items with other items. In this lesson, we will take a proper look at the CSS _Box Model_, in order that you can move onto more complex layout tasks with an understanding of how it works and the terminology that relates to it.
- [Backgrounds and borders](/en-US/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders)
- : In this lesson we will take a look at some of the creative things you can do with CSS backgrounds and borders. From adding gradients, background images, and rounded corners, backgrounds and borders are the answer to a lot of styling questions in CSS.
- [Handling different text directions](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions)
- : In recent years, CSS has evolved in order to better support different directionality of content, including right-to-left but also top-to-bottom content (such as Japanese) — these different directionalities are called **writing modes**. As you progress in your study and begin to work with layout, an understanding of writing modes will be very helpful to you, therefore we will introduce them in this article.
- [Overflowing content](/en-US/docs/Learn/CSS/Building_blocks/Overflowing_content)
- : In this lesson we will look at another important concept in CSS — **overflow**. Overflow is what happens when there is too much content to be contained comfortably inside a box. In this guide, you will learn what it is and how to manage it.
- [CSS values and units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units)
- : Every property used in CSS has a value or set of values that are allowed for that property. In this lesson, we will take a look at some of the most common values and units in use.
- [Sizing items in CSS](/en-US/docs/Learn/CSS/Building_blocks/Sizing_items_in_CSS)
- : In the various lessons so far you have come across a number of ways to size items on a web page using CSS. Understanding how big the different features in your design will be is important, and in this lesson, we will summarize the various ways elements get a size via CSS and define a few terms around sizing that will help you in the future.
- [Images, media, and form elements](/en-US/docs/Learn/CSS/Building_blocks/Images_media_form_elements)
- : In this lesson we will take a look at how certain special elements are treated in CSS. Images, other media, and form elements behave a little differently in terms of your ability to style them with CSS than regular boxes. Understanding what is and isn't possible can save some frustration, and this lesson will highlight some of the main things that you need to know.
- [Styling tables](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables)
- : Styling an HTML table isn't the most glamorous job in the world, but sometimes we all have to do it. This article provides a guide to making HTML tables look good, with some specific table styling techniques highlighted.
- [Debugging CSS](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS)
- : Sometimes when writing CSS you will encounter an issue where your CSS doesn't seem to be doing what you expect. This article will give you guidance on how to go about debugging a CSS problem, and show you how the DevTools included in all modern browsers can help you find out what is going on.
- [Organizing your CSS](/en-US/docs/Learn/CSS/Building_blocks/Organizing)
- : As you start to work on larger stylesheets and big projects you will discover that maintaining a huge CSS file can be challenging. In this article, we will take a brief look at some best practices for writing your CSS to make it easily maintainable, and some of the solutions you will find in use by others to help improve maintainability.
## Assessments
The following assessments will test your understanding of the CSS covered in the guides above.
- [Fundamental CSS comprehension](/en-US/docs/Learn/CSS/Building_blocks/Fundamental_CSS_comprehension)
- : This assessment tests your understanding of basic syntax, selectors, specificity, box model, and more.
- [Creating fancy letterheaded paper](/en-US/docs/Learn/CSS/Building_blocks/Creating_fancy_letterheaded_paper)
- : If you want to make the right impression, writing a letter on nice letterheaded paper can be a really good start. In this assessment, we'll challenge you to create an online template to achieve such a look.
- [A cool looking box](/en-US/docs/Learn/CSS/Building_blocks/A_cool_looking_box)
- : Here you'll get some practice in using background and border styling to create an eye-catching box.
## See also
- [Advanced styling effects](/en-US/docs/Learn/CSS/Building_blocks/Advanced_styling_effects)
- : This article acts as a box of tricks, providing an introduction to some interesting advanced styling features such as box shadows, blend modes, and filters.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/creating_fancy_letterheaded_paper/index.md | ---
title: Creating fancy letterheaded paper
slug: Learn/CSS/Building_blocks/Creating_fancy_letterheaded_paper
page-type: learn-module-assessment
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/CSS/Building_blocks/Fundamental_CSS_comprehension", "Learn/CSS/Building_blocks/A_cool_looking_box", "Learn/CSS/Building_blocks")}}
If you want to make the right impression, writing a letter on nice letterheaded paper can be a really good start. In this assessment we'll challenge you to create an online template to achieve such a look.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Before attempting this assessment you should have already worked through
all the articles in this module.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To test comprehension of CSS box model, and other box-related features
such as implementing backgrounds.
</td>
</tr>
</tbody>
</table>
## Starting point
To get this assessment started, you should:
- Make local copies of the [HTML](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/letterheaded-paper-start/index.html) and [CSS](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/letterheaded-paper-start/style.css) — save them as `index.html` and `style.css` in a new directory.
- Save local copies of the [top](https://raw.githubusercontent.com/mdn/learning-area/master/css/styling-boxes/letterheaded-paper-start/top-image.png), [bottom](https://raw.githubusercontent.com/mdn/learning-area/master/css/styling-boxes/letterheaded-paper-start/bottom-image.png) and [logo](https://raw.githubusercontent.com/mdn/learning-area/master/css/styling-boxes/letterheaded-paper-start/logo.png) images in the same directory as your code files.
Alternatively, you could use an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
You could paste the HTML and fill in the CSS into one of these online editors.
> **Note:** If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Project brief
You have been given the files needed to create a letterheaded paper template. You just need to put the files together. To get there, you need to:
### The main letter
- Apply the CSS to the HTML.
- Add a background declaration to the letter that:
- Fixes the top image to the top of the letter
- Fixes the bottom image to the bottom of the letter
- Adds a semi-transparent gradient over the top of both of the previous backgrounds that gives the letter a bit of texture. Make it slightly dark right near the top and bottom, but completely transparent for a large part of the center.
- Add another background declaration that just adds the top image to the top of the letter, as a fallback for browsers that don't support the previous declaration.
- Add a white background color to the letter.
- Add a 1mm top and bottom solid border to the letter, in a color that is in keeping with the rest of the color scheme.
### The logo
- To the {{htmlelement("Heading_Elements", "h1")}}, add the logo as a background image.
- Add a filter to the logo to give it a subtle drop shadow.
- Now comment out the filter and implement the drop shadow in a different (slightly more cross-browser compatible) way, which still follows the shape of the round image.
## Hints and tips
- Remember that you can create a fallback for older browsers by putting the fallback version of a declaration first, followed by the version that works across newer browsers only. Older browsers will apply the first declaration and ignore the second one, whereas newer browsers will apply the first one, then override it with the second one.
- Feel free to create your own graphics for the assessment if you wish.
## Example
The following screenshot shows an example of what the finished design could look like:

{{PreviousMenuNext("Learn/CSS/Building_blocks/Fundamental_CSS_comprehension", "Learn/CSS/Building_blocks/A_cool_looking_box", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/selectors/index.md | ---
title: CSS selectors
slug: Learn/CSS/Building_blocks/Selectors
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors", "Learn/CSS/Building_blocks")}}
In {{Glossary("CSS")}}, selectors are used to target the {{glossary("HTML")}} elements on our web pages that we want to style. There are a wide variety of CSS selectors available, allowing for fine-grained precision when selecting elements to style. In this article and its sub-articles we'll run through the different types in great detail, seeing how they work.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn how CSS selectors work in detail.</td>
</tr>
</tbody>
</table>
## What is a selector?
A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the _subject of the selector_.

In other articles you may have met some different selectors, and learned that there are selectors that target the document in different ways — for example by selecting an element such as `h1`, or a class such as `.special`.
In CSS, selectors are defined in the CSS Selectors specification; like any other part of CSS they need to have support in browsers for them to work. The majority of selectors that you will come across are defined in the [Level 3 Selectors specification](https://www.w3.org/TR/selectors-3/) and [Level 4 Selectors specification](https://www.w3.org/TR/selectors-4/), which are both mature specifications, therefore you will find excellent browser support for these selectors.
## Selector lists
If you have more than one thing which uses the same CSS then the individual selectors can be combined into a _selector list_ so that the rule is applied to all of the individual selectors. For example, if I have the same CSS for an `h1` and also a class of `.special`, I could write this as two separate rules.
```css
h1 {
color: blue;
}
.special {
color: blue;
}
```
I could also combine these into a selector list, by adding a comma between them.
```css-nolint
h1, .special {
color: blue;
}
```
White space is valid before or after the comma. You may also find the selectors more readable if each is on a new line.
```css
h1,
.special {
color: blue;
}
```
In the live example below try combining the two selectors which have identical declarations. The visual display should be the same after combining them.
{{EmbedGHLiveSample("css-examples/learn/selectors/selector-list.html", '100%', 1150)}}
When you group selectors in this way, if any selector is syntactically invalid, the whole rule will be ignored.
In the following example, the invalid class selector rule will be ignored, whereas the `h1` would still be styled.
```css-nolint
h1 {
color: blue;
}
..special {
color: blue;
}
```
When combined however, neither the `h1` nor the class will be styled as the entire rule is deemed invalid.
```css-nolint
h1, ..special {
color: blue;
}
```
## Types of selectors
There are a few different groupings of selectors, and knowing which type of selector you might need will help you to find the right tool for the job. In this article's subarticles we will look at the different groups of selectors in more detail.
### Type, class, and ID selectors
Type selectors target an HTML element such as an [`<h1>`](/en-US/docs/Web/HTML/Element/Heading_Elements):
```css
h1 {
}
```
Class selectors target an element that has a specific value for its [`class`](/en-US/docs/Web/HTML/Global_attributes/class) attribute:
```css
.box {
}
```
ID selectors target an element that has a specific value for its [`id`](/en-US/docs/Web/HTML/Global_attributes/id) attribute:
```css
#unique {
}
```
### Attribute selectors
This group of selectors gives you different ways to select elements based on the presence of a certain attribute on an element:
```css
a[title] {
}
```
Or even make a selection based on the presence of an attribute with a particular value:
```css
a[href="https://example.com"]
{
}
```
### Pseudo-classes and pseudo-elements
This group of selectors includes pseudo-classes, which style certain states of an element. The `:hover` pseudo-class for example selects an element only when it is being hovered over by the mouse pointer:
```css
a:hover {
}
```
It also includes pseudo-elements, which select a certain part of an element rather than the element itself. For example, `::first-line` always selects the first line of text inside an element (a `<p>` in the below case), acting as if a `<span>` was wrapped around the first formatted line and then selected.
```css
p::first-line {
}
```
### Combinators
The final group of selectors combine other selectors in order to target elements within our documents. The following, for example, selects paragraphs that are direct children of `<article>` elements using the child combinator (`>`):
```css
article > p {
}
```
## Summary
In this article we've introduced CSS selectors, which enable you to target particular HTML elements. Next, we'll take a closer look at [type, class, and ID selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors).
For a complete list of selectors, see our [CSS selectors reference](/en-US/docs/Web/CSS/CSS_selectors).
{{NextMenu("Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks/selectors | data/mdn-content/files/en-us/learn/css/building_blocks/selectors/combinators/index.md | ---
title: Combinators
slug: Learn/CSS/Building_blocks/Selectors/Combinators
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements", "Learn/CSS/Building_blocks/Cascade_and_inheritance", "Learn/CSS/Building_blocks")}}
The final selectors we will look at are called combinators, because they combine other selectors in a way that gives them a useful relationship to each other and the location of content in the document.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn about the different combinator selectors that can be used in
CSS.
</td>
</tr>
</tbody>
</table>
## Descendant combinator
The **descendant combinator** — typically represented by a single space (" ") character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc.) element matching the first selector. Selectors that utilize a descendant combinator are called _descendant selectors_.
```css
body article p
```
In the example below, we are matching only the `<p>` element which is inside an element with a class of `.box`.
{{EmbedGHLiveSample("css-examples/learn/selectors/descendant.html", '100%', 500)}}
## Child combinator
The **child combinator** (`>`) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Descendant elements further down the hierarchy don't match. For example, to select only `<p>` elements that are direct children of `<article>` elements:
```css
article > p
```
In this next example, we have an unordered list, nested inside of which is an ordered list. The child combinator selects only those `<li>` elements which are direct children of a `<ul>`, and styles them with a top border.
If you remove the `>` that designates this as a child combinator, you end up with a descendant selector and all `<li>` elements will get a red border.
{{EmbedGHLiveSample("css-examples/learn/selectors/child.html", '100%', 600)}}
## Next-sibling combinator
The **next-sibling combinator** (`+`) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the next sibling element of the first selector. For example, to select all `<img>` elements that are immediately preceded by a `<p>` element:
```css
p + img
```
A common use case is to do something with a paragraph that follows a heading, as in the example below. In that example, we are looking for any paragraph which shares a parent element with an `<h1>`, and immediately follows that `<h1>`.
If you insert some other element such as a `<h2>` in between the `<h1>` and the `<p>`, you will find that the paragraph is no longer matched by the selector and so does not get the background and foreground color applied when the element is adjacent.
<!-- This example lives https://github.com/mdn/css-examples/blob/main/learn/selectors/adjacent.html -->
{{EmbedGHLiveSample("css-examples/learn/selectors/adjacent.html", '100%', 800)}}
## Subsequent-sibling combinator
If you want to select siblings of an element even if they are not directly adjacent, then you can use the **subsequent-sibling combinator** (`~`). To select all `<img>` elements that come _anywhere_ after `<p>` elements, we'd do this:
```css
p ~ img
```
In the example below we are selecting all `<p>` elements that come after the `<h1>`, and even though there is a `<div>` in the document as well, the `<p>` that comes after it is selected.
<!-- This example lives https://github.com/mdn/css-examples/blob/main/learn/selectors/general.html -->
{{EmbedGHLiveSample("css-examples/learn/selectors/general.html", '100%', 600)}}
## Creating complex selectors with nesting
The [CSS nesting module](/en-US/docs/Web/CSS/CSS_nesting/Using_CSS_nesting#combinators) allows you to write nested rules that use combinators to create [complex selectors](/en-US/docs/Web/CSS/CSS_selectors/Selector_structure#complex_selector).
```css
p {
~ img {
}
}
/* This is parsed by the browser as */
p ~ img {
}
```
The [`&` nesting selector](/en-US/docs/Web/CSS/Nesting_selector) can also be used to create complex selectors.
```css
p {
& img {
}
}
/* This is parsed by the browser as */
p img {
}
```
<!-- This example lives https://github.com/mdn/css-examples/blob/main/learn/selectors/nesting.html -->
{{EmbedGHLiveSample("css-examples/learn/selectors/nesting.html", '100%', 800)}}
> **Note:** In the example above, the `&` nesting selector is not required, but adding it helps to explicitly show that CSS nesting is being used.
## Using combinators
You can combine any of the selectors that we discovered in previous lessons with combinators in order to pick out part of your document. For example, to select list items with a class of "a" which are direct children of a `<ul>`, try the following:
```css
ul > li[class="a"] {
}
```
Take care, however, when creating big lists of selectors that select very specific parts of your document. It will be hard to reuse the CSS rules since you have made the selector very specific to the location of that element in the markup.
It is often better to create a simple class and apply that to the element in question. That said, your knowledge of combinators will be very useful if you need to style something in your document and are unable to access the HTML, perhaps due to it being generated by a {{Glossary("CMS")}}.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Selectors_Tasks).
## Summary
This is the last section in our lessons on selectors. Next, we'll move on to another important part of CSS — the [cascade, specificity, and inheritance](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance).
{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements", "Learn/CSS/Building_blocks/Cascade_and_inheritance", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks/selectors | data/mdn-content/files/en-us/learn/css/building_blocks/selectors/attribute_selectors/index.md | ---
title: Attribute selectors
slug: Learn/CSS/Building_blocks/Selectors/Attribute_selectors
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors", "Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements", "Learn/CSS/Building_blocks")}}
As you know from your study of HTML, elements can have attributes that give further detail about the element being marked up. In CSS you can use attribute selectors to target elements with certain attributes. This lesson will show you how to use these very useful selectors.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn what attribute selectors are and how to use them.</td>
</tr>
</tbody>
</table>
## Presence and value selectors
These selectors enable the selection of an element based on the presence of an attribute alone (for example `href`), or on various different matches against the value of the attribute.
<table class="standard-table">
<thead>
<tr>
<th scope="col">Selector</th>
<th scope="col">Example</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>[<em>attr</em>]</code></td>
<td><code>a[title]</code></td>
<td>
Matches elements with an <em>attr</em> attribute (whose name is the
value in square brackets).
</td>
</tr>
<tr>
<td><code>[<em>attr</em>=<em>value</em>]</code></td>
<td><code>a[href="https://example.com"]</code></td>
<td>
Matches elements with an <em>attr</em> attribute whose value is exactly
<em>value</em> — the string inside the quotes.
</td>
</tr>
<tr>
<td><code>[<em>attr</em>~=<em>value</em>]</code></td>
<td><code>p[class~="special"]</code></td>
<td>
<p>
<br />Matches elements with an <em>attr</em> attribute whose value is
exactly <em>value</em>, or contains <em>value</em> in its (space
separated) list of values.
</p>
</td>
</tr>
<tr>
<td><code>[<em>attr</em>|=<em>value</em>]</code></td>
<td><code>div[lang|="zh"]</code></td>
<td>
Matches elements with an <em>attr</em> attribute whose value is exactly
<em>value</em> or begins with <em>value</em> immediately followed by a
hyphen.
</td>
</tr>
</tbody>
</table>
In the example below you can see these selectors being used.
- By using `li[class]` we can match any list item with a class attribute. This matches all of the list items except the first one.
- `li[class="a"]` matches a selector with a class of `a`, but not a selector with a class of `a` with another space-separated class as part of the value. It selects the second list item.
- `li[class~="a"]` will match a class of `a` but also a value that contains the class of `a` as part of a whitespace-separated list. It selects the second and third list items.
{{EmbedGHLiveSample("css-examples/learn/selectors/attribute.html", '100%', 800)}}
## Substring matching selectors
These selectors allow for more advanced matching of substrings inside the value of your attribute. For example, if you had classes of `box-warning` and `box-error` and wanted to match everything that started with the string "box-", you could use `[class^="box-"]` to select them both (or `[class|="box"]` as described in section above).
| Selector | Example | Description |
| --------------- | ------------------- | -------------------------------------------------------------------------------------------------- |
| `[attr^=value]` | `li[class^="box-"]` | Matches elements with an _attr_ attribute, whose value begins with _value_. |
| `[attr$=value]` | `li[class$="-box"]` | Matches elements with an _attr_ attribute whose value ends with _value_. |
| `[attr*=value]` | `li[class*="box"]` | Matches elements with an _attr_ attribute whose value contains _value_ anywhere within the string. |
(Aside: It may help to note that `^` and `$` have long been used as _anchors_ in so-called _regular expressions_ to mean _begins with_ and _ends with_ respectively.)
The next example shows usage of these selectors:
- `li[class^="a"]` matches any attribute value which starts with `a`, so matches the first two list items.
- `li[class$="a"]` matches any attribute value that ends with `a`, so matches the first and third list item.
- `li[class*="a"]` matches any attribute value where `a` appears anywhere in the string, so it matches all of our list items.
{{EmbedGHLiveSample("css-examples/learn/selectors/attribute-substring.html", '100%', 800)}}
## Case-sensitivity
If you want to match attribute values case-insensitively you can use the value `i` before the closing bracket. This flag tells the browser to match {{Glossary("ASCII")}} characters case-insensitively. Without the flag the values will be matched according to the case-sensitivity of the document language — in HTML's case it will be case sensitive.
In the example below, the first selector will match a value that begins with `a` — it only matches the first list item because the other two list items start with an uppercase A. The second selector uses the case-insensitive flag and so matches all of the list items.
{{EmbedGHLiveSample("css-examples/learn/selectors/attribute-case.html", '100%', 800)}}
> **Note:** There is also a newer value `s`, which will force case-sensitive matching in contexts where matching is normally case-insensitive, however this is less well supported in browsers and isn't very useful in an HTML context.
## Summary
Now that we are done with attribute selectors, you can continue on to the next article and read about [pseudo-class and pseudo-element selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements).
{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors", "Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks/selectors | data/mdn-content/files/en-us/learn/css/building_blocks/selectors/selectors_tasks/index.md | ---
title: "Test your skills: Selectors"
slug: Learn/CSS/Building_blocks/Selectors/Selectors_Tasks
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand [CSS selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors).
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Task 1
In this task, use CSS to do the following things, without changing the HTML:
- Make `<h1>` headings blue.
- Give `<h2>` headings a blue background and white text.
- Cause text wrapped in a `<span>` to have a font-size of 200%.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/selectors/type.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/selectors/type-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, we want you to make the following changes to the look of the content in this example, without changing the HTML:
- Give the element with an id of `special` a yellow background.
- Give the element with a class of `alert` a 1px grey border.
- If the element with a class of `alert` also has a class of `stop`, make the background red.
- If the element with a class of `alert` also has a class of `go`, make the background green.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/selectors/class-id.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/selectors/class-id-download.html) to work in your own editor or in an online editor.
## Task 3
In this task, we want you to make the following changes without adding to the HTML:
- Style links, making the link-state orange, visited links green, and remove the underline on hover.
- Make the first element inside the container font-size: 150% and the first line of that element red.
- Stripe every other row in the table by selecting these rows and giving them a background color of #333 and foreground of white.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/selectors/pseudo.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/selectors/pseudo-download.html) to work in your own editor or in an online editor.
## Task 4
In this task, we want you to do the following:
- Make any paragraph that directly follows an `<h2>` element red.
- Remove the bullets and add a 1px grey bottom border only to list items that are a direct child of the ul with a class of `list`.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/selectors/combinators.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/selectors/combinators-download.html) to work in your own editor or in an online editor.
## Task 5
In this task, add CSS using attribute selectors to do the following:
- Target the `<a>` element with a `title` attribute and make the border pink (`border-color: pink`).
- Target the `<a>` element with an `href` attribute that contains the word `contact` somewhere in its value and make the border orange (`border-color: orange`).
- Target the `<a>` element with an `href` value starting with `https` and give it a green border (`border-color: green`).
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/selectors/attribute-links.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/selectors/attribute-links-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks/selectors | data/mdn-content/files/en-us/learn/css/building_blocks/selectors/type_class_and_id_selectors/index.md | ---
title: Type, class, and ID selectors
slug: Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors", "Learn/CSS/Building_blocks/Selectors/Attribute_selectors", "Learn/CSS/Building_blocks")}}
In this lesson, we examine some of the simplest selectors, which you will probably use most frequently in your work.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn about the different CSS selectors we can use to apply CSS to a
document.
</td>
</tr>
</tbody>
</table>
## Type selectors
A **type selector** is sometimes referred to as a _tag name selector_ or _element selector_ because it selects an HTML tag/element in your document. Type selectors are not case-sensitive. In the example below, we have used the `span`, `em` and `strong` selectors.
**Try adding a CSS rule to select the `<h1>` element and change its color to blue.**
{{EmbedGHLiveSample("css-examples/learn/selectors/type.html", '100%', 1100)}}
## The universal selector
The universal selector is indicated by an asterisk (`*`). It selects everything in the document (or inside the parent element if it is being chained together with another element and a descendant combinator). In the following example, we use the universal selector to remove the margins on all elements. Instead of the default styling added by the browser — which spaces out headings and paragraphs with margins — everything is close together.
{{EmbedGHLiveSample("css-examples/learn/selectors/universal.html", '100%', 750)}}
This kind of behavior can sometimes be seen in "reset stylesheets", which strip out all of the browser styling. Since the universal selector makes global changes, we use it for very specific situations, such as the one described below.
### Using the universal selector to make your selectors easier to read
One use of the universal selector is to make selectors easier to read and more obvious in terms of what they are doing. For example, if we wanted to select any descendant elements of an `<article>` element that are the first child of their parent, including direct children, and make them bold, we could use the {{cssxref(":first-child")}} pseudo-class. We will learn more about this in the lesson on [pseudo-classes and pseudo-elements](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements), as a descendant selector along with the `<article>` element selector:
```css
article :first-child {
font-weight: bold;
}
```
However, this selector could be confused with `article:first-child`, which will select any `<article>` element that is the first child of another element.
To avoid this confusion, we can add the universal selector to the `:first-child` pseudo-class, so it is more obvious what the selector is doing. It is selecting _any_ element which is the first-child of an `<article>` element, or the first-child of any descendant element of `<article>`:
```css
article *:first-child {
font-weight: bold;
}
```
Although both do the same thing, the readability is significantly improved.
## Class selectors
The case-sensitive class selector starts with a dot (`.`) character. It will select everything in the document with that class applied to it. In the live example below we have created a class called `highlight`, and have applied it to several places in my document. All of the elements that have the class applied are highlighted.
{{EmbedGHLiveSample("css-examples/learn/selectors/class.html", '100%', 750)}}
### Targeting classes on particular elements
You can create a selector that will target specific elements with the class applied. In this next example, we will highlight a `<span>` with a class of `highlight` differently to an `<h1>` heading with a class of `highlight`. We do this by using the type selector for the element we want to target, with the class appended using a dot, with no white space in between.
{{EmbedGHLiveSample("css-examples/learn/selectors/class-type.html", '100%', 750)}}
This approach reduces the scope of a rule. The rule will only apply to that particular element and class combination. You would need to add another selector if you decided the rule should apply to other elements too.
### Target an element if it has more than one class applied
You can apply multiple classes to an element and target them individually, or only select the element when all of the classes in the selector are present. This can be helpful when building up components that can be combined in different ways on your site.
In the example below, we have a `<div>` that contains a note. The grey border is applied when the box has a class of `notebox`. If it also has a class of `warning` or `danger`, we change the {{cssxref("border-color")}}.
We can tell the browser that we only want to match the element if it has two classes applied by chaining them together with no white space between them. You'll see that the last `<div>` doesn't get any styling applied, as it only has the `danger` class; it needs `notebox` as well to get anything applied.
{{EmbedGHLiveSample("css-examples/learn/selectors/class-many.html", '100%', 900)}}
## ID selectors
The case-sensitive ID selector begins with a `#` rather than a dot character, but is used in the same way as a class selector. However, an ID can be used only once per page, and elements can only have a single `id` value applied to them. It can select an element that has the `id` set on it, and you can precede the ID with a type selector to only target the element if both the element and ID match. You can see both of these uses in the following example:
{{EmbedGHLiveSample("css-examples/learn/selectors/id.html", '100%', 750)}}
> **Warning:** Using the same ID multiple times in a document may appear to work for styling purposes, but don't do this. It results in invalid code, and will cause strange behavior in many places.
> **Note:** The ID selector has high {{cssxref("specificity")}}. This means styles applied based on matching an ID selector will overrule styles applied based on other selector, including class and type selectors. Because an ID can only occur once on a page and because of the high specificity of ID selectors, it is preferable to add a class to an element instead of an ID. If using the ID is the only way to target the element — perhaps because you do not have access to the markup and cannot edit it — consider using the ID within an [attribute selector](/en-US/docs/Web/CSS/Attribute_selectors), such as `p[id="header"]`. [Learn specificity](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance).
## Summary
That wraps up Type, class, and ID selectors. We'll continue exploring selectors by looking at [attribute selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Attribute_selectors).
{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors", "Learn/CSS/Building_blocks/Selectors/Attribute_selectors", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks/selectors | data/mdn-content/files/en-us/learn/css/building_blocks/selectors/pseudo-classes_and_pseudo-elements/index.md | ---
title: Pseudo-classes and pseudo-elements
slug: Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Attribute_selectors", "Learn/CSS/Building_blocks/Selectors/Combinators", "Learn/CSS/Building_blocks")}}
The next set of selectors we will look at are referred to as **pseudo-classes** and **pseudo-elements**. There are a large number of these, and they often serve quite specific purposes. Once you know how to use them, you can look at the list to see if there is something which works for the task you are trying to achieve. Once again the relevant MDN page for each selector is helpful in explaining browser support.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>).
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn about the pseudo-class and pseudo-element selectors.</td>
</tr>
</tbody>
</table>
## What is a pseudo-class?
A pseudo-class is a selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer. They tend to act as if you had applied a class to some part of your document, often helping you cut down on excess classes in your markup, and giving you more flexible, maintainable code.
Pseudo-classes are keywords that start with a colon. For example, `:hover` is a pseudo-class.
### Simple pseudo-class example
Let's look at a simple example. If we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add CSS to that class, as shown in the first example below:
{{EmbedGHLiveSample("css-examples/learn/selectors/first-child.html", '100%', 800)}}
However, this could be annoying to maintain — what if a new paragraph got added to the top of the document? We'd need to move the class over to the new paragraph. Instead of adding the class, we could use the {{cssxref(":first-child")}} pseudo-class selector — this will _always_ target the first child element in the article, and we will no longer need to edit the HTML (this may not always be possible anyway, maybe due to it being generated by a CMS).
{{EmbedGHLiveSample("css-examples/learn/selectors/first-child2.html", '100%', 700)}}
All pseudo-classes behave in this same kind of way. They target some bit of your document that is in a certain state, behaving as if you had added a class into your HTML. Take a look at some other examples on MDN:
- [`:last-child`](/en-US/docs/Web/CSS/:last-child)
- [`:only-child`](/en-US/docs/Web/CSS/:only-child)
- [`:invalid`](/en-US/docs/Web/CSS/:invalid)
> **Note:** It is valid to write pseudo-classes and elements without any element selector preceding them. In the example above, you could write `:first-child` and the rule would apply to _any_ element that is the first child of an `<article>` element, not just a paragraph first child — `:first-child` is equivalent to `*:first-child`. However, usually you want more control than that, so you need to be more specific.
### User-action pseudo classes
Some pseudo-classes only apply when the user interacts with the document in some way. These **user-action** pseudo-classes, sometimes referred to as **dynamic pseudo-classes**, act as if a class had been added to the element when the user interacts with it. Examples include:
- [`:hover`](/en-US/docs/Web/CSS/:hover) — mentioned above; this only applies if the user moves their pointer over an element, typically a link.
- [`:focus`](/en-US/docs/Web/CSS/:focus) — only applies if the user focuses the element by clicking or using keyboard controls.
{{EmbedGHLiveSample("css-examples/learn/selectors/hover.html", '100%', 500)}}
## What is a pseudo-element?
Pseudo-elements behave in a similar way. However, they act as if you had added a whole new HTML element into the markup, rather than applying a class to existing elements.
Pseudo-elements start with a double colon `::`. `::before` is an example of a pseudo-element.
> **Note:** Some early pseudo-elements used the single colon syntax, so you may sometimes see this in code or examples. Modern browsers support the early pseudo-elements with single- or double-colon syntax for backwards compatibility.
For example, if you wanted to select the first line of a paragraph you could wrap it in a `<span>` element and use an element selector; however, that would fail if the number of words you had wrapped were longer or shorter than the parent element's width. As we tend not to know how many words will fit on a line — as that will change if the screen width or font-size changes — it is impossible to robustly do this by adding HTML.
The `::first-line` pseudo-element selector will do this for you reliably — if the number of words increases or decreases it will still only select the first line.
{{EmbedGHLiveSample("css-examples/learn/selectors/first-line.html", '100%', 800)}}
It acts as if a `<span>` was magically wrapped around that first formatted line, and updated each time the line length changed.
You can see that this selects the first line of both paragraphs.
## Combining pseudo-classes and pseudo-elements
If you wanted to make the first line of the first paragraph bold you could chain the `:first-child` and `::first-line` selectors together. Try editing the previous live example so it uses the following CSS. We are saying that we want to select the first line, of the first `<p>` element, which is inside an `<article>` element.
```css
article p:first-child::first-line {
font-size: 120%;
font-weight: bold;
}
```
## Generating content with ::before and ::after
There are a couple of special pseudo-elements, which are used along with the [`content`](/en-US/docs/Web/CSS/content) property to insert content into your document using CSS.
You could use these to insert a string of text, such as in the live example below. Try changing the text value of the {{cssxref("content")}} property and see it change in the output. You could also change the `::before` pseudo-element to `::after` and see the text inserted at the end of the element instead of the beginning.
{{EmbedGHLiveSample("css-examples/learn/selectors/before.html", '100%', 400)}}
Inserting strings of text from CSS isn't really something we do very often on the web however, as that text is inaccessible to some screen readers and might be hard for someone to find and edit in the future.
A more valid use of these pseudo-elements is to insert an icon, for example the little arrow added in the example below, which is a visual indicator that we wouldn't want read out by a screen reader:
{{EmbedGHLiveSample("css-examples/learn/selectors/after-icon.html", '100%', 400)}}
These pseudo-elements are also frequently used to insert an empty string, which can then be styled just like any element on the page.
In this next example, we have added an empty string using the `::before` pseudo-element. We have set this to `display: block` in order that we can style it with a width and height. We then use CSS to style it just like any element. You can play around with the CSS and change how it looks and behaves.
{{EmbedGHLiveSample("css-examples/learn/selectors/before-styled.html", '100%', 500)}}
The use of the `::before` and `::after` pseudo-elements along with the `content` property is referred to as "Generated Content" in CSS, and you will often see this technique being used for various tasks. A great example is the site [CSS Arrow Please](https://cssarrowplease.com/), which helps you to generate an arrow with CSS. Look at the CSS as you create your arrow and you will see the {{cssxref("::before")}} and {{cssxref("::after")}} pseudo-elements in use. Whenever you see these selectors, look at the {{cssxref("content")}} property to see what is being added to the HTML element.
## Summary
In this article we've introduced CSS pseudo-classes and pseudo-elements, which are special types of selectors.
Pseudo-classes enable you to target an element when it's in a particular state, as if you had added a class for that state to the DOM. Pseudo-elements act as if you had added a whole new element to the DOM, and enable you to style that. The `::before` and `::after` pseudo-elements enable you to insert content into the document using CSS.
In the next article, we'll learn about [combinators](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Combinators).
## See also
- [Pseudo-classes reference](/en-US/docs/Web/CSS/Pseudo-classes)
- [Pseudo-elements reference](/en-US/docs/Web/CSS/Pseudo-elements)
{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Attribute_selectors", "Learn/CSS/Building_blocks/Selectors/Combinators", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/tables_tasks/index.md | ---
title: "Test your skills: Tables"
slug: Learn/CSS/Building_blocks/Tables_tasks
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand how to [style HTML tables in CSS](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables).
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Task
In the lesson on [styling tables](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables) we styled up a table in a rather garish manner. In this task, we are going to style the same table, but using some good practices for table design as outlined in the external article [Web Typography: designing tables to be read not looked at](https://alistapart.com/article/web-typography-tables/).
Our finished table will look like the image below. There are a number of ways that you can achieve this, but we suggest you follow similar patterns as used in the tutorial to do the following things:
- Add padding of `0.3em` to the table headings and data and align them at the top of their cells.
- Align headings and data for columns containing numbers right.
- Align headings and data for columns containing text left.
- Add a 1px top and bottom solid border with the hex color `#999`, plus a 1px solid border of the same color above the footer.
- Remove the default spacing between the table elements borders to get the expected result.
- Stripe every odd row of the main table with the hex color `#eee`.

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/tables/table.html", '100%', 1000)}}
Additional question:
- What can you do to make the table layout behave a bit more predictably? Think of how table columns are sized by default and how we can change this behavior to size the columns according to the width of their headings.
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/tables/table-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/styling_tables/index.md | ---
title: Styling tables
slug: Learn/CSS/Building_blocks/Styling_tables
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Images_media_form_elements", "Learn/CSS/Building_blocks/Debugging_CSS", "Learn/CSS/Building_blocks")}}
Styling an HTML table isn't the most glamorous job in the world, but sometimes we all have to do it. This article provides a guide to making HTML tables look good, with some specific table styling techniques highlighted.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), knowledge of
<a href="/en-US/docs/Learn/HTML/Tables">HTML tables</a>, and an idea of
how CSS works (study CSS first steps.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn how to effectively style HTML tables.</td>
</tr>
</tbody>
</table>
## A typical HTML table
Let's start by looking at a typical HTML table. Well, I say typical — most HTML table examples are about shoes, or the weather, or employees; we decided to make things more interesting by making it about famous punk bands from the UK. The markup looks like so:
```html
<table>
<caption>
A summary of the UK's most famous punk bands
</caption>
<thead>
<tr>
<th scope="col">Band</th>
<th scope="col">Year formed</th>
<th scope="col">No. of Albums</th>
<th scope="col">Most famous song</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Buzzcocks</th>
<td>1976</td>
<td>9</td>
<td>Ever fallen in love (with someone you shouldn't've)</td>
</tr>
<tr>
<th scope="row">The Clash</th>
<td>1976</td>
<td>6</td>
<td>London Calling</td>
</tr>
<!-- several other great bands -->
<tr>
<th scope="row">The Stranglers</th>
<td>1974</td>
<td>17</td>
<td>No More Heroes</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row" colspan="2">Total albums</th>
<td colspan="2">77</td>
</tr>
</tfoot>
</table>
```
The table is nicely marked up, easily stylable, and accessible, thanks to features such as [`scope`](/en-US/docs/Web/HTML/Element/th#scope), {{htmlelement("caption")}}, {{htmlelement("thead")}}, {{htmlelement("tbody")}}, etc. Unfortunately, it doesn't look good when rendered on the screen (see it live at [punk-bands-unstyled.html](https://mdn.github.io/learning-area/css/styling-boxes/styling-tables/punk-bands-unstyled.html)):

With only the default browser styling it looks cramped, hard to read, and boring. We need to use some CSS to fix this up.
## Styling our table
Let's work through styling our table example together.
1. To start with, make a local copy of the [sample markup](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/styling-tables/punk-bands-unstyled.html), download both images ([noise](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/styling-tables/noise.png) and [leopardskin](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/styling-tables/leopardskin.jpg)), and put the three resulting files in a working directory somewhere on your local computer.
2. Next, create a new file called `style.css` and save it in the same directory as your other files.
3. Link the CSS to the HTML by placing the following line of HTML inside your {{htmlelement("head")}}:
```html
<link href="style.css" rel="stylesheet" />
```
### Spacing and layout
The first thing we need to do is sort out the spacing/layout — default table styling is so cramped! To do this, add the following CSS to your `style.css` file:
```css
/* spacing */
table {
table-layout: fixed;
width: 100%;
border-collapse: collapse;
border: 3px solid purple;
}
thead th:nth-child(1) {
width: 30%;
}
thead th:nth-child(2) {
width: 20%;
}
thead th:nth-child(3) {
width: 15%;
}
thead th:nth-child(4) {
width: 35%;
}
th,
td {
padding: 20px;
}
```
The most important parts to note are as follows:
- A {{cssxref("table-layout")}} value of `fixed` is generally a good idea to set on your table, as it makes the table behave a bit more predictably by default. Normally, table columns tend to be sized according to how much content they contain, which produces some strange results. With `table-layout: fixed`, you can size your columns according to the width of their headings, and then deal with their content as appropriate. This is why we've selected the four different headings with the `thead th:nth-child(n)` ({{cssxref(":nth-child")}}) selector ("Select the n-th child that is a {{htmlelement("th")}} element in a sequence, inside a {{htmlelement("thead")}} element") and given them set percentage widths. The entire column width follows the width of its heading, making for a nice way to size your table columns. Chris Coyier discusses this technique in more detail in [Fixed Table Layouts](https://css-tricks.com/fixing-tables-long-strings/).
We've coupled this with a {{cssxref("width")}} of 100%, meaning that the table will fill any container it is put in, and be nicely responsive (although it would still need some more work to get it looking good on narrow screen widths).
- A {{cssxref("border-collapse")}} value of `collapse` is standard best practice for any table styling effort. By default, when you set borders on table elements, they will all have spacing between them, as the below image illustrates:  This doesn't look very nice (although it might be the look you want, who knows?). With `border-collapse: collapse;` set, the borders collapse down into one, which looks much better: 
- We've put a {{cssxref("border")}} around the whole table, which is needed because we'll be putting some borders around the table header and footer later on — it looks really odd and disjointed when you don't have a border around the whole outside of the table and end up with gaps.
- We've set some {{cssxref("padding")}} on the {{htmlelement("th")}} and {{htmlelement("td")}} elements — this gives the data items some space to breathe, making the table look a lot more legible.
At this point, our table already looks a lot better:

### Some simple typography
Now we'll get our text sorted out a bit.
First of all, we've found a font on [Google Fonts](https://fonts.google.com/) that is suitable for a table about punk bands. You can go there and find a different one if you like; you'll just have to replace our provided {{htmlelement("link")}} element and custom {{cssxref("font-family")}} declaration with the ones Google Fonts gives you.
First, add the following {{htmlelement("link")}} element into your HTML head, just above your existing `<link>` element:
```html
<link
href="https://fonts.googleapis.com/css?family=Rock+Salt"
rel="stylesheet"
type="text/css" />
```
Now add the following CSS into your `style.css` file, below the previous addition:
```css
/* typography */
html {
font-family: "helvetica neue", helvetica, arial, sans-serif;
}
thead th,
tfoot th {
font-family: "Rock Salt", cursive;
}
th {
letter-spacing: 2px;
}
td {
letter-spacing: 1px;
}
tbody td {
text-align: center;
}
tfoot th {
text-align: right;
}
```
There is nothing really specific to tables here; we are generally tweaking the font styling to make things easier to read:
- We have set a global sans-serif font stack; this is purely a stylistic choice. We've also set our custom font on the headings inside the {{htmlelement("thead")}} and {{htmlelement("tfoot")}} elements, for a nice grungy, punky look.
- We've set some {{cssxref("letter-spacing")}} on the headings and cells, as we feel it aids readability. Again, mostly a stylistic choice.
- We've center-aligned the text in the table cells inside the {{htmlelement("tbody")}} so that they line up with the headings. By default, cells are given a {{cssxref("text-align")}} value of `left`, and headings are given a value of `center`, but generally it looks better to have the alignments set the same for both. The default bold weight on the heading fonts is enough to differentiate their look.
- We've right-aligned the heading inside the {{htmlelement("tfoot")}} so that it is visually associated better with its data point.
The result looks a bit neater:

### Graphics and colors
Now onto graphics and colors! Because the table is full of punk and attitude, we need to give it some bright imposing styling to suit it. Don't worry, you don't have to make your tables this loud — you can opt for something more subtle and tasteful.
Start by adding the following CSS to your `style.css` file, again at the bottom:
```css
/* graphics and colors */
thead,
tfoot {
background: url(leopardskin.jpg);
color: white;
text-shadow: 1px 1px 1px black;
}
thead th,
tfoot th,
tfoot td {
background: linear-gradient(to bottom, rgb(0 0 0 / 10%), rgb(0 0 0 / 50%));
border: 3px solid purple;
}
```
Again, there's nothing specific to tables here, but it is worthwhile to note a few things.
We've added a {{cssxref("background-image")}} to the {{htmlelement("thead")}} and {{htmlelement("tfoot")}}, and changed the {{cssxref("color")}} of all the text inside the header and footer to white (and given it a {{cssxref("text-shadow")}}) so it is readable. You should always make sure your text contrasts well with your background, so it is readable.
We've also added a linear gradient to the {{htmlelement("th")}} and {{htmlelement("td")}} elements inside the header and footer for a nice bit of texture, as well as giving those elements a bright purple border. It is useful to have multiple nested elements available so you can layer styles on top of one another. Yes, we could have put both the background image and the linear gradient on the {{htmlelement("thead")}} and {{htmlelement("tfoot")}} elements using multiple background images, but we decided to do it separately for the benefit of older browsers that don't support multiple background images or linear gradients.
#### Zebra striping
We wanted to dedicate a separate section to showing you how to implement **zebra stripes** — alternating rows of color that make the different data rows in your table easier to parse and read. Add the following CSS to the bottom of your `style.css` file:
```css
/* zebra striping */
tbody tr:nth-child(odd) {
background-color: #ff33cc;
}
tbody tr:nth-child(even) {
background-color: #e495e4;
}
tbody tr {
background-image: url(noise.png);
}
table {
background-color: #ff33cc;
}
```
- Earlier on you saw the {{cssxref(":nth-child")}} selector being used to select specific child elements. It can also be given a formula as a parameter, so it will select a sequence of elements. The formula `2n+1` would select all the odd numbered children (1, 3, 5, etc.) and the formula `2n` would select all the even numbered children (2, 4, 6, etc.) We've used the `odd` and `even` keywords in our code, which do exactly the same things as the aforementioned formulae. In this case we are giving the odd and even rows different (lurid) colors.
- We've also added a repeating background tile to all the body rows, which is just a bit of noise (a semi-transparent `.png` with a bit of visual distortion on it) to provide some texture.
- Lastly, we've given the entire table a solid background color so that browsers that don't support the `:nth-child` selector still have a background for their body rows.
This color explosion results in the following look:

Now, this may be a bit over the top and not to your taste, but the point we are trying to make here is that tables don't have to be boring and academic.
### Styling the caption
There is one last thing to do with our table — style the caption. To do this, add the following to the bottom of your `style.css` file:
```css
/* caption */
caption {
font-family: "Rock Salt", cursive;
padding: 20px;
font-style: italic;
caption-side: bottom;
color: #666;
text-align: right;
letter-spacing: 1px;
}
```
There is nothing remarkable here, except for the {{cssxref("caption-side")}} property, which has been given a value of `bottom`. This causes the caption to be positioned on the bottom of the table, which along with the other declarations gives us this final look (see it live at [punk-bands-complete.html](https://mdn.github.io/learning-area/css/styling-boxes/styling-tables/punk-bands-complete.html)):

## Table styling quick tips
Before moving on, we thought we'd provide you with a quick list of the most useful points illustrated above:
- Make your table markup as simple as possible, and keep things flexible, e.g. by using percentages, so the design is more responsive.
- Use {{cssxref("table-layout")}}`: fixed` to create a more predictable table layout that allows you to easily set column widths by setting {{cssxref("width")}} on their headings ({{htmlelement("th")}}).
- Use {{cssxref("border-collapse")}}`: collapse` to make table elements borders collapse into each other, producing a neater and easier to control look.
- Use {{htmlelement("thead")}}, {{htmlelement("tbody")}}, and {{htmlelement("tfoot")}} to break up your table into logical chunks and provide extra places to apply CSS to, so it is easier to layer styles on top of one another if required.
- Use zebra striping to make alternative rows easier to read.
- Use {{cssxref("text-align")}} to line up your {{htmlelement("th")}} and {{htmlelement("td")}} text, to make things neater and easier to follow.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Tables](/en-US/docs/Learn/CSS/Building_blocks/Tables_tasks).
## Summary
With styling tables now behind us, we need something else to occupy our time. The next article explores [debugging CSS](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS) — how to solve problems such as layouts not looking like they should, or properties not applying when you think they should. This includes information on using browser DevTools to find solutions to your problems.
{{PreviousMenuNext("Learn/CSS/Building_blocks/Images_media_form_elements", "Learn/CSS/Building_blocks/Debugging_CSS", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/fundamental_css_comprehension/index.md | ---
title: Fundamental CSS comprehension
slug: Learn/CSS/Building_blocks/Fundamental_CSS_comprehension
page-type: learn-module-assessment
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/CSS/Building_blocks/Organizing", "Learn/CSS/Building_blocks/Creating_fancy_letterheaded_paper", "Learn/CSS/Building_blocks")}}
You've covered a lot in this module, so it must feel good to have reached the end! The final step before you move on is to attempt the assessment for the module — this involves a number of related exercises that must be completed in order to create the final design — a business card/gamer card/social media profile.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Before attempting this assessment you should have already worked through
all the articles in this module.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To test comprehension of fundamental CSS theory, syntax and mechanics.
</td>
</tr>
</tbody>
</table>
## Starting point
To get this assessment started, you should:
- Go and grab the [HTML file for the exercise](https://github.com/mdn/learning-area/blob/main/css/introduction-to-css/fundamental-css-comprehension/index.html), and the [associated image file](https://github.com/mdn/learning-area/blob/main/css/introduction-to-css/fundamental-css-comprehension/chris.jpg), and save them in a new directory on your local computer. If you want to use your own image file and fill your own name in, you are welcome to — just make sure the image is square.
- Grab the [CSS resources text file](https://github.com/mdn/learning-area/blob/main/css/introduction-to-css/fundamental-css-comprehension/style-resources.txt) — this contains a set of raw selectors and rulesets that you'll need to study and combine to answer part of this assessment.
Alternatively, you could use an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
You could paste the HTML and fill in the CSS into one of these online editors, and use [this URL](https://mdn.github.io/learning-area/css/introduction-to-css/fundamental-css-comprehension/chris.jpg) to point the `<img>` element to the image file.
> **Note:** If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Project brief
You have been provided with some raw HTML and an image, and need to write the necessary CSS to style this into a nifty little online business card, which can perhaps double as a gamer card or social media profile. The following sections describe what you need to do.
Basic setup:
- First of all, create a new file in the same directory as your HTML and image files. Call it something really imaginative like `style.css`.
- Link your CSS to your HTML file via a `<link>` element.
- The first two rulesets in the CSS resource file are yours, for FREE! After you've finished rejoicing at your good fortune, copy and paste them into the top of your new CSS file. Use them as a test to make sure your CSS is properly applied to your HTML.
- Above the two rules, add a CSS comment with some text inside it to indicate that this is a set of general styles for the overall page. "General page styles" would do. Also add three more comments at the bottom of the CSS file to indicate styles specific to the setup of the card container, styles specific to the header and footer, and styles specific to the main business card contents. From now on, subsequent styles added to the stylesheet should be organized in an appropriate place.
Taking care of the selectors and rulesets provided in the CSS resource file:
- Next up, we'd like you to look at the four selectors, and calculate the specificity for each one. Write these down somewhere where they can be found later on, such as in a comment at the top of your CSS.
- Now it's time to put the right selector on the right rule set! You've got four pairs of selector and ruleset to match in your CSS resources. Do this now, and add them to your CSS file. You need to:
- Give the main card container a fixed width/height, solid background color, border, and border-radius (rounded corners!), amongst other things.
- Give the header a background gradient that goes from darker to lighter, plus rounded corners that fit in with the rounded corners set on the main card container.
- Give the footer a background gradient that goes from lighter to darker, plus rounded corners that fit in with the rounded corners set on the main card container.
- [Float](/en-US/docs/Learn/CSS/CSS_layout/Floats) the image to the right so that it sticks to the right-hand side of the main business card contents, and give it a max-height of 100% (a clever trick that ensures that it will grow/shrink to stay the same height as its parent container, regardless of what height it becomes.)
- Beware! There are two errors in the provided rulesets. Using any technique that you know, track these down and fix them before moving on.
New rulesets you need to write:
- Write a ruleset that targets both the card header, and card footer, giving them both a computed total height of 50px (including a content height of 30px and padding of 10px on all sides.) But express it in `em`s.
- The default margin applied to the `<h2>` and `<p>` elements by the browser will interfere with our design, so write a rule that targets all these elements and sets their margin to 0.
- To stop the image from spilling out of the main business card content (the `<article>` element), we need to give it a specific height. Set the `<article>`'s height to 120px, but expressed in `em`s. Also give it a background color of semi-transparent black, resulting in a slightly darker shade that lets the background red color shine through a bit too.
- Write a ruleset that gives the `<h2>` an effective font size of 20px (but expressed in `em`s) and an appropriate line height to place it in the center of the header's content box. Recall from earlier that the content box height should be 30px — this gives you all the numbers you need to calculate the line height.
- Write a ruleset that gives the `<p>` inside the footer an effective font size of 15px (but expressed in `em`s) and an appropriate line height to place it in the center of the footer's content box. Recall from earlier that the content box height should be 30px — this gives you all the numbers you need to calculate the line height.
- As a last little touch, give the paragraph inside the `<article>` an appropriate padding value so that its left edge lines up with the `<h2>` and footer paragraph, and set its color to be fairly light so it is easy to read.
> **Note:** Bear in mind that the second ruleset sets `font-size: 10px;` on the `<html>` element — this means that for any descendants of `<html>`, an em will be equal to 10px rather than 16px as it is by default. (This is of course, provided the descendants in question don't have any ancestors sitting in between them and `<html>` in the hierarchy that have a different `font-size` set on them. This could affect the values you need, although in this simple example this is not an issue.)
Other things to think about:
- You'll get bonus marks if you write your CSS for maximum readability, with a separate declaration on each line.
- You should include `.card` at the start of the selector chain in all your rules, so that these rules wouldn't interfere with the styling of any other elements if the business card were to be put on a page with a load of other content.
## Hints and tips
- You don't need to edit the HTML in any way, except to apply the CSS to your HTML.
- When trying to work out the `em` value you need to represent a certain pixel length, think about what base font size the root (`<html>`) element has, and what it needs to be multiplied by to get the desired value. That'll give you your em value, at least in a simple case like this.
## Example
The following screenshot shows an example of what the finished design should look like:

{{PreviousMenuNext("Learn/CSS/Building_blocks/Organizing", "Learn/CSS/Building_blocks/Creating_fancy_letterheaded_paper", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/advanced_styling_effects/index.md | ---
title: Advanced styling effects
slug: Learn/CSS/Building_blocks/Advanced_styling_effects
page-type: guide
---
{{LearnSidebar}}
This article acts as a box of tricks, providing an introduction to some interesting advanced styling features such as box shadows, blend modes, and filters.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>) and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To get an idea about how to use some of the advanced styling effects
available in modern browsers.
</td>
</tr>
</tbody>
</table>
## Box shadows
{{cssxref("box-shadow")}} allows you to apply one or more drop shadows to an element's box. Like text shadows, box shadows are supported pretty well across browsers, including IE9+ and Edge. Users of older IE versions might just have to cope with no shadows, so just test your designs to make sure your content is legible without them.
You can find the examples in this section at [box-shadow.html](https://mdn.github.io/learning-area/css/styling-boxes/advanced_box_effects/box-shadow.html) (see the [source code](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/advanced_box_effects/box-shadow.html) too).
### A simple box shadow
Let's look at a simple example to get things started. First, some HTML:
```html
<article class="simple">
<p>
<strong>Warning</strong>: The thermostat on the cosmic transcender has
reached a critical level.
</p>
</article>
```
Now the CSS:
```css
p {
margin: 0;
}
article {
max-width: 500px;
padding: 10px;
background-color: red;
background-image: linear-gradient(
to bottom,
rgb(0 0 0 / 0%),
rgb(0 0 0 / 25%)
);
}
.simple {
box-shadow: 5px 5px 5px rgb(0 0 0 / 70%);
}
```
This gives us the following result:
{{ EmbedLiveSample('A_simple_box_shadow', '100%', 100) }}
You'll see that we've got four items in the `box-shadow` property value:
1. The first length value is the **horizontal offset** — the distance to the right the shadow is offset from the original box (or left, if the value is negative).
2. The second length value is the **vertical offset** — the distance downwards that the shadow is offset from the original box (or upwards, if the value is negative).
3. The third length value is the **blur radius** — the amount of blurring applied to the shadow.
4. The color value is the **base color** of the shadow.
You can use any length and color units that would make sense to do so to define these values.
### Multiple box shadows
You can also specify multiple box shadows in a single `box-shadow` declaration, by separating them with commas:
```html hidden
<article class="multiple">
<p>
<strong>Warning</strong>: The thermostat on the cosmic transcender has
reached a critical level.
</p>
</article>
```
```css-nolint
p {
margin: 0;
}
article {
max-width: 500px;
padding: 10px;
background-color: red;
background-image: linear-gradient(
to bottom,
rgb(0 0 0 / 0%),
rgb(0 0 0 / 25%)
);
}
.multiple {
box-shadow: 1px 1px 1px black,
2px 2px 1px black,
3px 3px 1px red,
4px 4px 1px red,
5px 5px 1px black,
6px 6px 1px black;
}
```
Now we get this result:
{{ EmbedLiveSample('Multiple_box_shadows', '100%', 100) }}
We've done something fun here by creating a raised box with multiple colored layers, but you could use it in any way you want, for example to create a more realistic look with shadows based on multiple light sources.
### Other box shadow features
Unlike {{cssxref("text-shadow")}}, {{cssxref("box-shadow")}} has an `inset` keyword available — putting this at the start of a shadow declaration causes it to become an inner shadow, rather than an outer shadow. Let's have a look and see what we mean.
First, we'll go with some different HTML for this example:
```html
<button>Press me!</button>
```
```css
button {
width: 150px;
font-size: 1.1rem;
line-height: 2;
border-radius: 10px;
border: none;
background-image: linear-gradient(to bottom right, #777, #ddd);
box-shadow:
1px 1px 1px black,
inset 2px 3px 5px rgb(0 0 0 / 30%),
inset -2px -3px 5px rgb(255 255 255 / 50%);
}
button:focus,
button:hover {
background-image: linear-gradient(to bottom right, #888, #eee);
}
button:active {
box-shadow:
inset 2px 2px 1px black,
inset 2px 3px 5px rgb(0 0 0 / 30%),
inset -2px -3px 5px rgb(255 255 255 / 50%);
}
```
This gives us the following result:
{{ EmbedLiveSample('Other_box_shadow_features', '100%', 70) }}
Here we've set up some button styling along with focus/hover/active states. The button has a simple black box shadow set on it by default, plus a couple of inset shadows, one light and one dark, placed on opposite corners of the button to give it a nice shading effect.
When the button is pressed in, the active state causes the first box shadow to be swapped for a very dark inset shadow, giving the appearance of the button being pressed in.
> **Note:** There is another item that can be set in the `box-shadow` value — another length value can be optionally set just before the color value, which is a **spread radius**. If set, this causes the shadow to become bigger than the original box. It is not very commonly used, but worth mentioning.
## Filters
While you can't change the composure of an image using CSS, there are some creative things you can do. One very nice property, which can help you bring interest to your designs, is the {{cssxref("filter")}} property. This property enables Photoshop-like filters right from CSS.
In the example below we have used two different values for filter. The `first` is `blur()` — this function can be passed a value to indicate how much the image should be blurred.
The second is `grayscale()`; by using a percentage we are setting how much color we want to be removed.
{{EmbedGHLiveSample("css-examples/learn/images/filter.html", '100%', 900)}}
**Play with the percentage and pixel parameters in the live example to see how the images change. You could also swap the values for some others. Try `contrast(200%)`, `invert(100%)` or `hue-rotate(20deg)` on the live example above. Take a look at the MDN page for [`filter`](/en-US/docs/Web/CSS/filter) for many other options you could try.**
You can apply filters to any element and not just images. Some of the filter options available do very similar things to other CSS features, for example `drop-shadow()` works in a very similar way and gives a similar effect to [`box-shadow`](/en-US/docs/Web/CSS/box-shadow) or [`text-shadow`](/en-US/docs/Web/CSS/text-shadow). The really nice thing about filters however, is that they work on the exact shapes of the content inside the box, not just the box itself as one big chunk, so it is worth knowing the difference.
In this next example we are applying our filter to a box, and comparing it to a box shadow. As you can see, the drop-shadow filter follows the exact shape of the text and border dashes. The box shadow just follows the square of the box.
{{EmbedGHLiveSample("css-examples/learn/images/filter-text.html", '100%', 700)}}
## Blend modes
CSS blend modes allow us to add blend modes to elements that specify a blending effect when two elements overlap — the final color shown for each pixel will be the result of a combination of the original pixel color, and that of the pixel in the layer underneath it. Blend modes are again very familiar to users of graphics applications like Photoshop.
There are two properties that use blend modes in CSS:
- {{cssxref("background-blend-mode")}}, which blends together multiple background images and colors set on a single element.
- {{cssxref("mix-blend-mode")}}, which blends together the element it is set on with elements it is overlapping — both background and content.
You can find a lot more examples than are available here in our [blend-modes.html](https://mdn.github.io/learning-area/css/styling-boxes/advanced_box_effects/blend-modes.html) example page (see [source code](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/advanced_box_effects/blend-modes.html)), and on the {{cssxref("<blend-mode>")}} reference page.
> **Note:** Blend modes are also very new, and slightly less well supported than filters. There is no support as yet in Edge, and Safari only supports some of the blend mode options.
### background-blend-mode
Again, let's look at some examples so we can understand this better. First, {{cssxref("background-blend-mode")}} — here we'll show a couple of simple {{htmlelement("div")}}s, so you can compare the original with the blended version:
```html
<div></div>
<div class="multiply"></div>
```
Now some CSS — we are adding to the `<div>` one background image and a green background color:
```css
div {
width: 250px;
height: 130px;
padding: 10px;
margin: 10px;
display: inline-block;
background: url(colorful-heart.png) no-repeat center 20px;
background-color: green;
}
.multiply {
background-blend-mode: multiply;
}
```
The result we get is this — you can see the original on the left, and the multiply blend mode on the right:
{{ EmbedLiveSample('background-blend-mode', '100%', 300) }}
### mix-blend-mode
Now let's look at {{cssxref("mix-blend-mode")}}. Here we'll present the same two `<div>`s, but each one is now sat on top of a simple `<div>` with a purple background, to show how the elements will blend together:
```html
<article>
No mix blend mode
<div></div>
<div></div>
</article>
<article>
Multiply mix
<div class="multiply-mix"></div>
<div></div>
</article>
```
Here's the CSS we'll style this with:
```css
article {
width: 280px;
height: 180px;
margin: 10px;
position: relative;
display: inline-block;
}
div {
width: 250px;
height: 130px;
padding: 10px;
margin: 10px;
}
article div:first-child {
position: absolute;
top: 10px;
left: 0;
background: url(colorful-heart.png) no-repeat center 20px;
background-color: green;
}
article div:last-child {
background-color: purple;
position: absolute;
bottom: -10px;
right: 0;
z-index: -1;
}
.multiply-mix {
mix-blend-mode: multiply;
}
```
This gives us the following results:
{{ EmbedLiveSample('mix-blend-mode', '100%', 300) }}
You can see here that the multiply mix blend has blended together not only the two background images, but also the color from the `<div>` below it too.
> **Note:** Don't worry if you don't understand some of the layout properties above, like {{cssxref("position")}}, {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("z-index")}}, etc. We will cover these in detail in our [CSS Layout](/en-US/docs/Learn/CSS/CSS_layout) module.
## CSS shapes
While it is true that everything in CSS is a rectangular box, and images are a physical rectangular box, we can make it look as if our content flows around non-rectangular things by using [CSS Shapes](/en-US/docs/Web/CSS/CSS_shapes).
The CSS Shapes specification enables the wrapping of text around a non-rectangular shape. It's especially useful when working with an image which has some white-space you might want to float text around.
In the image below we have a pleasingly round balloon. The actual file is rectangular, but by floating the image (shapes only apply to floated elements) and using the {{cssxref("shape-outside")}} property with a value of `circle(50%)`, we can give the effect of the text following the line of the balloon.
{{EmbedGHLiveSample("css-examples/learn/images/shapes.html", '100%', 1000)}}
The shape in this example is not reacting to the content of the image file. Instead, the circle function is taking its center point from the center of the image file, as if we had put a compass in the middle of the file and drawn a circle that fits inside the file. It is that circle that the text flows around.
> **Note:** In Firefox you can use the DevTools [Shapes Inspector](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/edit_css_shapes/index.html) to inspect Shapes.
The `circle()` function is just one of a few basic shapes that are defined, however there are a number of different ways to create shapes. For more information and example code for CSS Shapes see the [Guides to CSS Shapes](/en-US/docs/Web/CSS/CSS_shapes/Overview_of_shapes) on MDN.
## -webkit-background-clip: text
Another feature we thought we'd mention briefly is the `text` value for {{cssxref("background-clip")}}. When used along with the proprietary `-webkit-text-fill-color: transparent;` feature, this allows you to clip background images to the shape of the element's text, making for some nice effects. This is not an official standard, but has been implemented across multiple browsers, as it is popular, and used fairly widely by developers. When used in this context, both of the properties would require a `-webkit-` vendor prefix, even for Non-Webkit/Chrome-based browsers:
```css
.text-clip {
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
```
So why have other browsers implemented a `-webkit-` prefix? Mainly for browser compatibility — so many web developers have started implementing websites with `-webkit-` prefixes that it started to look like the other browsers were broken, whereas in actual fact they were following the standards. So they were forced to implement a few such features. This highlights the danger of using non-standard and/or prefixed CSS features in your work — not only do they cause browser compatibility issues, but they are also subject to change, so your code could break at any time. It is much better to stick to the standards.
If you do want to use such features in your production work, make sure to test across browsers thoroughly and check that, where these features don't work, the site is still usable.
> **Note:** For a full `-webkit-background-clip: text` code example, see [background-clip-text.html](https://mdn.github.io/learning-area/css/styling-boxes/advanced_box_effects/background-clip-text.html) (see also the [source code](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/advanced_box_effects/background-clip-text.html)).
## Summary
We hope this article was fun — playing with shiny toys generally is, and it is always interesting to see what kinds of advanced styling tools are becoming available in modern browsers.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/handling_different_text_directions/index.md | ---
title: Handling different text directions
slug: Learn/CSS/Building_blocks/Handling_different_text_directions
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Backgrounds_and_borders", "Learn/CSS/Building_blocks/Overflowing_content", "Learn/CSS/Building_blocks")}}
Many of the properties and values that we have encountered so far in our CSS learning have been tied to the physical dimensions of our screen. We create borders on the top, right, bottom, and left of a box, for example. These physical dimensions map very neatly to content that is viewed horizontally, and by default the web tends to support left-to-right languages (e.g. English or French) better than right-to-left languages (such as Arabic).
In recent years however, CSS has evolved in order to better support different directionality of content, including right-to-left but also top-to-bottom content (such as Japanese) — these different directionalities are called **writing modes**. As you progress in your study and begin to work with layout, an understanding of writing modes will be very helpful to you, therefore we will introduce them now.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To understand the importance of writing modes to modern CSS.</td>
</tr>
</tbody>
</table>
## What are writing modes?
A writing mode in CSS refers to whether the text is running horizontally or vertically. The {{cssxref("writing-mode")}} property lets us switch from one writing mode to another. You don't need to be working in a language which uses a vertical writing mode to want to do this — you could also change the writing mode of parts of your layout for creative purposes.
In the example below we have a heading displayed using `writing-mode: vertical-rl`. The text now runs vertically. Vertical text is common in graphic design, and can be a way to add a more interesting look and feel to your web design.
{{EmbedGHLiveSample("css-examples/learn/writing-modes/simple-vertical.html", '100%', 800)}}
The three possible values for the [`writing-mode`](/en-US/docs/Web/CSS/writing-mode) property are:
- `horizontal-tb`: Top-to-bottom block flow direction. Sentences run horizontally.
- `vertical-rl`: Right-to-left block flow direction. Sentences run vertically.
- `vertical-lr`: Left-to-right block flow direction. Sentences run vertically.
So the `writing-mode` property is in reality setting the direction in which block-level elements are displayed on the page — either from top-to-bottom, right-to-left, or left-to-right. This then dictates the direction text flows in sentences.
## Writing modes and block and inline layout
We have already discussed [block and inline layout](/en-US/docs/Web/CSS/CSS_flow_layout/Block_and_inline_layout_in_normal_flow), and the fact that some things display as block elements and others as inline elements. As we have seen described above, block and inline is tied to the writing mode of the document, and not the physical screen. Blocks are only displayed from the top to the bottom of the page if you are using a writing mode that displays text horizontally, such as English.
If we look at an example this will become clearer. In this next example I have two boxes that contain a heading and a paragraph. The first uses `writing-mode: horizontal-tb`, a writing mode that is written horizontally and from the top of the page to the bottom. The second uses `writing-mode: vertical-rl`; this is a writing mode that is written vertically and from right to left.
{{EmbedGHLiveSample("css-examples/learn/writing-modes/block-inline.html", '100%', 1200)}}
When we switch the writing mode, we are changing which direction is block and which is inline. In a `horizontal-tb` writing mode the block direction runs from top to bottom; in a `vertical-rl` writing mode the block direction runs right-to-left horizontally. So the **block dimension** is always the direction blocks are displayed on the page in the writing mode in use. The **inline dimension** is always the direction a sentence flows.
This figure shows the two dimensions when in a horizontal writing mode.
This figure shows the two dimensions in a vertical writing mode.

Once you start to look at CSS layout, and in particular the newer layout methods, this idea of block and inline becomes very important. We will revisit it later on.
### Direction
In addition to writing mode we also have text direction. As mentioned above, some languages such as Arabic are written horizontally, but right-to-left. This is not something you are likely to use in a creative sense — if you want to line something up on the right there are other ways to do so — however it is important to understand this as part of the nature of CSS. The web is not just for languages that are displayed left-to-right!
Due to the fact that writing mode and direction of text can change, newer CSS layout methods do not refer to left and right, and top and bottom. Instead they will talk about _start_ and _end_ along with this idea of inline and block. Don't worry too much about that right now, but keep these ideas in mind as you start to look at layout; you will find it really helpful in your understanding of CSS.
## Logical properties and values
The reason to talk about writing modes and direction at this point in your learning is that we have already looked at a lot of properties that are tied to the physical dimensions of the screen, and these make more sense when in a horizontal writing mode.
Let's take a look at our two boxes again — one with a `horizontal-tb` writing mode and one with `vertical-rl`. I have given both of these boxes a {{cssxref("width")}}. You can see that when the box is in the vertical writing mode, it still has a width, and this is causing the text to overflow.
{{EmbedGHLiveSample("css-examples/learn/writing-modes/width.html", '100%', 1200)}}
What we really want in this scenario is to essentially swap height with width in accordance to the writing mode. When we're in a vertical writing mode we want the box to expand in the block dimension just like it does in the horizontal mode.
To make this easier, CSS has recently developed a set of mapped properties. These essentially replace physical properties — things like `width` and `height` — with **logical**, or **flow relative** versions.
The property mapped to `width` when in a horizontal writing mode is called {{cssxref("inline-size")}} — it refers to the size in the inline dimension. The property for `height` is named {{cssxref("block-size")}} and is the size in the block dimension. You can see how this works in the example below where we have replaced `width` with `inline-size`.
{{EmbedGHLiveSample("css-examples/learn/writing-modes/inline-size.html", '100%', 1000)}}
### Logical margin, border, and padding properties
In the last two lessons we have learned about the CSS box model, and CSS borders. In the margin, border, and padding properties you will find many instances of physical properties, for example {{cssxref("margin-top")}}, {{cssxref("padding-left")}}, and {{cssxref("border-bottom")}}. In the same way that we have mappings for width and height there are mappings for these properties.
The `margin-top` property is mapped to {{cssxref("margin-block-start")}} — this will always refer to the margin at the start of the block dimension.
The {{cssxref("padding-left")}} property maps to {{cssxref("padding-inline-start")}}, the padding that is applied to the start of the inline direction. This will be where sentences start in that writing mode. The {{cssxref("border-bottom")}} property maps to {{cssxref("border-block-end")}}, which is the border at the end of the block dimension.
You can see a comparison between physical and logical properties below.
**If you change the writing mode of the boxes by switching the `writing-mode` property on `.box` to `vertical-rl`, you will see how the physical properties stay tied to their physical direction, whereas the logical properties switch with the writing mode.**
**You can also see that the {{htmlelement("Heading_Elements", "h2")}} has a black `border-bottom`. Can you work out how to make that bottom border always go below the text in both writing modes?**
{{EmbedGHLiveSample("css-examples/learn/writing-modes/logical-mbp.html", '100%', 1300)}}
There are a huge number of properties when you consider all of the individual border longhands, and you can see all of the mapped properties on the MDN page for [Logical Properties and Values](/en-US/docs/Web/CSS/CSS_logical_properties_and_values).
### Logical values
We have so far looked at logical property names. There are also some properties that take physical values of `top`, `right`, `bottom`, and `left`. These values also have mappings, to logical values — `block-start`, `inline-end`, `block-end`, and `inline-start`.
For example, you can float an image left to cause text to wrap round the image. You could replace `left` with `inline-start` as shown in the example below.
**Change the writing mode on this example to `vertical-rl` to see what happens to the image. Change `inline-start` to `inline-end` to change the float.**
{{EmbedGHLiveSample("css-examples/learn/writing-modes/float.html", '100%', 1000)}}
Here we are also using logical margin values to ensure the margin is in the correct place no matter what the writing mode is.
### Should you use physical or logical properties?
The logical properties and values are newer than their physical equivalents, and therefore have only recently been implemented in browsers. You can check any property page on MDN to see how far back the browser support goes. If you are not using multiple writing modes, then for now you might prefer to use the physical versions. However, ultimately we expect that people will transition to the logical versions for most things, as they make a lot of sense once you also start dealing with layout methods such as flexbox and grid.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Writing modes and logical properties](/en-US/docs/Learn/CSS/Building_blocks/Writing_Modes_Tasks).
## Summary
The concepts explained in this lesson are becoming increasingly important in CSS. An understanding of the block and inline direction — and how text flow changes with a change in writing mode — will be very useful going forward. It will help you in understanding CSS even if you never use a writing mode other than a horizontal one.
In the next article, we'll take a good look at [overflow](/en-US/docs/Learn/CSS/Building_blocks/Overflowing_content) in CSS.
{{PreviousMenuNext("Learn/CSS/Building_blocks/Backgrounds_and_borders", "Learn/CSS/Building_blocks/Overflowing_content", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/test_your_skills_backgrounds_and_borders/index.md | ---
title: "Test your skills: Backgrounds and borders"
slug: Learn/CSS/Building_blocks/Test_your_skills_backgrounds_and_borders
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you understand [backgrounds and borders of boxes in CSS](/en-US/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders).
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Task 1
In this task, we want you to add a background, border, and some simple styling to a page header:
1. Give the box a 5px black solid border, with rounded corners of 10px.
2. Add a background image (use the URL `balloons.jpg`) and size it so that it covers the box.
3. Give the `<h2>` a semi-transparent black background color, and make the text white.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/backgrounds/backgrounds1.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/backgrounds/backgrounds1-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, we want you to add background images, a border, and some other styling to a decorative box:
- Give the box a 5px lightblue border and round the top left corner 20px and the bottom right corner 40px.
- The heading uses the `star.png` image as a background image, with a single centered star on the left and a repeating pattern of stars on the right.
- Make sure that the heading text does not overlay the image, and that it is centered — you will need to use techniques learned in previous lessons to achieve this.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/backgrounds/backgrounds2.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/backgrounds/backgrounds2-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/cascade_layers/index.md | ---
title: Cascade layers
slug: Learn/CSS/Building_blocks/Cascade_layers
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Cascade_and_inheritance", "Learn/CSS/Building_blocks/The_box_model", "Learn/CSS/Building_blocks")}}
This lesson aims to introduce you to [cascade layers](/en-US/docs/Web/CSS/@layer), a more advanced feature that builds on the fundamental concepts of the [CSS cascade](/en-US/docs/Web/CSS/Cascade) and [CSS specificity](/en-US/docs/Web/CSS/Specificity).
If you are new to CSS, working through this lesson may seem less relevant immediately and a little more academic than some other parts of the course. However, knowing the basics of what cascade layers are should you encounter them in your projects is helpful. The more you work with CSS, understanding cascade layers and knowing how to leverage their power will save you from a lot of pain managing a code base with CSS from different parties, plugins, and development teams.
Cascade layers are most relevant when you're working with CSS from multiple sources when there are conflicting CSS selectors and competing specificities, or when you're considering using [`!important`](/en-US/docs/Web/CSS/important).
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>An idea of how CSS works, including cascade and specificity (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a> and <a href="/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance">Cascade, specificity, and inheritance</a>).
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how cascade layers work.
</td>
</tr>
</tbody>
</table>
For each CSS property applied to an element, there can only be one value. You can view all the property values applied to an element by inspecting the element in your browser's developer tools. The tool's "Styles" panel shows all the property values applied to the element being inspected, along with the matched selector and the CSS source file. The selector from the origin with precedence has its values applied to the matching element.
In addition to the applied styles, the Styles panel displays crossed-out values that matched the selected element but were not applied due to the cascade, specificity, or source order. Crossed-out styles may come from the same origin with precedence but with lower specificity, or with matching origin and specificity, but were found earlier in the code base. For any applied property value, there may be several declarations crossed out from many different sources. If you see a style crossed out that has a selector with greater specificity it means the value is lacking in origin or importance.
Often, as the complexity of a site increases, the number of stylesheets increases, which makes the source order of the stylesheets both more important and more complex. Cascade layers simplify maintaining stylesheets across such code bases. Cascade layers are explicit specificity containers providing simpler and greater control over the CSS declarations that ultimately get applied, enabling web developers to prioritize sections of CSS without having to fight specificity.
To understand cascade layers, you must understand the CSS cascade well. The sections below provide a quick recap of the important cascade concepts.
## Review of the cascade concept
The C in CSS stands for "Cascading". It is the method by which styles cascade together. The user agent runs through several clearly defined steps to determine the values assigned to every property for every element. We will briefly list these steps here and then dig deeper into step 4, **Cascade layers**, which is what you came here to learn:
1. **Relevance:** Find all the declaration blocks with a selector match for each element.
2. **Importance:** Sort rules based on whether they are normal or important. Important styles are those that have the [`!important`](/en-US/docs/Web/CSS/important) flag set.
3. **Origin:** Within each of the two importance buckets, sort rules by author, user, or user-agent origin.
4. **Cascade layers:** Within each of the six origin importance buckets, sort by cascade layer. The layer order for normal declarations is from the first layer created to the last, followed by unlayered normal styles. This order is inverted for important styles, with unlayered important styles having the lowest precedence.
5. **Specificity:** For competing styles in the origin layer with precedence, sort declarations by [specificity](/en-US/docs/Web/CSS/Specificity).
6. **Scoping proximity**: When two selectors in the origin layer with precedence have the same specificity, the property value within scoped rules with the smallest number of hops up the DOM hierarchy to the scope root wins. See [How `@scope` conflicts are resolved](/en-US/docs/Web/CSS/@scope#how_scope_conflicts_are_resolved) for more details and an example.
7. **Order of appearance:** When two selectors in the origin layer with precedence have the same specificity and scope proximity, the property value from the last declared selector with the highest specificity wins.
For each step, only the declarations "still in the running" move on to "compete" in the next step. If only one declaration is in the running, it "wins", and the subsequent steps are moot.
### Origin and cascade
There are three [cascade origin types](/en-US/docs/Web/CSS/Cascade#origin_types): user-agent stylesheets, user stylesheets, and author stylesheets. The browser sorts each declaration into six origin buckets by origin and importance. There are eight levels of precedence: the six origin buckets, properties that are transitioning, and properties that are animating. The order of precedence goes from normal user-agent styles, which have the lowest precedence, to styles within currently applied animations, to important user-agent styles, and then styles being transitioned, which have the highest precedence:
1. user-agent normal styles
2. user normal styles
3. author normal styles
4. styles being animated
5. author important styles
6. user important styles
7. user-agent important styles
8. styles being transitioned
The "user-agent" is the browser. The "user" is the site visitor. The "author" is you, the developer. Styles declared directly on an element with the {{HTMLElement('style')}} element are author styles. Not including animating and transitioning styles, user-agent normal styles have the lowest precedence; user-agent important styles have the highest.
### Origin and specificity
For each property, the declaration that "wins" is the one from the origin with precedence based on the weight (normal or important). Ignoring layers for the moment, the value from the origin with the highest precedence gets applied. If the winning origin has more than one property declaration for an element, the [specificity](/en-US/docs/Web/CSS/Specificity) of the selectors for those competing property values are compared. Specificity is never compared between selectors from different origins.
In the example below, there are two links. The first has no author styles applied, so only user-agent styles are applied (and your personal user styles, if any). The second has [`text-decoration`](/en-US/docs/Web/CSS/text-decoration) and [`color`](/en-US/docs/Web/CSS/color) set by author styles even though the selector in the author stylesheet has a specificity of [`0-0-0`](/en-US/docs/Web/CSS/Specificity#selector_weight_categories). The reason why author styles "win" is because when there are conflicting styles from different origins, the rules from the origin with precedence are applied, irrespective of the specificity in the origin that doesn't have precedence.
{{EmbedGHLiveSample("css-examples/learn/layers/basic-cascade.html", '100%', 500)}}
The "competing" selector in the user-agent stylesheet at the time of this writing is `a:any-link`, which has a specificity weight of `0-1-1`. While this is greater than the `0-0-0` selector in the author stylesheet, even if the selector in your current user agent is different, it doesn't matter: the specificity weights from author and user-agent origins are never compared. Learn more about [how specificity weight is calculated](/en-US/docs/Web/CSS/Specificity#how_is_specificity_calculated).
Origin precedence always wins over selector specificity. If an element property is styled with a normal style declaration in multiple origins, the author style sheet will always override the redundant normal properties declared in a user or user-agent stylesheet. If the style is important, the user-agent stylesheet will always win over author and user styles. Cascade origin precedence ensures specificity conflicts between origins never happen.
One last thing to note before moving on: the order of appearance becomes relevant only when competing declarations in the origin of precedence have the same specificity.
## Overview of cascade layers
We now understand "cascade origin precedence", but what is "cascade layer precedence"? We will answer that question by addressing what cascade layers are, how they are ordered, and how styles are assigned to cascade layers. We'll cover [regular layers](#creating_cascade_layers), [nested layers](#overview_of_nested_cascade_layers), and anonymous layers. Let's first discuss what cascade layers are and what issues they solve.
### Cascade layer precedence order
Similar to how we have six levels of priority based on origin and importance, cascade layers enable us to create sub-origin level of priority within any of those origins.
Within each of the six origin buckets, there can be multiple cascade layers. The [order of layer creation](/en-US/docs/Web/CSS/@layer) matters a lot. It is the order of creation that sets the precedence order among layers within an origin.
In normal origin buckets, layers are sorted in the order of each layer's creation. The order of precedence is from the first layer created to the last, followed by unlayered normal styles.
This order is inverted for important styles. All unlayered important styles cascade together into an implicit layer having precedence over all non-transitioning normal styles. The unlayered important styles have lower precedence than any important layered styles. The important styles in earlier declared layers have precedence over important styles in subsequent declared layers within the same origin.
For the rest of this tutorial, we will limit our discussion to author styles, but keep in mind that layers can also exist in user and user-agent stylesheets.
### Issues cascade layers can solve
Large code bases can have styles coming from multiple teams, component libraries, frameworks, and third parties. No matter how many stylesheets are included, all these styles cascade together in a single origin: the _author_ style sheet.
Having styles from many sources cascade together, especially from teams that aren't working together, can create problems. Different teams may have different methodologies; one may have a best practice of reducing specificity, while another may have a standard of including an `id` in each selector.
Specificity conflicts can escalate quickly. A web developer may create a "quick fix" by adding an `!important` flag. While this may feel like an easy solution, it often just moves the specificity war from normal to important declarations.
In the same way that cascade origins provide a balance of power between user, user-agents, and author styles, cascade layers provide a structured way to organize and balance concerns within a single origin as if each layer in an origin were a sub-origin. A layer can be created for each team, component, and third party, with style precedence based on layer order.
Rules within a layer cascade together, without competing with style rules outside the layer. Cascade layers enable the prioritizing of entire stylesheets over other stylesheets, without having to worry about specificity between these sub-origins.
Layer precedence always beats selector specificity. Styles in layers with precedence "win" over layers with less precedence. The specificity of a selector in a losing layer is irrelevant. Specificity still matters for competing property values within a layer, but there are no specificity concerns between layers because only the highest-priority layer for each property is considered.
### Issues nested cascade layers can solve
Cascade layers allow the creation of nested layers. Each cascade layer can contain nested layers.
For example, a component library may be imported into a `components` layer. A regular cascade layer will add the component library to the author origin, removing any specificity conflicts with other author styles. Within the `components` layer, a developer can choose to define various themes, each as a separate nested layer. The order of these nested theme layers can be defined based on media queries (see the [Layer creation and media queries](#layer_creation_and_media_queries) section below), such as viewport size or [orientation](/en-US/docs/Web/CSS/@media/orientation). These nested layers provide a way to create themes that don't conflict based on specificity.
The ability to nest layers is very useful for anybody who works on developing component libraries, frameworks, third-party widgets, and themes.
The ability to create nested layers also removes the worry of having conflicting layer names. We'll cover this in the [nested layer](#overview_of_nested_cascade_layers) section.
> "Authors can create layers to represent element defaults, third-party libraries, themes, components, overrides, and other styling concerns—and are able to re-order the cascade of layers in an explicit way, without altering selectors or specificity within each layer, or relying on order of appearance to resolve conflicts across layers."
>
> —[Cascading and Inheritance specification](https://www.w3.org/TR/css-cascade-5/#layering).
## Creating cascade layers
Layers can be created using any one of the following methods:
- The `@layer` statement at-rule, declaring layers using `@layer` followed by the names of one or more layers. This creates named layers without assigning any styles to them.
- The `@layer` block at-rule, in which all styles within a block are added to a named or unnamed layer.
- The [`@import`](/en-US/docs/Web/CSS/@import) rule with the `layer` keyword or `layer()` function, which assigns the contents of the imported file into that layer.
All three methods create a layer if a layer with that name has not already been initialized. If no layer name is provided in the `@layer` at-rule or `@import` with `layer()`, a new anonymous (unnamed) layer is created.
> **Note:** The order of precedence of layers is the order in which they are created. Styles not in a layer, or "unlayered styles", cascade together into a final implicit label.
Let's cover the three ways of creating a layer in a little more detail before discussing nested layers.
### The @layer statement at-rule for named layers
The order of layers is set by the order in which the layers appear in your CSS. Declaring layers using `@layer` followed by the names of one or more layers without assigning any styles is one way to define the [layer order](#determining_the_precedence_based_on_the_order_of_layers).
The [`@layer`](/en-US/docs/Web/CSS/@layer) CSS at-rule is used to declare a cascade layer and to define the order of precedence when there are multiple cascade layers. The following at-rule declares three layers, in the order listed:
```css
@layer theme, layout, utilities;
```
You will often want to have your first line of CSS be this `@layer` declaration (with layer names that make sense for your site, of course) to have full control over layer ordering.
If the above statement is the first line of a site's CSS, the layer order will be `theme`, `layout`, and `utilities`. If some layers were created prior to the above statement, as long as layers with these names don't already exist, these three layers will be created and added to the end of the list of existing layers. However, if a layer with the same name already exists, then the above statement will create only two new layers. For example, if `layout` already existed, only `theme` and `utilities` will be created, but the order of layers, in this case, will be `layout`, `theme`, and `utilities`.
### The @layer block at-rule for named and anonymous layers
Layers can be created using the block `@layer` at-rule. If an `@layer` at-rule is followed by an identifier and a block of styles, the identifier is used to name the layer, and the styles in this at-rule are added to the layer's styles. If a layer with the specified name does not already exist, a new layer will be created. If a layer with the specified name already exists, the styles are added to the previously existing layer. If no name is specified while creating a block of styles using `@layer`, the styles in the at-rule will be added to a new anonymous layer.
In the example below, we've used four block and one inline `@layer` at-rules. This CSS does the following in the order listed:
1. Creates a named `layout` layer
2. Creates an unnamed, anonymous layer
3. Declares a list of three layers and creates only two new layers, `theme` and `utilities`, because `layout` already exists
4. Adds additional styles to the already existing `layout` layer
5. Creates a second unnamed, anonymous layer
```css
/* file: layers1.css */
/* unlayered styles */
body {
color: #333;
}
/* creates the first layer: `layout` */
@layer layout {
main {
display: grid;
}
}
/* creates the second layer: an unnamed, anonymous layer */
@layer {
body {
margin: 0;
}
}
/* creates the third and fourth layers: `theme` and `utilities` */
@layer theme, layout, utilities;
/* adds styles to the already existing `layout` layer */
@layer layout {
main {
color: #000;
}
}
/* creates the fifth layer: an unnamed, anonymous layer */
@layer {
body {
margin: 1vw;
}
}
```
In the above CSS, we created five layers: `layout`, `<anonymous(01)>`, `theme`, `utilities`, and `<anonymous(02)>` – in that order - with a sixth, implicit layer of unlayered styles contained in the `body` style block. The layer order is the order in which the layers are created, with the implicit layer of unlayered styles always being last. There is no way to change the layer order once created.
We assigned some styles to the layer named `layout`. If a named layer doesn't already exist, then specifying the name in an `@layer` at-rule, with or without assigning styles to the layer, creates the layer; this adds the layer to the end of the series of existing layer names. If the named layer already exists, all styles within the named block get appended to styles in the previously existing layer – specifying styles in a block by reusing an existing layer name does not create a new layer.
Anonymous layers are created by assigning styles to a layer without naming the layer. Styles can be added to an unnamed layer only at the time of its creation.
> **Note:** Subsequent use of `@layer` with no layer name creates additional unnamed layers; it does not append styles to a previously existing unnamed layer.
The `@layer` at-rule creates a layer, named or not, or appends styles to a layer if the named layer already exists. We called the first anonymous layer `<anonymous(01)>` and the second `<anonymous(02)>`, this is just so we can explain them. These are actually unnamed layers. There is no way to reference them or add additional styles to them.
All styles declared outside of a layer are joined together in an implicit layer. In the example code above, the first declaration set the `color: #333` property on `body`. This was declared outside of any layer. Normal unlayered declarations take precedence over normal layered declarations even if the unlayered styles have a lower specificity and come first in the order of appearance. This explains why even though the unlayered CSS was declared first in the code block, the implicit layer containing these unlayered styles takes precedence as if it was the last declared layer.
In the line `@layer theme, layout, utilities;`, in which a series of layers were declared, only the `theme` and `utilities` layers were created; `layout` was already created in the first line. Note that this declaration does not change the order of already created layers. There is currently no way to re-order layers once declared.
In the following interactive example, we assign styles to two layers, creating them and naming them in the process. Because they already exist, being created when first used, declaring them on the last line does nothing.
{{EmbedGHLiveSample("css-examples/learn/layers/layer-order.html", '100%', 500)}}
Try moving the last line, `@layer site, page;`, to make it the first line. What happens?
#### Layer creation and media queries
If you define a layer using [media](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) or [feature](/en-US/docs/Web/CSS/CSS_conditional_rules/Using_feature_queries) queries, and the media is not a match or the feature is not supported, the layer is not created. The example below shows how changing the size of your device or browser may change the layer order. In this example, we create the `site` layer only in wider browsers. We then assign styles to the `page` and `site` layers, in that order.
{{EmbedGHLiveSample("css-examples/learn/layers/media-order.html", '100%', 500)}}
In wide screens, the `site` layer is declared in the first line, meaning `site` has less precedence than `page`. Otherwise, `site` has precedence over `page` because it is declared later on narrow screens. If that doesn't work, try changing the `50em` in the media query to `10em` or `100em`.
### Importing style sheets into named and anonymous layers with @import
The [`@import`](/en-US/docs/Web/CSS/@import) rule allows users to import style rules from other style sheets either directly into a CSS file or into a {{htmlelement('style')}} element.
When importing stylesheets, the `@import` statement must be defined before any CSS styles within the stylesheet or `<style>` block. The `@import` statement must come first, before any styles, but can be preceded by an `@layer` at-rule that creates one or more layers without assigning any styles to the layers. (`@import` can also be preceded by an [`@charset`](/en-US/docs/Web/CSS/@charset) rule.)
You can import a stylesheet into a named layer, a nested named layer, or an anonymous layer. The following layer imports the style sheets into a `components` layer, a nested `dialog` layer within the `components` layer, and an un-named layer, respectively:
```css
@import url("components-lib.css") layer(components);
@import url("dialog.css") layer(components.dialog);
@import url("marketing.css") layer();
```
You can import more than one CSS file into a single layer. The following declaration imports two separate files into a single `social` layer:
```css
@import url(comments.css) layer(social);
@import url(sm-icons.css) layer(social);
```
You can import styles and create layers based on specific conditions using [media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) and [feature queries](/en-US/docs/Web/CSS/CSS_conditional_rules/Using_feature_queries). The following imports a style sheet into an `international` layer only if the browser supports `display: ruby`, and the file being imported is dependent on the width of the screen.
```css
@import url("ruby-narrow.css") layer(international) supports(display: ruby) and
(width < 32rem);
@import url("ruby-wide.css") layer(international) supports(display: ruby) and
(width >= 32rem);
```
> **Note:** There is no equivalent of the {{HTMLElement('link')}} method of linking stylesheets. Use `@import` to import a stylesheet into a layer when you can't use `@layer` within the stylesheet.
## Overview of nested cascade layers
Nested layers are layers within a named or an anonymous layer. Each cascade layer, even an anonymous one, can contain nested layers. Layers imported into another layer become nested layers within that layer.
### Advantages of nesting layers
The ability to nest layers enables teams to create cascade layers without worrying about whether other teams will import them into a layer. Similarly, nesting enables you to import third-party style sheets into a layer without worrying if that style sheet itself has layers. Because layers can be nested, you don't have to worry about having conflicting layer names between external and internal style sheets.
### Creating nested cascade layers
Nested layers can be created using the same methods as described for regular layers. For example, they can be created using `@layer` at-rule followed by the names of one or more layers, using a dot notation. Multiple dots and layer names signify multiple nesting.
If you nest a block `@layer` at-rule inside another block `@layer` at-rule, with or without a name, the nested block becomes a nested layer. Similarly, when a style sheet is imported with an `@import` declaration containing the `layer` keyword or `layer()` function, the styles get assigned to that named or anonymous layer. If the `@import` statement contains layers, those layers become nested layers within that anonymous or named layer.
Let's look at the following example:
```css
@import url("components-lib.css") layer(components);
@import url("narrowtheme.css") layer(components.narrow);
```
In the first line, we import `components-lib.css` into the `components` layer. If that file contains any layers, named or not, those layers become nested layers within the `components` layer.
The second line imports `narrowtheme.css` into the `narrow` layer, which is a sub-layer of `components`. The nested `components.narrow` gets created as the last layer within the `components` layer, unless `components-lib.css` already contains a `narrow` layer, in which case, the contents of `narrowtheme.css` would be appended to the `components.narrow` nested layer. Additional nested named layers can be added to the `components` layer using the pattern `components.<layerName>`. As mentioned before, unnamed layers can be created but they cannot be accessed subsequently.
Let's look at another example, where we [import `layers1.css` into a named layer](#the_layer_block_at-rule_for_named_and_anonymous_layers) using the following statement:
```css
@import url(layers1.css) layer(example);
```
This will create a single layer named `example` containing some declarations and five nested layers - `example.layout`, `example.<anonymous(01)>`, `example.theme`, `example.utilities`, and `example.<anonymous(02)>`.
To add styles to a named nested layer, use the dot notation:
```css
@layer example.layout {
main {
width: 50vw;
}
}
```
## Determining the precedence based on the order of layers
The order of layers determines their order of precedence. Therefore, the order of layers is very important. In the same way as the cascade sorts by origin and importance, the cascade sorts each CSS declaration by origin layer and importance.
### Precedence order of regular cascade layers
```css
@import url(A.css) layer(firstLayer);
@import url(B.css) layer(secondLayer);
@import url(C.css);
```
The above code creates two named layers (C.css styles get appended to the implicit layer of unlayered styles). Let us assume that the three files (`A.css`, `B.css`, and `C.css`) do not contain any additional layers within them. The following list shows where styles declared inside and outside of these files will be sorted from least (1) precedence to highest (10).
1. `firstLayer` normal styles (`A.css`)
2. `secondLayer` normal styles (`B.css`)
3. unlayered normal styles (`C.css`)
4. inline normal styles
5. animating styles
6. unlayered important styles (`C.css`)
7. `secondLayer` important styles (`B.css`)
8. `firstLayer` important styles (`A.css`)
9. inline important styles
10. transitioning styles
Normal styles declared inside layers receive the lowest priority and are sorted by the order in which the layers were created. Normal styles in the first created layer have the lowest precedence, and normal styles in the layer created last have the highest precedence among the layers. In other words, normal styles declared within `firstLayer` will be overridden by any subsequent stylings on the list if any conflicts exist.
Next up are any styles declared outside of layers. The styles in `C.css` were not imported into a layer and will override any conflicting styles from `firstLayer` and `secondLayer`. Styles not declared in a layer always have higher precedence than styles that _are_ declared inside a layer (with the exception of important styles).
Inline styles are declared using the [`style` attribute](/en-US/docs/Web/HTML/Global_attributes/style). Normal styles declared in this way will take precedence over normal styles found in the unlayered and layered style sheets (`firstLayer – A.css`, `secondLayer – B.css`, and `C.css`).
Animating styles have higher precedence than all normal styles, including inline normal styles.
Important styles, that is, property values that include the `!important` flag, take precedence over any styles previously mentioned in our list. They are sorted in reverse order of normal styles. Any important styles declared outside of a layer have less precedence than those declared within a layer. Important styles found within layers are also sorted in order of layer creation. For important styles, the last created layer has the lowest precedence, and the first created layer has the highest precedence among declared layers.
Inline important styles again have higher precedence than important styles declared elsewhere.
Transitioning styles have the highest precedence. When a normal property value is being transitioned, it takes precedence over all other property value declarations, even inline important styles; but only while transitioning.
{{EmbedGHLiveSample("css-examples/learn/layers/layer-precedence.html", '100%', 500)}}
In this example, there are two inline layers `A` and `B` without styles, a block of unlayered styles, and two blocks of styles in named layers `A` and `B`.
The inline styles added on the `h1` element using the `style` attribute, set a normal `color` and an important `background-color`. Normal inline styles override all layered and unlayered normal styles. Important inline styles override all layered and unlayered normal and important author styles. There is no way for author styles to override important inline styles.
The normal `text-decoration` and important `box-shadow` are not part of the `style` inline styles and can therefore be overridden. For normal non-inline styles, unlayered styles have precedence. For important styles, layer order matters too. While normal unlayered styles override all normal styles set in a layer, with important styles, the precedence order is reversed; unlayered important styles have lower precedence than layered styles.
The two styles declared only within layers are `font-style`, with normal importance, and `font-weight` with an `!important` flag. For normal styles, the `B` layer, declared last, overrides styles in the earlier declared layer `A`. For normal styles, later layers have precedence over earlier layers. The order of precedence is reversed for important styles. For the important `font-weight` declarations, layer `A`, being declared first, has precedence over the last declared layer `B`.
You can reverse the layer order by changing the first line from `@layer A, B;` to `@layer B, A;`. Try that. Which styles get changed by this, and which stay the same? Why?
The order of layers is set by the order in which the layers appear in your CSS. In our first line, we declared layers without assigning any styles using `@layer` followed by the names of our layers, ending with a semi-colon. Had we omitted this line, the results would have been the same. Why? We assigned style rules in named `@layer` blocks in the order A then B. The two layers were created in that first line. Had they not been, these rule blocks would have created them, in that order.
We included that first line for two reasons: first so you could easily edit the line and switch the order, and second because often you'll find declaring the order layer up front to be the best practice for your layer order management.
To summarize:
- The order of precedence of layers is the order in which the layers are created.
- Once created, there is no way to change the layer order.
- Layer precedence for normal styles is the order in which the layers are created.
- Unlayered normal styles have precedence over normal layered styles.
- Layer precedence for important styles is reversed, with earlier created layers having precedence.
- All layered important styles have precedence over unlayered important (and normal) styles.
- Normal inline styles take precedence over all normal styles, layered or not.
- Important inline styles take precedence over all other styles, with the exception of styles being transitioned.
- There is no way for author styles to override important inline styles (other than transitioning them, which is temporary).
### Precedence order of nested cascade layers
The cascade precedence order for nested layers is similar to that of regular layers, but contained within the layer. The precedence order is based on the order of nested layer creation. Non-nested styles in a layer have precedence over nested normal styles, with the precedence order reversed for important styles. Specificity weight between nested layers does not matter, though it does matter for conflicting styles within a nested layer.
The following creates and adds styles to the `components` layer and `components.narrow` nested layer and creates and appends styles to a new `components.wide` layer:
```css
@import url("components-lib.css") layer(components);
@import url("narrowtheme.css") layer(components.narrow);
@layer components {
:root {
--theme: red;
font-family: serif !important;
}
}
@layer components.narrow {
:root {
--theme: blue;
font-family: sans-serif !important;
}
}
@layer components.wide {
:root {
--theme: purple;
font-family: cursive !important;
}
}
```
Because unlayered normal styles have precedence over layered normal styles, and within a layer, non-nested styles have precedence over normal nested styles, `red` wins over the other `theme` colors.
With important styles, layered styles take precedence over unlayered styles, with important styles in earlier declared layers having precedence over later declared layers. In this example, the order of nested layer creation is `components.narrow`, then `components.wide`, so important styles in `components.narrow` have precedence over important styles in `components.wide`, meaning `sans-serif` wins.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: The Cascade, Task 2](/en-US/docs/Learn/CSS/Building_blocks/Cascade_tasks#task_2).
## Summary
If you understood most of this article, then well done — you're now familiar with the fundamental mechanics of CSS cascade layers. Next up, we'll look at [the box model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model) in detail.
{{PreviousMenuNext("Learn/CSS/Building_blocks/Cascade_and_inheritance", "Learn/CSS/Building_blocks/The_box_model", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/box_model_tasks/index.md | ---
title: "Test your skills: The box model"
slug: Learn/CSS/Building_blocks/Box_Model_Tasks
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand the [CSS box model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model).
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Task 1
In this task, there are two boxes below, one is using the standard box model, the other the alternate box model. Change the width of the second box by adding declarations to the `.alternate` class, so that it matches the visual width of the first box.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/box-model/box-models.html", '100%', 1100)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/box-model/box-models-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, add to the box:
- A 5px, black, dotted border.
- A top margin of 20px.
- A right margin of 1em.
- A bottom margin of 40px.
- A left margin of 2em.
- Padding on all sides of 1em.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/box-model/mbp.html", '100%', 600)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/box-model/mbp-download.html) to work in your own editor or in an online editor.
## Task 3
In this task, the inline element has a margin, padding and border. However, the lines above and below are overlapping it. What can you add to your CSS to cause the size of the margin, padding, and border to be respected by the other lines, while still keeping the element inline?
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/box-model/inline-block.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/box-model/inline-block-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/writing_modes_tasks/index.md | ---
title: "Test your skills: Writing modes and logical properties"
slug: Learn/CSS/Building_blocks/Writing_Modes_Tasks
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand how to [handle different text directions using writing modes and logical properties in CSS](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions).
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Task 1
In this task, the box is displayed with a horizontal writing mode. Can you add a line of CSS to change it so it uses a vertical writing mode with right to left text?
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/writing-modes/writing-mode.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/writing-modes/writing-mode-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, we want you to use logical properties to replace `width` and `height` in order to maintain the aspect ratio of the box as it is turned vertically.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/writing-modes/logical-width-height.html", '100%', 1100)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/writing-modes/logical-width-height-download.html) to work in your own editor or in an online editor.
## Task 3
In this task, we want you to use logical versions of the margin, border, and padding properties so that the edges of the box relate to the text rather than following top, left, bottom and right.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/writing-modes/logical-mbp.html", '100%', 1100)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/writing-modes/logical-mbp-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/values_tasks/index.md | ---
title: "Test your skills: Values and units"
slug: Learn/CSS/Building_blocks/Values_tasks
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand different types of [values and units used in CSS properties](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units).
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Task 1
In this task, the first list item has been given a background color using a hex color code. Your task is to complete the CSS using the same color in different formats, plus a final list item where you should make the background semi-opaque.
- The second list item should use RGB color.
- The third should use HSL color.
- The fourth should use RGB color but with the alpha channel set to `0.6`.
You can find conversions for the hex color at [this link](https://convertingcolors.com/hex-color-86DEFA.html). You need to figure out how to use the values in CSS. Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/values/color.html", '100%', 1000)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/values/color-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, we want you to set the size of various items of text, as described below:
- The `<h1>` element should be 50 pixels.
- The `<h2>` element should be 2em.
- All `<p>` elements should be 16 pixels.
- A `<p>` element that is directly after an `<h1>` should be 120%.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/values/length.html", '100%', 1000)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/values/length-download.html) to work in your own editor or in an online editor.
## Task 3
In this task, we want you to move the background image so that it is centered horizontally and is 20% from the top of the box.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/values/position.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/values/position-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/images_tasks/index.md | ---
title: "Test your skills: Images and form elements"
slug: Learn/CSS/Building_blocks/Images_tasks
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand how special elements like [images, media and form elements are treated in CSS](/en-US/docs/Learn/CSS/Building_blocks/Images_media_form_elements).
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Task 1
In this task, you have an image that is overflowing the box. We want the image to scale down to fit inside the box without any extra white space, but we do not mind if some part of the image is cropped.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/images/object-fit.html", '100%', 1000)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/images/object-fit-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, you have a simple form. Your task is to make the following changes:
- Use attribute selectors to target the search field and button inside `.myform`.
- Make the form field and button use the same text size as the rest of the form.
- Give the form field and button 10 px of padding.
- Give the button a background of `rebeccapurple`, white foreground, no border and rounded corners of 5px.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/images/form.html", '100%', 600)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/images/form-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/overflow_tasks/index.md | ---
title: "Test your skills: Overflow"
slug: Learn/CSS/Building_blocks/Overflow_Tasks
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand [overflow in CSS and how to manage it](/en-US/docs/Learn/CSS/Building_blocks/Overflowing_content).
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Task 1
In this task, the content is overflowing the box because it has a fixed height. Keep the height but cause the box to have scrollbars only if there is enough text to cause an overflow. Test by removing some of the text from the HTML, that if there is only a small amount of text that does not overflow, no scrollbar appears.

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/overflow/overflow-scroll.html", '100%', 1000)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/overflow/overflow-scroll-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, there is an image in the box that is bigger than the dimensions of the box so that it overflows visibly. Change it so that any image outside of the box is hidden.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/overflow/overflow-hidden.html", '100%', 1200)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/overflow/overflow-hidden-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/backgrounds_and_borders/index.md | ---
title: Backgrounds and borders
slug: Learn/CSS/Building_blocks/Backgrounds_and_borders
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/The_box_model", "Learn/CSS/Building_blocks/Handling_different_text_directions", "Learn/CSS/Building_blocks")}}
In this lesson, we will take a look at some of the creative things you can do with CSS backgrounds and borders. From adding gradients, background images, and rounded corners, backgrounds and borders are the answer to a lot of styling questions in CSS.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn how to style the background and border of boxes.</td>
</tr>
</tbody>
</table>
## Styling backgrounds in CSS
The CSS {{cssxref("background")}} property is a shorthand for a number of background longhand properties that we will meet in this lesson. If you discover a complex background property in a stylesheet, it might seem a little hard to understand as so many values can be passed in at once.
```css
.box {
background:
linear-gradient(
105deg,
rgb(255 255 255 / 20%) 39%,
rgb(51 56 57 / 100%) 96%
) center center / 400px 200px no-repeat,
url(big-star.png) center no-repeat,
rebeccapurple;
}
```
We'll return to how the shorthand works later in the tutorial, but first let's have a look at the different things you can do with backgrounds in CSS, by looking at the individual background properties.
### Background colors
The {{cssxref("background-color")}} property defines the background color on any element in CSS. The property accepts any valid [`<color>`](/en-US/docs/Web/CSS/color_value). A `background-color` extends underneath the content and padding box of the element.
In the example below, we have used various color values to add a background color to the box, a heading, and a {{htmlelement("span")}} element.
**Play around with these, using any available [\<color>](/en-US/docs/Web/CSS/color_value) value.**
{{EmbedGHLiveSample("css-examples/learn/backgrounds-borders/color.html", '100%', 700)}}
### Background images
The {{cssxref("background-image")}} property enables the display of an image in the background of an element. In the example below, we have two boxes — one has a background image which is larger than the box ([balloons.jpg](https://mdn.github.io/css-examples/learn/backgrounds-borders/balloons.jpg)), the other has a small image of a single star ([star.png](https://mdn.github.io/css-examples/learn/backgrounds-borders/star.png)).
This example demonstrates two things about background images. By default, the large image is not scaled down to fit the box, so we only see a small corner of it, whereas the small image is tiled to fill the box.
{{EmbedGHLiveSample("css-examples/learn/backgrounds-borders/background-image.html", '100%', 700)}}
**If you specify a background color in addition to a background image then the image displays on top of the color. Try adding a `background-color` property to the example above to see that in action.**
#### Controlling background-repeat
The {{cssxref("background-repeat")}} property is used to control the tiling behavior of images. The available values are:
- `no-repeat` — stop the background from repeating altogether.
- `repeat-x` — repeat horizontally.
- `repeat-y` — repeat vertically.
- `repeat` — the default; repeat in both directions.
**Try these values out in the example below. We have set the value to `no-repeat` so you will only see one star. Try out the different values — `repeat-x` and `repeat-y` — to see what their effects are.**
{{EmbedGHLiveSample("css-examples/learn/backgrounds-borders/repeat.html", '100%', 600)}}
#### Sizing the background image
The _balloons.jpg_ image used in the initial background images example, is a large image that was cropped due to being larger than the element it is a background of. In this case we could use the {{cssxref("background-size")}} property, which can take {{cssxref("length")}} or {{cssxref("percentage")}} values, to size the image to fit inside the background.
You can also use keywords:
- `cover` — the browser will make the image just large enough so that it completely covers the box area while still retaining its aspect ratio. In this case, part of the image is likely to end up outside the box.
- `contain` — the browser will make the image the right size to fit inside the box. In this case, you may end up with gaps on either side or on the top and bottom of the image, if the aspect ratio of the image is different from that of the box.
In the example below I have used the _balloons.jpg_ image along with length units to size it inside the box. You can see this has distorted the image.
Try the following.
- Change the length units used to modify the size of the background.
- Remove the length units and see what happens when you use `background-size: cover` or `background-size: contain`.
- If your image is smaller than the box, you can change the value of `background-repeat` to repeat the image.
{{EmbedGHLiveSample("css-examples/learn/backgrounds-borders/size.html", '100%', 800)}}
#### Positioning the background image
The {{cssxref("background-position")}} property allows you to choose the position in which the background image appears on the box it is applied to. This uses a coordinate system in which the top-left-hand corner of the box is `(0,0)`, and the box is positioned along the horizontal (`x`) and vertical (`y`) axes.
> **Note:** The default `background-position` value is `(0,0)`.
The most common `background-position` values take two individual values — a horizontal value followed by a vertical value.
You can use keywords such as `top` and `right` (look up the others on the {{cssxref("background-position")}} page):
```css
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: top center;
}
```
And {{cssxref("length", "lengths")}}, and {{cssxref("percentage", "percentages")}}:
```css
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: 20px 10%;
}
```
You can also mix keyword values with lengths or percentages, in which case the first value must refer to the horizontal position or offset and the second vertical. For example:
```css
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: 20px top;
}
```
Finally, you can also use a 4-value syntax in order to indicate a distance from certain edges of the box — the length unit, in this case, is an offset from the value that precedes it. So in the CSS below we are positioning the background 20px from the top and 10px from the right:
```css
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: top 20px right 10px;
}
```
**Use the example below to play around with these values and move the star around inside the box.**
{{EmbedGHLiveSample("css-examples/learn/backgrounds-borders/position.html", '100%', 600)}}
> **Note:** `background-position` is a shorthand for {{cssxref("background-position-x")}} and {{cssxref("background-position-y")}}, which allow you to set the different axis position values individually.
### Gradient backgrounds
A gradient — when used for a background — acts just like an image and is also set by using the {{cssxref("background-image")}} property.
You can read more about the different types of gradients and things you can do with them on the MDN page for the [`<gradient>`](/en-US/docs/Web/CSS/gradient) data type. A fun way to play with gradients is to use one of the many CSS Gradient Generators available on the web, such as [this one](https://cssgradient.io/). You can create a gradient then copy and paste out the source code that generates it.
Try some different gradients in the example below. In the two boxes respectively, we have a linear gradient that is stretched over the whole box, and a radial gradient with a set size, which therefore repeats.
{{EmbedGHLiveSample("css-examples/learn/backgrounds-borders/gradients.html", '100%', 700)}}
### Multiple background images
It is also possible to have multiple background images — you specify multiple `background-image` values in a single property value, separating each one with a comma.
When you do this you may end up with background images overlapping each other. The backgrounds will layer with the last listed background image at the bottom of the stack, and each previous image stacking on top of the one that follows it in the code.
> **Note:** Gradients can be happily mixed with regular background images.
The other `background-*` properties can also have comma-separated values in the same way as `background-image`:
```css
background-image: url(image1.png), url(image2.png), url(image3.png),
url(image4.png);
background-repeat: no-repeat, repeat-x, repeat;
background-position:
10px 20px,
top right;
```
Each value of the different properties will match up to the values in the same position in the other properties. Above, for example, `image1`'s `background-repeat` value will be `no-repeat`. However, what happens when different properties have different numbers of values? The answer is that the smaller numbers of values will cycle — in the above example there are four background images but only two `background-position` values. The first two position values will be applied to the first two images, then they will cycle back around again — `image3` will be given the first position value, and `image4` will be given the second position value.
**Let's play. In the example below I have included two images. To demonstrate the stacking order, try switching which background image comes first in the list. Or play with the other properties to change the position, size, or repeat values.**
{{EmbedGHLiveSample("css-examples/learn/backgrounds-borders/multiple-background-image.html", '100%', 600)}}
### Background attachment
Another option we have available for backgrounds is specifying how they scroll when the content scrolls. This is controlled using the {{cssxref("background-attachment")}} property, which can take the following values:
- `scroll`: causes the element's background to scroll when the page is scrolled. If the element content is scrolled, the background does not move. In effect, the background is fixed to the same position on the page, so it scrolls as the page scrolls.
- `fixed`: causes an element's background to be fixed to the viewport so that it doesn't scroll when the page or element content is scrolled. It will always remain in the same position on the screen.
- `local`: fixes the background to the element it is set on, so when you scroll the element, the background scrolls with it.
The {{cssxref("background-attachment")}} property only has an effect when there is content to scroll, so we've made a demo to demonstrate the differences between the three values — have a look at [background-attachment.html](https://mdn.github.io/learning-area/css/styling-boxes/backgrounds/background-attachment.html) (also [see the source code](https://github.com/mdn/learning-area/tree/main/css/styling-boxes/backgrounds) here).
### Using the background shorthand property
As I mentioned at the beginning of this lesson, you will often see backgrounds specified using the {{cssxref("background")}} property. This shorthand lets you set all of the different properties at once.
If using multiple backgrounds, you need to specify all of the properties for the first background, then add your next background after a comma. In the example below we have a gradient with a size and position, then an image background with `no-repeat` and a position, then a color.
There are a few rules that need to be followed when writing background image shorthand values, for example:
- A `background-color` may only be specified after the final comma.
- The value of `background-size` may only be included immediately after `background-position`, separated with the '/' character, like this: `center/80%`.
Take a look at the MDN page for {{cssxref("background")}} to see all of the considerations.
{{EmbedGHLiveSample("css-examples/learn/backgrounds-borders/background.html", '100%', 900)}}
### Accessibility considerations with backgrounds
When placing text on top of a background image or color, you should take care that you have enough contrast for the text to be legible for your visitors. If specifying an image, and if text will be placed on top of that image, you should also specify a `background-color` that will allow the text to be legible if the image does not load.
Screen readers cannot parse background images; therefore, they should be purely decoration. Any important content should be part of the HTML page and not contained in a background.
## Borders
When learning about the Box Model, we discovered how borders affect the size of our box. In this lesson we will look at how to use borders creatively. Typically when we add borders to an element with CSS we use a shorthand property that sets the color, width, and style of the border in one line of CSS.
We can set a border for all four sides of a box with {{cssxref("border")}}:
```css
.box {
border: 1px solid black;
}
```
Or we can target one edge of the box, for example:
```css
.box {
border-top: 1px solid black;
}
```
The individual properties for these shorthands would be:
```css
.box {
border-width: 1px;
border-style: solid;
border-color: black;
}
```
And for the longhands:
```css
.box {
border-top-width: 1px;
border-top-style: solid;
border-top-color: black;
}
```
> **Note:** These top, right, bottom, and left border properties also have mapped _logical_ properties that relate to the writing mode of the document (e.g. left-to-right or right-to-left text, or top-to-bottom). We'll be exploring these in the next lesson, which covers [handling different text directions](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions).
There are a variety of styles that you can use for borders. In the example below, we have used two different border styles for the box and two different border styles for the heading. Play with the border style, width, and color to see how borders work.
{{EmbedGHLiveSample("css-examples/learn/backgrounds-borders/borders.html", '100%', 800)}}
### Rounded corners
Rounding corners on a box is achieved by using the {{cssxref("border-radius")}} property and associated longhands which relate to each corner of the box. Two lengths or percentages may be used as a value, the first value defining the horizontal radius, and the second the vertical radius. In a lot of cases, you will only pass in one value, which will be used for both.
For example, to make all four corners of a box have a 10px radius:
```css
.box {
border-radius: 10px;
}
```
Or to make the top right corner have a horizontal radius of 1em, and a vertical radius of 10%:
```css
.box {
border-top-right-radius: 1em 10%;
}
```
We have set all four corners in the example below and then changed the values for the top right corner to make it different. You can play with the values to change the corners. Take a look at the property page for {{cssxref("border-radius")}} to see the available syntax options.
{{EmbedGHLiveSample("css-examples/learn/backgrounds-borders/corners.html", '100%', 800)}}
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Backgrounds and borders](/en-US/docs/Learn/CSS/Building_blocks/Test_your_skills_backgrounds_and_borders).
## Summary
We have covered quite a lot here, and you can see that there is quite a lot to adding a background or a border to a box. Do explore the different property pages if you want to find out more about any of the features we have discussed. Each page on MDN has more examples of usage for you to play with and enhance your knowledge.
In the next article, we'll find out how the Writing Mode of your document interacts with your CSS. What happens when the text does not flow from left to right?
{{PreviousMenuNext("Learn/CSS/Building_blocks/The_box_model", "Learn/CSS/Building_blocks/Handling_different_text_directions", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/the_box_model/index.md | ---
title: The box model
slug: Learn/CSS/Building_blocks/The_box_model
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Cascade_layers", "Learn/CSS/Building_blocks/Backgrounds_and_borders", "Learn/CSS/Building_blocks")}}
Everything in CSS has a box around it, and understanding these boxes is key to being able to create more complex layouts with CSS, or to align items with other items. In this lesson, we will take a look at the CSS _Box Model_. You'll get an understanding of how it works and the terminology that relates to it.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn about the CSS Box Model, what makes up the box model and how to
switch to the alternate model.
</td>
</tr>
</tbody>
</table>
## Block and inline boxes
In CSS we have several types of boxes that generally fit into the categories of **block boxes** and **inline boxes**. The type refers to how the box behaves in terms of page flow and in relation to other boxes on the page. Boxes have an **inner display type** and an **outer display type**.
In general, you can set various values for the display type using the {{cssxref("display")}} property, which can have various values.
## Outer display type
If a box has an outer display type of `block`, then:
- The box will break onto a new line.
- The {{cssxref("width")}} and {{cssxref("height")}} properties are respected.
- Padding, margin and border will cause other elements to be pushed away from the box.
- If {{cssxref("width")}} is not specified, the box will extend in the inline direction to fill the space available in its container. In most cases, the box will become as wide as its container, filling up 100% of the space available.
Some HTML elements, such as `<h1>` and `<p>`, use `block` as their outer display type by default.
If a box has an outer display type of `inline`, then:
- The box will not break onto a new line.
- The {{cssxref("width")}} and {{cssxref("height")}} properties will not apply.
- Top and bottom padding, margins, and borders will apply but will not cause other inline boxes to move away from the box.
- Left and right padding, margins, and borders will apply and will cause other inline boxes to move away from the box.
Some HTML elements, such as `<a>`, `<span>`, `<em>` and `<strong>` use `inline` as their outer display type by default.
## Inner display type
Boxes also have an _inner_ display type, which dictates how elements inside that box are laid out.
Block and inline layout is the default way things behave on the web. By default and without any other instruction, the elements inside a box are also laid out in **[normal flow](/en-US/docs/Learn/CSS/CSS_layout/Normal_Flow)** and behave as block or inline boxes.
You can change the inner display type for example by setting `display: flex;`. The element will still use the outer display type `block` but this changes the inner display type to `flex`. Any direct children of this box will become flex items and behave according to the [Flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox) specification.
When you move on to learn about CSS Layout in more detail, you will encounter [`flex`](/en-US/docs/Learn/CSS/CSS_layout/Flexbox), and various other inner values that your boxes can have, for example [`grid`](/en-US/docs/Learn/CSS/CSS_layout/Grids).
> **Note:** To read more about the values of display, and how boxes work in block and inline layout, take a look at the MDN guide [Block and Inline Layout](/en-US/docs/Web/CSS/CSS_flow_layout/Block_and_inline_layout_in_normal_flow).
## Examples of different display types
The example below has three different HTML elements, all of which have an outer display type of `block`.
- A paragraph with a border added in CSS. The browser renders this as a block box. The paragraph starts on a new line and extends the entire available width.
- A list, which is laid out using `display: flex`. This establishes flex layout for the children of the container, which are flex items. The list itself is a block box and — like the paragraph — expands to the full container width and breaks onto a new line.
- A block-level paragraph, inside which are two `<span>` elements. These elements would normally be `inline`, however, one of the elements has a class of "block" which gets set to `display: block`.
{{EmbedGHLiveSample("css-examples/learn/box-model/block.html", '100%', 1100)}}
In the next example, we can see how `inline` elements behave.
- The `<span>` elements in the first paragraph are inline by default and so do not force line breaks.
- The `<ul>` element that is set to `display: inline-flex` creates an inline box containing some flex items.
- The two paragraphs are both set to `display: inline`. The inline flex container and paragraphs all run together on one line rather than breaking onto new lines (as they would do if they were displaying as block-level elements).
**To toggle between the display modes, you can change `display: inline` to `display: block` or `display: inline-flex` to `display: flex`.**
{{EmbedGHLiveSample("css-examples/learn/box-model/inline.html", '100%', 1100)}}
The key thing to remember for now is: Changing the value of the `display` property can change whether the outer display type of a box is block or inline. This changes the way it displays alongside other elements in the layout.
## What is the CSS box model?
The CSS box model as a whole applies to block boxes and defines how the different parts of a box — margin, border, padding, and content — work together to create a box that you can see on a page. Inline boxes use just _some_ of the behavior defined in the box model.
To add complexity, there is a standard and an alternate box model. By default, browsers use the standard box model.
### Parts of a box
Making up a block box in CSS we have the:
- **Content box**: The area where your content is displayed; size it using properties like {{cssxref("inline-size")}} and {{cssxref("block-size")}} or {{cssxref("width")}} and {{cssxref("height")}}.
- **Padding box**: The padding sits around the content as white space; size it using {{cssxref("padding")}} and related properties.
- **Border box**: The border box wraps the content and any padding; size it using {{cssxref("border")}} and related properties.
- **Margin box**: The margin is the outermost layer, wrapping the content, padding, and border as whitespace between this box and other elements; size it using {{cssxref("margin")}} and related properties.
The below diagram shows these layers:

### The standard CSS box model
In the standard box model, if you set `inline-size` and `block-size` (or `width` and `height`) property values on a box, these values define the `inline-size` and `block-size` (`width` and `height` in horizontal languages) of the _content box_. Any padding and borders are then added to those dimensions to get the total size taken up by the box (see the image below).
If we assume that a box has the following CSS:
```css
.box {
width: 350px;
height: 150px;
margin: 10px;
padding: 25px;
border: 5px solid black;
}
```
The _actual_ space taken up by the box will be 410px wide (350 + 25 + 25 + 5 + 5) and 210px high (150 + 25 + 25 + 5 + 5).

> **Note:** The margin is not counted towards the actual size of the box — sure, it affects the total space that the box will take up on the page, but only the space outside the box. The box's area stops at the border — it does not extend into the margin.
### The alternative CSS box model
In the alternative box model, any width is the width of the visible box on the page. The content area width is that width minus the width for the padding and border (see image below). No need to add up the border and padding to get the real size of the box.
To turn on the alternative model for an element, set `box-sizing: border-box` on it:
```css
.box {
box-sizing: border-box;
}
```
If we assume the box has the same CSS as above:
```css
.box {
width: 350px;
inline-size: 350px;
height: 150px;
block-size: 150px;
margin: 10px;
padding: 25px;
border: 5px solid black;
}
```
Now, the _actual_ space taken up by the box will be 350px in the inline direction and 150px in the block direction.

To use the alternative box model for all of your elements (which is a common choice among developers), set the `box-sizing` property on the `<html>` element and set all other elements to inherit that value:
```css
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
```
To understand the underlying idea, you can read [the CSS Tricks article on box-sizing](https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/).
## Playing with box models
In the example below, you can see two boxes. Both have a class of `.box`, which gives them the same `width`, `height`, `margin`, `border`, and `padding`. The only difference is that the second box has been set to use the alternative box model.
**Can you change the size of the second box (by adding CSS to the `.alternate` class) to make it match the first box in width and height?**
{{EmbedGHLiveSample("css-examples/learn/box-model/box-models.html", '100%', 1100)}}
> **Note:** You can find a solution for this task [here](https://github.com/mdn/css-examples/blob/main/learn/solutions.md#the-box-model).
### Use browser DevTools to view the box model
Your [browser developer tools](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools) can make understanding the box model far easier. If you inspect an element in Firefox's DevTools, you can see the size of the element plus its margin, padding, and border. Inspecting an element in this way is a great way to find out if your box is really the size you think it is!

## Margins, padding, and borders
You've already seen the {{cssxref("margin")}}, {{cssxref("padding")}}, and {{cssxref("border")}} properties at work in the example above. The properties used in that example are **shorthands** and allow us to set all four sides of the box at once. These shorthands also have equivalent longhand properties, which allow control over the different sides of the box individually.
Let's explore these properties in more detail.
### Margin
The margin is an invisible space around your box. It pushes other elements away from the box. Margins can have positive or negative values. Setting a negative margin on one side of your box can cause it to overlap other things on the page. Whether you are using the standard or alternative box model, the margin is always added after the size of the visible box has been calculated.
We can control all margins of an element at once using the {{cssxref("margin")}} property, or each side individually using the equivalent longhand properties:
- {{cssxref("margin-top")}}
- {{cssxref("margin-right")}}
- {{cssxref("margin-bottom")}}
- {{cssxref("margin-left")}}
**In the example below, try changing the margin values to see how the box is pushed around due to the margin creating or removing space (if it is a negative margin) between this element and the containing element.**
{{EmbedGHLiveSample("css-examples/learn/box-model/margin.html", '100%', 800)}}
#### Margin collapsing
Depending on whether two elements whose margins touch have positive or negative margins, the results will be different:
- Two positive margins will combine to become one margin. Its size will be equal to the largest individual margin.
- Two negative margins will collapse and the smallest (furthest from zero) value will be used.
- If one margin is negative, its value will be _subtracted_ from the total.
In the example below, we have two paragraphs. The top paragraph has a `margin-bottom` of 50 pixels, the other has a `margin-top` of 30 pixels. The margins have collapsed together so the actual margin between the boxes is 50 pixels and not the total of the two margins.
**You can test this by setting the `margin-top` of paragraph two to 0. The visible margin between the two paragraphs will not change — it retains the 50 pixels set in the `margin-bottom` of paragraph one. If you set it to -10px, you'll see that the overall margin becomes 40px — it subtracts from the 50px.**
{{EmbedGHLiveSample("css-examples/learn/box-model/margin-collapse.html", '100%', 800)}}
A number of rules dictate when margins do and do not collapse. For further information see the detailed page on [mastering margin collapsing](/en-US/docs/Web/CSS/CSS_box_model/Mastering_margin_collapsing). The main thing to remember is that margin collapsing is a thing that happens if you are creating space with margins and don't get the space you expect.
### Borders
The border is drawn between the margin and the padding of a box. If you are using the standard box model, the size of the border is added to the `width` and `height` of the content box. If you are using the alternative box model, then the bigger the border is, the smaller the content box is, as the border takes up some of that available `width` and `height` of the element box.
For styling borders, there are a large number of properties — there are four borders, and each border has a style, width, and color that we might want to manipulate.
You can set the width, style, or color of all four borders at once using the {{cssxref("border")}} property.
To set the properties of each side individually, use:
- {{cssxref("border-top")}}
- {{cssxref("border-right")}}
- {{cssxref("border-bottom")}}
- {{cssxref("border-left")}}
To set the width, style, or color of all sides, use:
- {{cssxref("border-width")}}
- {{cssxref("border-style")}}
- {{cssxref("border-color")}}
To set the width, style, or color of a single side, use one of the more granular longhand properties:
- {{cssxref("border-top-width")}}
- {{cssxref("border-top-style")}}
- {{cssxref("border-top-color")}}
- {{cssxref("border-right-width")}}
- {{cssxref("border-right-style")}}
- {{cssxref("border-right-color")}}
- {{cssxref("border-bottom-width")}}
- {{cssxref("border-bottom-style")}}
- {{cssxref("border-bottom-color")}}
- {{cssxref("border-left-width")}}
- {{cssxref("border-left-style")}}
- {{cssxref("border-left-color")}}
In the example below, we have used various shorthands and longhands to create borders. Play around with the different properties to check that you understand how they work. The MDN pages for the border properties give you information about the different available border styles.
{{EmbedGHLiveSample("css-examples/learn/box-model/border.html", '100%', 700)}}
### Padding
The padding sits between the border and the content area and is used to push the content away from the border. Unlike margins, you cannot have a negative padding. Any background applied to your element will display behind the padding.
The {{cssxref("padding")}} property controls the padding on all sides of an element. To control each side individually, use these longhand properties:
- {{cssxref("padding-top")}}
- {{cssxref("padding-right")}}
- {{cssxref("padding-bottom")}}
- {{cssxref("padding-left")}}
In the example below, you can change the values for padding on the class `.box` to see that this changes where the text begins in relation to the box. You can also change the padding on the class `.container` to create space between the container and the box. You can change the padding on any element to create space between its border and whatever is inside the element.
{{EmbedGHLiveSample("css-examples/learn/box-model/padding.html", '100%', 700)}}
## The box model and inline boxes
All of the above fully applies to block boxes. Some of the properties can apply to inline boxes too, such as those created by a `<span>` element.
In the example below, we have a `<span>` inside a paragraph. We have applied a `width`, `height`, `margin`, `border`, and `padding` to it. You can see that the width and height are ignored. The top and bottom margin, padding, and border are respected but don't change the relationship of other content to our inline box. The padding and border overlap other words in the paragraph. The left and right padding, margins, and borders move other content away from the box.
{{EmbedGHLiveSample("css-examples/learn/box-model/inline-box-model.html", '100%', 700)}}
## Using display: inline-block
`display: inline-block` is a special value of `display`, which provides a middle ground between `inline` and `block`. Use it if you do not want an item to break onto a new line, but do want it to respect `width` and `height` and avoid the overlapping seen above.
An element with `display: inline-block` does a subset of the block things we already know about:
- The `width` and `height` properties are respected.
- `padding`, `margin`, and `border` will cause other elements to be pushed away from the box.
It does not, however, break onto a new line, and will only become larger than its content if you explicitly add `width` and `height` properties.
**In this next example, we have added `display: inline-block` to our `<span>` element. Try changing this to `display: block` or removing the line completely to see the difference in display models.**
{{EmbedGHLiveSample("css-examples/learn/box-model/inline-block.html", '100%', 800)}}
Where this can be useful is when you want to give a link a larger hit area by adding `padding`. `<a>` is an inline element like `<span>`; you can use `display: inline-block` to allow padding to be set on it, making it easier for a user to click the link.
You see this fairly frequently in navigation bars. The navigation below is displayed in a row using flexbox and we have added padding to the `<a>` element as we want to be able to change the `background-color` when the `<a>` is hovered. The padding appears to overlap the border on the `<ul>` element. This is because the `<a>` is an inline element.
**Add `display: inline-block` to the rule with the `.links-list a` selector, and you will see how it fixes this issue by causing the padding to be respected by other elements.**
{{EmbedGHLiveSample("css-examples/learn/box-model/inline-block-nav.html", '100%', 700)}}
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: The box model](/en-US/docs/Learn/CSS/Building_blocks/Box_Model_Tasks).
## Summary
That's most of what you need to understand about the box model. You may want to return to this lesson in the future if you ever find yourself confused about how big boxes are in your layout.
In the next article, we'll take a look at how [backgrounds and borders](/en-US/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders) can be used to make your plain boxes look more interesting.
{{PreviousMenuNext("Learn/CSS/Building_blocks/Cascade_layers", "Learn/CSS/Building_blocks/Backgrounds_and_borders", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/sizing_items_in_css/index.md | ---
title: Sizing items in CSS
slug: Learn/CSS/Building_blocks/Sizing_items_in_CSS
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Values_and_units", "Learn/CSS/Building_blocks/Images_media_form_elements", "Learn/CSS/Building_blocks")}}
In the various lessons so far, you have come across a number of ways to size items on a web page using CSS. Understanding how big the different features in your design will be is important. So, in this lesson we will summarize the various ways elements get a size via CSS and define a few terms about sizing that will help you in the future.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To understand the different ways we can size things in CSS.</td>
</tr>
</tbody>
</table>
## The natural or intrinsic size of things
HTML Elements have a natural size, set before they are affected by any CSS. A straightforward example is an image. An image file contains sizing information, described as its **intrinsic size**. This size is determined by the image _itself_, not by any formatting we happen to apply.
If you place an image on a page and do not change its height or width, either by using attributes on the `<img>` tag or else by CSS, it will be displayed using that intrinsic size. We have given the image in the example below a border so that you can see the extent of its size as defined in its file.
{{EmbedGHLiveSample("css-examples/learn/sizing/intrinsic-image.html", '100%', 600)}}
An empty {{htmlelement("div")}}, on the other hand, has no size of its own. If you add a {{htmlelement("div")}} to your HTML with no content, then give it a border as we did with the image, you will see a line on the page. This is the collapsed border on the element — there is no content to hold it open. In our example below, that border stretches to the width of the container, because it is a block level element, a behavior that should be starting to become familiar to you. It has no height (or size in the block dimension) because there is no content.
{{EmbedGHLiveSample("css-examples/learn/sizing/intrinsic-text.html", '100%', 500)}}
In the example above, try adding some text inside the empty element. The border now contains that text because the height of the element is defined by the content. Therefore the size of this `<div>` in the block dimension comes from the size of the content. Again, this is the intrinsic size of the element — its size is defined by its content.
## Setting a specific size
We can, of course, give elements in our design a specific size. When a size is given to an element (the content of which then needs to fit into that size) we refer to it as an **extrinsic size**. Take our `<div>` from the example above — we can give it specific {{cssxref("width")}} and {{cssxref("height")}} values, and it will now have that size no matter what content is placed into it. As we discovered in [our previous lesson on overflow](/en-US/docs/Learn/CSS/Building_blocks/Overflowing_content), a set height can cause content to overflow if there is more content than the element has space to fit inside it.
{{EmbedGHLiveSample("css-examples/learn/sizing/height.html", '100%', 600)}}
Due to this problem of overflow, fixing the height of elements with lengths or percentages is something we need to do very carefully on the web.
### Using percentages
In many ways, percentages act like length units, and as we [discussed in the lesson on values and units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#percentages), they can often be used interchangeably with lengths. When using a percentage you need to be aware what it is a percentage _of_. In the case of a box inside another container, if you give the child box a percentage width it will be a percentage of the width of the parent container.
{{EmbedGHLiveSample("css-examples/learn/sizing/percent-width.html", '100%', 600)}}
This is because percentages resolve against the size of the containing block. With no percentage applied, our `<div>` would take up 100% of the available space, as it is a block level element. If we give it a percentage width, this becomes a percentage of the space it would normally fill.
### Percentage margins and padding
If you set `margins` and `padding` as a percentage, you may notice some strange behavior. In the below example we have a box. We have given the inner box a {{cssxref("margin")}} of 10% and a {{cssxref("padding")}} of 10%. The padding and margin on the top and bottom of the box are the same size as the padding and margin on the left and right.
{{EmbedGHLiveSample("css-examples/learn/sizing/percent-mp.html", '100%', 800)}}
You might expect for example the percentage top and bottom margins to be a percentage of the element's height, and the percentage left and right margins to be a percentage of the element's width. However, this is not the case!
When you use margin and padding set in percentages, the value is calculated from the **inline size** of the containing block — therefore the width when working in a horizontal language. In our example, all of the margins and padding are 10% of the width. This means you can have equal-sized margins and padding all around the box. This is a fact worth remembering if you do use percentages in this way.
## min- and max- sizes
In addition to giving things a fixed size, we can ask CSS to give an element a minimum or a maximum size. If you have a box that might contain a variable amount of content, and you always want it to be _at least_ a certain height, you could set the {{cssxref("min-height")}} property on it. The box will always be at least this height, but will then grow taller if there is more content than the box has space for at its minimum height.
In the example below you can see two boxes, both with a defined `min-height` of 150 pixels. The box on the left is 150 pixels tall; the box on the right has content that needs more room, and so it has grown taller than 150 pixels.
{{EmbedGHLiveSample("css-examples/learn/sizing/min-height.html", '100%', 800)}}
This is very useful for dealing with variable amounts of content while avoiding overflow.
A common use of {{cssxref("max-width")}} is to cause images to scale down if there is not enough space to display them at their intrinsic width while making sure they don't become larger than that width.
As an example, if you were to set `width: 100%` on an image, and its intrinsic width was smaller than its container, the image would be forced to stretch and become larger, causing it to look pixelated.
If you instead use `max-width: 100%`, and its intrinsic width is smaller than its container, the image will not be forced to stretch and become larger, thus preventing pixelation.
In the example below, we have used the same image three times. The first image has been given `width: 100%` and is in a container which is larger than it, therefore it stretches to the container width. The second image has `max-width: 100%` set on it and therefore does not stretch to fill the container. The third box contains the same image again, also with `max-width: 100%` set; in this case you can see how it has scaled down to fit into the box.
{{EmbedGHLiveSample("css-examples/learn/sizing/max-width.html", '100%', 800)}}
This technique is used to make images _responsive_, so that when viewed on a smaller device they scale down appropriately. You should, however, not use this technique to load really large images and then scale them down in the browser. Images should be appropriately sized to be no larger than they need to be for the largest size they are displayed in the design. Downloading overly large images will cause your site to become slow, and it can cost users more money if they are on a metered connection.
> **Note:** Find out more about [responsive image techniques](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images).
## Viewport units
The viewport — which is the visible area of your page in the browser you are using to view a site — also has a size. In CSS we have units which relate to the size of the viewport — the `vw` unit for viewport width, and `vh` for viewport height. Using these units you can size something relative to the viewport of the user.
`1vh` is equal to 1% of the viewport height, and `1vw` is equal to 1% of the viewport width. You can use these units to size boxes, but also text. In the example below we have a box which is sized as 20vh and 20vw. The box contains a letter `A`, which has been given a {{cssxref("font-size")}} of 10vh.
{{EmbedGHLiveSample("css-examples/learn/sizing/vw-vh.html", '100%', 600)}}
**If you change the `vh` and `vw` values this will change the size of the box or font; changing the viewport size will also change their sizes because they are sized relative to the viewport. To see the example change when you change the viewport size you will need to load the example in a new browser window that you can resize (as the embedded `<iframe>` that contains the example shown above is its viewport). [Open the example](https://mdn.github.io/css-examples/learn/sizing/vw-vh.html), resize the browser window, and observe what happens to the size of the box and text.**
Sizing things according to the viewport can be useful in your designs. For example, if you want a full-page hero section to show before the rest of your content, making that part of your page 100vh high will push the rest of the content below the viewport, meaning that it will only appear once the document is scrolled.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Sizing](/en-US/docs/Learn/CSS/Building_blocks/Sizing_tasks).
## Summary
This lesson has given you a rundown of some key issues that you might run into when sizing things on the web. When you move onto [CSS Layout](/en-US/docs/Learn/CSS/CSS_layout), sizing will become very important in mastering the different layout methods, so it is worth understanding the concepts here before moving on.
In the next article, we'll take a look at how [images, media, and form elements](/en-US/docs/Learn/CSS/Building_blocks/Images_media_form_elements) are treated in CSS.
{{PreviousMenuNext("Learn/CSS/Building_blocks/Values_and_units", "Learn/CSS/Building_blocks/Images_media_form_elements", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/cascade_tasks/index.md | ---
title: "Test your skills: The Cascade"
slug: Learn/CSS/Building_blocks/Cascade_tasks
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand universal property values for [controlling inheritance in CSS](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance).
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Task 1
In this task, we want you to use one of the special values we looked at in the [controlling inheritance](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#controlling_inheritance) section. To write a declaration in a new rule that will reset the background color back to white, without using an actual color value.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/cascade/cascade.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/cascade/cascade-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, we want you to make your changes by leveraging the [order of cascade layers](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#order_of_cascade_layers) section. Edit an existing declaration, without touching the lightgreen declaration, using the cascade layer order to make the links rebeccapurple.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/cascade/cascadelayer.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/cascade/cascadelayer-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/cascade_and_inheritance/index.md | ---
title: Cascade, specificity, and inheritance
slug: Learn/CSS/Building_blocks/Cascade_and_inheritance
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Combinators", "Learn/CSS/Building_blocks/Cascade_layers", "Learn/CSS/Building_blocks")}}
The aim of this lesson is to develop your understanding of some of the most fundamental concepts of CSS — the cascade, specificity, and inheritance — which control how CSS is applied to HTML and how conflicts between style declarations are resolved.
While working through this lesson may seem less relevant immediately and a little more academic than some other parts of the course, an understanding of these concepts will save you from a lot of pain later on! We encourage you to work through this section carefully and check that you understand the concepts before moving on.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn about the cascade and specificity, and how inheritance works in
CSS.
</td>
</tr>
</tbody>
</table>
## Conflicting rules
CSS stands for **Cascading Style Sheets**, and that first word _cascading_ is incredibly important to understand — the way that the cascade behaves is key to understanding CSS.
At some point, you will be working on a project and you will find that the CSS you thought should be applied to an element is not working. Often, the problem is that you create two rules that apply different values of the same property to the same element. [**Cascade**](/en-US/docs/Web/CSS/Cascade) and the closely-related concept of [**specificity**](/en-US/docs/Web/CSS/Specificity) are mechanisms that control which rule applies when there is such a conflict. The rule that's styling your element may not be the one you expect, so you need to understand how these mechanisms work.
Also significant here is the concept of [**inheritance**](/en-US/docs/Web/CSS/Inheritance), which means that some CSS properties by default inherit values set on the current element's parent element and some don't. This can also cause some behavior that you might not expect.
Let's start by taking a quick look at the key things we are dealing with, then we'll look at each in turn and see how they interact with each other and your CSS. These can seem like a tricky set of concepts to understand. As you get more practice writing CSS, the way it works will become more obvious to you.
### Cascade
Stylesheets [**cascade**](/en-US/docs/Web/CSS/Cascade) — at a very simple level, this means that the origin, the cascade layer, and the order of CSS rules matter. When two rules from the same cascade layer apply and both have equal specificity, the one that is defined last in the stylesheet is the one that will be used.
In the below example, we have two rules that could apply to the `<h1>` element. The `<h1>` content ends up being colored blue. This is because both the rules are from the same source, have an identical element selector, and therefore, carry the same specificity, but the last one in the source order wins.
{{EmbedGHLiveSample("css-examples/learn/cascade/cascade-simple.html", '100%', 500)}}
### Specificity
[Specificity](/en-US/docs/Web/CSS/Specificity) is the algorithm that the browser uses to decide which property value is applied to an element. If multiple style blocks have different selectors that configure the same property with different values and target the same element, specificity decides the property value that gets applied to the element. Specificity is basically a measure of how specific a selector's selection will be:
- An element selector is less specific; it will select all elements of that type that appear on a page, so it has less weight. Pseudo-element selectors have the same specificity as regular element selectors.
- A class selector is more specific; it will select only the elements on a page that have a specific `class` attribute value, so it has more weight. Attribute selectors and pseudo-classes have the same weight as a class.
Below, we again have two rules that could apply to the `<h1>` element. The `<h1>` content below ends up being colored red because the class selector `main-heading` gives its rule a higher specificity. So even though the rule with the `<h1>` element selector appears further down in the source order, the one with the higher specificity, defined using the class selector, will be applied.
{{EmbedGHLiveSample("css-examples/learn/cascade/specificity-simple.html", '100%', 600)}}
We'll explain the specificity algorithm later on.
### Inheritance
Inheritance also needs to be understood in this context — some CSS property values set on parent elements are inherited by their child elements, and some aren't.
For example, if you set a `color` and `font-family` on an element, every element inside it will also be styled with that color and font, unless you've applied different color and font values directly to them.
{{EmbedGHLiveSample("css-examples/learn/cascade/inheritance-simple.html", '100%', 650)}}
Some properties do not inherit — for example, if you set a {{cssxref("width")}} of 50% on an element, all of its descendants do not get a width of 50% of their parent's width. If this was the case, CSS would be very frustrating to use!
> **Note:** On MDN CSS property reference pages, you can find a technical information box called "Formal definition", which lists a number of data points about that property, including whether it is inherited or not. See the [color property Formal definition section](/en-US/docs/Web/CSS/color#formal_definition) as an example.
## Understanding how the concepts work together
These three concepts (cascade, specificity, and inheritance) together control which CSS applies to what element. In the sections below, we'll see how they work together. It can sometimes seem a little bit complicated, but you will start to remember them as you get more experienced with CSS, and you can always look up the details if you forget! Even experienced developers don't remember all the details.
The following video shows how you can use the Firefox DevTools to inspect a page's cascade, specificity, and more:
{{EmbedYouTube("Sp9ZfSvpf7A")}}
## Understanding inheritance
We'll start with inheritance. In the example below, we have a {{HTMLElement("ul")}} element with two levels of unordered lists nested inside it. We have given the outer `<ul>` a border, padding, and font color.
The `color` property is an inherited property. So, the `color` property value is applied to the direct children and also to the indirect children — the immediate child `<li>`s and those inside the first nested list. We have then added the class `special` to the second nested list and applied a different color to it. This then inherits down through its children.
{{EmbedGHLiveSample("css-examples/learn/cascade/inheritance.html", '100%', 1100)}}
Properties like `width` (as mentioned earlier), `margin`, `padding`, and `border` are not inherited properties. If a border were to be inherited by the children in this list example, every single list and list item would gain a border — probably not an effect we would ever want!
Though every CSS property page lists whether or not the property is inherited, you can often guess the same intuitively if you know what aspect the property value will style.
### Controlling inheritance
CSS provides five special universal property values for controlling inheritance. Every CSS property accepts these values.
- {{cssxref("inherit")}}
- : Sets the property value applied to a selected element to be the same as that of its parent element. Effectively, this "turns on inheritance".
- {{cssxref("initial")}}
- : Sets the property value applied to a selected element to the [initial value](/en-US/docs/Web/CSS/initial_value) of that property.
- {{cssxref("revert")}}
- : Resets the property value applied to a selected element to the browser's default styling rather than the defaults applied to that property. This value acts like {{cssxref("unset")}} in many cases.
- {{cssxref("revert-layer")}}
- : Resets the property value applied to a selected element to the value established in a previous [cascade layer](/en-US/docs/Web/CSS/@layer).
- {{cssxref("unset")}}
- : Resets the property to its natural value, which means that if the property is naturally inherited it acts like `inherit`, otherwise it acts like `initial`.
> **Note:** See [Origin types](/en-US/docs/Web/CSS/Cascade#origin_types) for more information on each of these and how they work.
We can look at a list of links and explore how universal values work. The live example below allows you to play with the CSS and see what happens when you make changes. Playing with code really is the best way to better understand HTML and CSS.
For example:
1. The second list item has the class `my-class-1` applied. This sets the color of the `<a>` element nested inside to `inherit`. If you remove the rule, how does it change the color of the link?
2. Do you understand why the third and fourth links are the color that they are? The third link is set to `initial`, which means it uses the initial value of the property (in this case black) and not the browser default for links, which is blue. The fourth is set to `unset` which means that the link text uses the color of the parent element, green.
3. Which of the links will change color if you define a new color for the `<a>` element — for example `a { color: red; }`?
4. After reading the next section on resetting all properties, come back and change the `color` property to `all`. Notice how the second link is on a new line and has a bullet. What properties do you think were inherited?
{{EmbedGHLiveSample("css-examples/learn/cascade/keywords.html", '100%', 800)}}
### Resetting all property values
The CSS shorthand property [`all`](/en-US/docs/Web/CSS/all) can be used to apply one of these inheritance values to (almost) all properties at once. Its value can be any one of the inheritance values (`inherit`, `initial`, `revert`, `revert-layer`, or `unset`). It's a convenient way to undo changes made to styles so that you can get back to a known starting point before beginning new changes.
In the below example, we have two blockquotes. The first has styling applied to the blockquote element itself. The second has a class applied to the blockquote, which sets the value of `all` to `unset`.
{{EmbedGHLiveSample("css-examples/learn/cascade/all.html", '100%', 800)}}
Try setting the value of `all` to some of the other available values and observe what the difference is.
## Understanding the cascade
We now understand that inheritance is why a paragraph nested deep in the structure of your HTML is the same color as the CSS applied to the body. From the introductory lessons, we have an understanding of how to change the CSS applied to something at any point in the document — whether by assigning CSS to an element or by creating a class. We will now look at how cascade defines which CSS rules apply when more than one style block apply the same property, but with different values, to the same element.
There are three factors to consider, listed here in increasing order of importance. Later ones overrule earlier ones:
1. **Source order**
2. **Specificity**
3. **Importance**
We will look at these to see how browsers figure out exactly what CSS should be applied.
### Source order
We have already seen how source order matters to the cascade. If you have more than one rule, all of which have exactly the same weight, then the one that comes last in the CSS will win. You can think of this as: the rule that is nearer the element itself overwrites the earlier ones until the last one wins and gets to style the element.
Source order only matters when the specificity weight of the rules is the same, so let's look at specificity:
### Specificity
You will often run into a situation where you know that a rule comes later in the stylesheet, but an earlier, conflicting rule is applied. This happens because the earlier rule has a **higher specificity** — it is more specific, and therefore, is being chosen by the browser as the one that should style the element.
As we saw earlier in this lesson, a class selector has more weight than an element selector, so the properties defined in the class style block will override those defined in the element style block.
Something to note here is that although we are thinking about selectors and the rules that are applied to the text or component they select, it isn't the entire rule that is overwritten, only the properties that are declared in multiple places.
This behavior helps avoid repetition in your CSS. A common practice is to define generic styles for the basic elements, and then create classes for those that are different. For example, in the stylesheet below, we have defined generic styles for level 2 headings, and then created some classes that change only some of the properties and values. The values defined initially are applied to all headings, then the more specific values are applied to the headings with the classes.
{{EmbedGHLiveSample("css-examples/learn/cascade/mixing-rules.html", '100%', 1000)}}
Let's now have a look at how the browser will calculate specificity. We already know that an element selector has low specificity and can be overwritten by a class. Essentially a value in points is awarded to different types of selectors, and adding these up gives you the weight of that particular selector, which can then be assessed against other potential matches.
The amount of specificity a selector has is measured using three different values (or components), which can be thought of as ID, CLASS, and ELEMENT columns in the hundreds, tens, and ones place:
- **Identifiers**: Score one in this column for each ID selector contained inside the overall selector.
- **Classes**: Score one in this column for each class selector, attribute selector, or pseudo-class contained inside the overall selector.
- **Elements**: Score one in this column for each element selector or pseudo-element contained inside the overall selector.
> **Note:** The universal selector ([`*`](/en-US/docs/Web/CSS/Universal_selectors)), [combinators](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Combinators) (`+`, `>`, `~`, ' '), and specificity adjustment selector ([`:where()`](/en-US/docs/Web/CSS/:where)) along with its parameters, have no effect on specificity.
The negation ([`:not()`](/en-US/docs/Web/CSS/:not)), relational selector ([`:has()`](/en-US/docs/Web/CSS/:has)), the matches-any ([`:is()`](/en-US/docs/Web/CSS/:is)) pseudo-classes, and [CSS nesting](/en-US/docs/Web/CSS/CSS_nesting/Nesting_and_specificity) themselves don't add to specificity, but their parameters or nested rules do. The specificity weight that each contributes to the specificity algorithm is the specificity weight of the selector in the parameter or nested rule with the greatest weight.
The following table shows a few isolated examples to get you in the mood. Try going through these, and make sure you understand why they have the specificity that we have given them. We've not covered selectors in detail yet, but you can find details of each selector on the MDN [selectors reference](/en-US/docs/Web/CSS/CSS_selectors/Selectors_and_combinators).
| Selector | Identifiers | Classes | Elements | Total specificity |
| ----------------------------------------- | ----------- | ------- | -------- | ----------------- |
| `h1` | 0 | 0 | 1 | 0-0-1 |
| `h1 + p::first-letter` | 0 | 0 | 3 | 0-0-3 |
| `li > a[href*="en-US"] > .inline-warning` | 0 | 2 | 2 | 0-2-2 |
| `#identifier` | 1 | 0 | 0 | 1-0-0 |
| `button:not(#mainBtn, .cta`) | 1 | 0 | 1 | 1-0-1 |
Before we move on, let's look at an example in action.
{{EmbedGHLiveSample("css-examples/learn/cascade/specificity-boxes.html", '100%', 800)}}
So what's going on here? First of all, we are only interested in the first seven rules of this example, and as you'll notice, we have included their specificity values in a comment before each one.
- The first two selectors are competing over the styling of the link's background color. The second one wins and makes the background color blue because it has an extra ID selector in the chain: its specificity is 2-0-1 vs. 1-0-1.
- Selectors 3 and 4 are competing over the styling of the link's text color. The second one wins and makes the text white because although it has one less element selector, the missing selector is swapped out for a class selector, which has more weight than infinity element selectors. The winning specificity is 1-1-3 vs. 1-0-4.
- Selectors 5–7 are competing over the styling of the link's border when hovered. Selector 6 clearly loses to selector 5 with a specificity of 0-2-3 vs. 0-2-4; it has one fewer element selectors in the chain. Selector 7, however, beats both selectors 5 and 6 because it has the same number of sub-selectors in the chain as selector 5, but an element has been swapped out for a class selector. So the winning specificity is 0-3-3 vs. 0-2-3 and 0-2-4.
> **Note:** Each selector type has its own level of specificity that cannot be overwritten by selectors with a lower specificity level. For example, a _million_ **class** selectors combined would not be able to overwrite the specificity of _one_ **id** selector.
>
> The best way to evaluate specificity is to score the specificity levels individually starting from the highest and moving on to the lowest when necessary. Only when there is a tie between selector scores within a specificity column do you need to evaluate the next column down; otherwise, you can disregard the lower specificity selectors since they can never overwrite the higher specificity selectors.
### Inline styles
Inline styles, that is, the style declaration inside a [`style`](/en-US/docs/Web/HTML/Global_attributes#style) attribute, take precedence over all normal styles, no matter the specificity. Such declarations don't have selectors, but their specificity can be construed as 1-0-0-0; always more than any other specificity weight no matter how many IDs are in the selectors.
### !important
There is a special piece of CSS that you can use to overrule all of the above calculations, even inline styles - the `!important` flag. However, you should be very careful while using it. This flag is used to make an individual property and value pair the most specific rule, thereby overriding the normal rules of the cascade, including normal inline styles.
> **Note:** It is useful to know that the `!important` flag exists so that you know what it is when you come across it in other people's code. **However, we strongly recommend that you never use it unless you absolutely have to.** The `!important` flag changes the way the cascade normally works, so it can make debugging CSS problems really hard to work out, especially in a large stylesheet.
Take a look at this example where we have two paragraphs, one of which has an ID.
{{EmbedGHLiveSample("css-examples/learn/cascade/important.html", '100%', 800)}}
Let's walk through this to see what's happening — try removing some of the properties to see what happens if you are finding it hard to understand:
1. You'll see that the third rule's {{cssxref("color")}} and {{cssxref("padding")}} values have been applied, but the {{cssxref("background-color")}} hasn't. Why? Really, all three should surely apply because rules later in the source order generally override earlier rules.
2. However, the rules above it win because class selectors have higher specificity than element selectors.
3. Both elements have a [`class`](/en-US/docs/Web/HTML/Global_attributes#class) of `better`, but the 2nd one has an [`id`](/en-US/docs/Web/HTML/Global_attributes#id) of `winning` too. Since IDs have an _even higher_ specificity than classes (you can only have one element with each unique ID on a page, but many elements with the same class — ID selectors are _very specific_ in what they target), the red background color and the 1px black border should both be applied to the 2nd element, with the first element getting the gray background color, and no border, as specified by the class.
4. The 2nd element _does_ get the red background color, but no border. Why? Because of the `!important` flag in the second rule. Adding the `!important` flag after `border: none` means that this declaration will win over the `border` value in the previous rule, even though the ID selector has higher specificity.
> **Note:** The only way to override an important declaration is to include another important declaration with the _same specificity_ later in the source order, or one with higher specificity, or to include an important declaration in a prior cascade layer (we haven't covered cascade layers yet).
One situation in which you may have to use the `!important` flag is when you are working on a CMS where you can't edit the core CSS modules, and you really want to override an inline style or an important declaration that can't be overridden in any other way. But really, don't use it if you can avoid it.
## The effect of CSS location
Finally, it is important to note that the precedence of a CSS declaration depends on what stylesheet and cascade layer it is specified in.
It is possible for users to set custom stylesheets to override the developer's styles. For example, a visually impaired user might want to set the font size on all web pages they visit to be double the normal size to allow for easier reading.
It is also possible to declare developer styles in cascade layers: you can make non-layered styles override styles declared in layers or you can make styles declared in later layers override styles from earlier declared layers. For example, as a developer you may not be able to edit a third-party stylesheet, but you can import the external stylesheet into a cascade layer so that all of your styles easily override the imported styles without worrying about third-party selector specificity.
### Order of overriding declarations
Conflicting declarations will be applied in the following order, with later ones overriding earlier ones:
1. Declarations in user agent style sheets (e.g., the browser's default styles, used when no other styling is set).
2. Normal declarations in user style sheets (custom styles set by a user).
3. Normal declarations in author style sheets (these are the styles set by us, the web developers).
4. Important declarations in author style sheets.
5. Important declarations in user style sheets.
6. Important declarations in user agent style sheets.
> **Note:** The order of precedence is inverted for styles flagged with `!important`. It makes sense for web developers' stylesheets to override user stylesheets, so the design can be kept as intended; however, sometimes users have good reasons to override web developer styles, as mentioned above, and this can be achieved by using `!important` in their rules.
### Order of cascade layers
Even though [cascade layers](/en-US/docs/Web/CSS/@layer) is an advanced topic and you might not use this feature right away, it's important to understand how layers cascade.
When you declare CSS in cascade layers, the order of precedence is determined by the order in which the layers are declared. CSS styles declared outside of any layer are combined together, in the order in which those styles are declared, into an unnamed layer, as if it were the last declared layer. With competing normal (not important) styles, later layers take precedence over earlier defined layers. For styles flagged with `!important`, however, the order is reversed, with important styles in earlier layers taking precedence over important styles declared in subsequent layers or outside of any layer. Inline styles take precedence over all author styles, no matter the layer.
When you have multiple style blocks in different layers providing competing values for a property on a single element, the order in which the layers are declared determines the precedence. Specificity between layers doesn't matter, but specificity within a single layer still does.
{{EmbedGHLiveSample("css-examples/learn/cascade/cascade-layers.html", '100%', 800)}}
Let's discuss a few things from the above example to understand what's happening. Two layers have been declared, `firstLayer` and `secondLayer`, in that order. Even though the specificity in `secondLayer` is the highest, no properties from that declaration are used. Why? Because non-layered normal styles take precedence over layered normal styles, no matter the specificity, and important layered styles take precedence over important styles declared in later layers, again, no matter the specificity.
If you change the first line of CSS in this example to read `@layer secondLayer, firstLayer;`, you will change the layer declaration order, and all the important styles from `firstLayer` will be changed to their respective values in `secondLayer`.
### Scoping proximity
Another advanced topic that you might not use right away but may need to understand in the future is {{CSSxRef("@scope")}}. This is an [at-rule](/en-US/docs/Web/CSS/At-rule) that enables you to create a block of rules that will only apply to a specific subsection of the HTML on your page. For example, you can specify styles that will only apply to {{htmlelement("img")}} elements when they're nested inside elements that have a `feature` class:
```css
@scope (.feature) {
img {
border: 2px solid black;
display: block;
}
}
```
**Scoping proximity** is the mechanism that resolves conflicts between scoped elements. Scoping proximity states that when two scopes have conflicting styles, the style with the smallest number of hops up the DOM tree hierarchy to the scope root wins. See [How `@scope` conflicts are resolved](/en-US/docs/Web/CSS/@scope#how_scope_conflicts_are_resolved) for more details and an example.
> **Note:** Scoping proximity overrules source order but is itself overridden by other, higher-priority criteria such as [importance](/en-US/docs/Web/CSS/important), [layers](/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers), and [specificity](/en-US/docs/Web/CSS/Specificity).
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: The Cascade](/en-US/docs/Learn/CSS/Building_blocks/Cascade_tasks).
## Summary
If you understood most of this article, then well done — you've started getting familiar with the fundamental mechanics of CSS. Next up, we'll take a deeper look at [Cascade Layers](/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers).
If you didn't fully understand the cascade, specificity, and inheritance, then don't worry! This is definitely the most complicated thing we've covered so far in the course and is something that even professional web developers sometimes find tricky. We'd advise that you return to this article a few times as you continue through the course, and keep thinking about it.
Refer back here if you start to come across strange issues with styles not applying as expected. It could be a specificity issue.
{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Combinators", "Learn/CSS/Building_blocks/Cascade_layers", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/debugging_css/index.md | ---
title: Debugging CSS
slug: Learn/CSS/Building_blocks/Debugging_CSS
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Styling_tables", "Learn/CSS/Building_blocks/Organizing", "Learn/CSS/Building_blocks")}}
Sometimes when writing CSS you will encounter an issue where your CSS doesn't seem to be doing what you expect. Perhaps you believe that a certain selector should match an element, but nothing happens, or a box is a different size than you expected. This article will give you guidance on how to go about debugging a CSS problem, and show you how the DevTools included in all modern browsers can help you to find out what is going on.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn the basics of what browser DevTools are, and how to do simple
inspection and editing of CSS.
</td>
</tr>
</tbody>
</table>
## How to access browser DevTools
The article [What are browser developer tools](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools) is an up-to-date guide explaining how to access the tools in various browsers and platforms. While you may choose to mostly develop in a particular browser, and therefore will become most familiar with the tools included in that browser, it is worth knowing how to access them in other browsers. This will help if you are seeing different rendering between multiple browsers.
You will also find that browsers have chosen to focus on different areas when creating their DevTools. For example, in Firefox there are some excellent tools for working visually with CSS Layout, allowing you to inspect and edit [Grid Layouts](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_grid_layouts/index.html), [Flexbox](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_flexbox_layouts/index.html), and [Shapes](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/edit_css_shapes/index.html). However, all of the different browsers have similar fundamental tools, e.g., for inspecting the properties and values applied to elements on your page, and making changes to them from the editor.
In this lesson we will look at some useful features of the Firefox DevTools for working with CSS. In order to do so I'll be using [an example file](https://mdn.github.io/css-examples/learn/inspecting/inspecting.html). Load this up in a new tab if you want to follow along, and open up your DevTools as described in the article linked above.
## The DOM versus view source
Something that can trip up newcomers to DevTools is the difference between what you see when you [view the source](https://firefox-source-docs.mozilla.org/devtools-user/view_source/index.html) of a webpage, or look at the HTML file you put on the server, and what you can see in the [HTML Pane](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/ui_tour/index.html#html-pane) of the DevTools. While it looks roughly similar to what you can see via View Source there are some differences.
In the rendered DOM the browser may have normalized the HTML, for example by correcting some badly-written HTML for you. If you incorrectly closed an element, for instance by opening an `<h2>` but closing with an `</h3>`, the browser will figure out what you were meaning to do and the HTML in the DOM will correctly close the open `<h2>` with an `</h2>`. The DOM will also show any changes made by JavaScript.
View Source, in comparison, is the HTML source code as stored on the server. The [HTML tree](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_and_edit_html/index.html#html-tree) in your DevTools shows exactly what the browser is rendering at any given time, so it gives you an insight into what is really going on.
## Inspecting the applied CSS
Select an element on your page, either by right/ctrl-clicking on it and selecting _Inspect_, or selecting it from the HTML tree on the left of the DevTools display. Try selecting the element with the class of `box1`; this is the first element on the page with a bordered box drawn around it.

If you look at the [Rules view](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/ui_tour/index.html#rules-view) to the right of your HTML, you should be able to see the CSS properties and values applied to that element. You will see the rules directly applied to class `box1` and also the CSS that is being inherited by the box from its ancestors, in this case from `<body>`. This is useful if you are seeing some CSS being applied that you didn't expect. Perhaps it is being inherited from a parent element and you need to add a rule to overwrite it in the context of this element.
Also useful is the ability to expand out shorthand properties. In our example the `margin` shorthand is used.
**Click on the little arrow to expand the view, showing the different longhand properties and their values.**
**You can toggle values in the Rules view on and off when that panel is active — if you hold your mouse over it, checkboxes will appear. Uncheck a rule's checkbox, for example `border-radius`, and the CSS will stop applying.**
You can use this to do an A/B comparison, deciding if something looks better with a rule applied or not, and also to help debug it — for example, if a layout is going wrong and you are trying to work out which property is causing the problem.
The following video provides some useful tips on debugging CSS using the Firefox DevTools:
{{EmbedYouTube("O3DAm82vIvU")}}
## Editing values
In addition to turning properties on and off, you can edit their values. Perhaps you want to see if another color looks better, or wish to tweak the size of something? DevTools can save you a lot of time editing a stylesheet and reloading the page.
**With `box1` selected, click on the swatch (the small colored circle) that shows the color applied to the border. A color picker will open up and you can try out some different colors; these will update in real time on the page. In a similar fashion, you could change the width or style of the border.**

## Adding a new property
You can add properties using the DevTools. Perhaps you have realized that you don't want your box to inherit the `<body>` element's font size, and want to set its own specific size? You can try this out in DevTools before adding it to your CSS file.
**You can click the closing curly brace in the rule to start entering a new declaration into it, at which point you can start typing the new property and DevTools will show you an autocomplete list of matching properties. After selecting `font-size`, enter the value you want to try. You can also click the + button to add an additional rule with the same selector, and add your new rules there.**

> **Note:** There are other useful features in the Rules view too, for example declarations with invalid values are crossed out. You can find out more at [Examine and edit CSS](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_and_edit_css/index.html).
## Understanding the box model
In previous lessons we have discussed [the Box Model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model), and the fact that we have an alternate box model that changes how the size of elements are calculated based on the size you give them, plus the padding and borders. DevTools can really help you to understand how the size of an element is being calculated.
The [Layout view](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/ui_tour/index.html#layout-view) shows you a diagram of the box model on the selected element, along with a description of the properties and values that change how the element is laid out. This includes a description of properties that you may not have explicitly used on the element, but which do have initial values set.
In this panel, one of the detailed properties is the `box-sizing` property, which controls what box model the element uses.
**Compare the two boxes with classes `box1` and `box2`. They both have the same width applied (400px), however `box1` is visually wider. You can see in the layout panel that it is using `content-box`. This is the value that takes the size you give the element and then adds on the padding and border width.**
The element with a class of `box2` is using `border-box`, so here the padding and border is subtracted from the size that you have given the element. This means that the space taken up on the page by the box is the exact size that you specified — in our case `width: 400px`.

> **Note:** Find out more in [Examining and Inspecting the Box Model](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_and_edit_the_box_model/index.html).
## Solving specificity issues
Sometimes during development, but in particular when you need to edit the CSS on an existing site, you will find yourself having a hard time getting some CSS to apply. No matter what you do, the element just doesn't seem to take the CSS. What is generally happening here is that a more specific selector is overriding your changes, and here DevTools will really help you out.
In our example file there are two words that have been wrapped in an `<em>` element. One is displaying as orange and the other hotpink. In the CSS we have applied:
```css
em {
color: hotpink;
font-weight: bold;
}
```
Above that in the stylesheet however is a rule with a `.special` selector:
```css
.special {
color: orange;
}
```
As you will recall from the lesson on [cascade and inheritance](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance) where we discussed specificity, class selectors are more specific than element selectors, and so this is the value that applies. DevTools can help you find such issues, especially if the information is buried somewhere in a huge stylesheet.
**Inspect the `<em>` with the class of `.special` and DevTools will show you that orange is the color that applies, and also that the `color` property applied to the `<em>` is crossed out. You can now see that the class selector is overriding the element selector.**

## Find out more about the Firefox DevTools
There is a lot of information about the Firefox DevTools here on MDN. Take a look at the main [DevTools section](https://firefox-source-docs.mozilla.org/devtools-user/index.html), and for more detail on the things we have briefly covered in this lesson see [The How To Guides](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/index.html#how-to).
## Debugging problems in CSS
DevTools can be a great help when solving CSS problems, so when you find yourself in a situation where CSS isn't behaving as you expect, how should you go about solving it? The following steps should help.
### Take a step back from the problem
Any coding problem can be frustrating, especially CSS problems because you often don't get an error message to search for online to help with finding a solution. If you are becoming frustrated, take a step away from the issue for a while — go for a walk, grab a drink, chat to a co-worker, or work on some other thing for a while. Sometimes the solution magically appears when you stop thinking about the problem, and even if not, working on it when feeling refreshed will be much easier.
### Do you have valid HTML and CSS?
Browsers expect your CSS and HTML to be correctly written, however browsers are also very forgiving and will try their best to display your webpages even if you have errors in the markup or stylesheet. If you have mistakes in your code the browser needs to make a guess at what you meant, and it might make a different decision to what you had in mind. In addition, two different browsers might cope with the problem in two different ways. A good first step, therefore, is to run your HTML and CSS through a validator, to pick up and fix any errors.
- [CSS Validator](https://jigsaw.w3.org/css-validator/)
- [HTML validator](https://validator.w3.org/)
### Are the property and value supported by the browser you are testing in?
Browsers ignore CSS they don't understand. If the property or value you are using is not supported by the browser you are testing in then nothing will break, but that CSS won't be applied. DevTools will generally highlight unsupported properties and values in some way. In the screenshot below the browser does not support the subgrid value of {{cssxref("grid-template-columns")}}.

You can also take a look at the Browser compatibility tables at the bottom of each property page on MDN. These show you browser support for that property, often broken down if there is support for some usage of the property and not others. [See the compatibility table for the `shape-outside` property](/en-US/docs/Web/CSS/shape-outside#browser_compatibility).
### Is something else overriding your CSS?
This is where the information you have learned about specificity will come into much use. If you have something more specific overriding what you are trying to do, you can enter into a very frustrating game of trying to work out what. However, as described above, DevTools will show you what CSS is applying and you can work out how to make the new selector specific enough to override it.
### Make a reduced test case of the problem
If the issue isn't solved by the steps above, then you will need to do some more investigating. The best thing to do at this point is to create something known as a reduced test case. Being able to "reduce an issue" is a really useful skill. It will help you find problems in your own code and that of your colleagues, and will also enable you to report bugs and ask for help more effectively.
A reduced test case is a code example that demonstrates the problem in the simplest possible way, with unrelated surrounding content and styling removed. This will often mean taking the problematic code out of your layout to make a small example which only shows that code or feature.
To create a reduced test case:
1. If your markup is dynamically generated — for example via a CMS — make a static version of the output that shows the problem. A code sharing site like [CodePen](https://codepen.io/) is useful for hosting reduced test cases, as then they are accessible online and you can easily share them with colleagues. You could start by doing View Source on the page and copying the HTML into CodePen, then grab any relevant CSS and JavaScript and include it too. After that, you can check whether the issue is still evident.
2. If removing the JavaScript does not make the issue go away, don't include the JavaScript. If removing the JavaScript _does_ make the issue go away, then remove as much JavaScript as you can, leaving in whatever causes the issue.
3. Remove any HTML that does not contribute to the issue. Remove components or even main elements of the layout. Again, try to get down to the smallest amount of code that still shows the issue.
4. Remove any CSS that doesn't impact the issue.
In the process of doing this, you may discover what is causing the problem, or at least be able to turn it on and off by removing something specific. It is worth adding some comments to your code as you discover things. If you need to ask for help, they will show the person helping you what you have already tried. This may well give you enough information to be able to search for likely problems and workarounds.
If you are still struggling to fix the problem then having a reduced test case gives you something to ask for help with, by posting to a forum, or showing to a co-worker. You are much more likely to get help if you can show that you have done the work of reducing the problem and identifying exactly where it happens, before asking for help. A more experienced developer might be able to quickly spot the problem and point you in the right direction, and even if not, your reduced test case will enable them to have a quick look and hopefully be able to offer at least some help.
In the instance that your problem is actually a bug in a browser, then a reduced test case can also be used to file a bug report with the relevant browser vendor (e.g. on Mozilla's [bugzilla site](https://bugzilla.mozilla.org)).
As you become more experienced with CSS, you will find that you get faster at figuring out issues. However, even the most experienced of us sometimes find ourselves wondering what on earth is going on. Taking a methodical approach, making a reduced test case, and explaining the issue to someone else will usually result in a fix being found.
## Summary
So there we have it: an introduction to debugging CSS, which should give you some useful skills to count on when you start to debug CSS and other types of code later on in your career.
In the last article of this module, we'll take a look at how to [organize your CSS](/en-US/docs/Learn/CSS/Building_blocks/Organizing).
{{PreviousMenuNext("Learn/CSS/Building_blocks/Styling_tables", "Learn/CSS/Building_blocks/Organizing", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/overflowing_content/index.md | ---
title: Overflowing content
slug: Learn/CSS/Building_blocks/Overflowing_content
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Handling_different_text_directions", "Learn/CSS/Building_blocks/Values_and_units", "Learn/CSS/Building_blocks")}}
Overflow is what happens when there is too much content to fit in an element box. In this guide, you will learn what overflow is and how to manage it.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To understand overflow and how to manage it.</td>
</tr>
</tbody>
</table>
## What is overflow?
Everything in CSS is a box. You can constrain the size of these boxes by assigning values of {{cssxref("width")}} and {{cssxref("height")}} (or {{cssxref("inline-size")}} and {{cssxref("block-size")}}). **Overflow happens when there is too much content to fit in a box.** CSS provides various tools to manage overflow. As you go further with CSS layout and writing CSS, you will encounter more overflow situations.
## CSS tries to avoid "data loss"
Let's consider two examples that demonstrate the default behavior of CSS when there is overflow.
The first example is a box that has been restricted by setting a `height`. Then we add content that exceeds the allocated space. The content overflows the box and falls into the paragraph below.
{{EmbedGHLiveSample("css-examples/learn/overflow/block-overflow.html", '100%', 700)}}
The second example is a word in a box. The box has been made too small for the word and so it breaks out of the box.
{{EmbedGHLiveSample("css-examples/learn/overflow/inline-overflow.html", '100%', 600)}}
You might wonder why CSS works in such a messy way, displaying content outside of its intended container. Why not hide overflowing content? Why not scale the size of the container to fit all the content?
Wherever possible, CSS does not hide content. This would cause data loss. The problem with data loss is that you might not notice. Website visitors may not notice. If the submit button on a form disappears and no one can complete the form, this could be a big problem! Instead, CSS overflows in visible ways. You are more likely to see there is a problem. At worst, a site visitor will let you know that content is overlapping.
If you restrict a box with a `width` or a `height`, CSS trusts you to know what you are doing. CSS assumes that you are managing the potential for overflow. In general, restricting the block dimension is problematic when the box contains text. There may be more text than you expected when designing the site, or the text may be larger (for example, if the user has increased their font size).
The next two lessons explain different approaches to control sizing in ways that are less prone to overflow. However, if you need a fixed size, you can also control how the overflow behaves. Let's read on!
## The overflow property
The {{cssxref("overflow")}} property helps you manage an element's content overflow. Using this property, you can convey to a browser how it should handle overflow content. The default value of the [`<overflow>`](/en-US/docs/Web/CSS/overflow_value) value type is `visible`. With this default setting, one can see content when it overflows.
To crop content when it overflows, you can set `overflow: hidden`. This does exactly what it says: it hides overflow. Beware that this can make some content invisible. You should only do this if hiding content won't cause problems.
{{EmbedGHLiveSample("css-examples/learn/overflow/hidden.html", '100%', 700)}}
Instead, perhaps you would like to add scrollbars when content overflows? Using `overflow: scroll`, browsers with visible scrollbars will always display them—even if there is not enough content to overflow. This offers the advantage of keeping the layout consistent, instead of scrollbars appearing or disappearing, depending upon the amount of content in the container.
**Remove some content from the box below. Notice how the scrollbars remain, even if there is no need for scrolling.**
{{EmbedGHLiveSample("css-examples/learn/overflow/scroll.html", '100%', 700)}}
In the example above, we only need to scroll on the `y` axis, however we get scrollbars in both axes. To just scroll on the `y` axis, you could use the {{cssxref("overflow-y")}} property, setting `overflow-y: scroll`.
{{EmbedGHLiveSample("css-examples/learn/overflow/scroll-y.html", '100%', 700)}}
You can also enable scrolling along the x-axis by using {{cssxref("overflow-x")}}, although this is not a recommended way to accommodate long words! If you have a long word in a small box, consider using the {{cssxref("word-break")}} or {{cssxref("overflow-wrap")}} property. In addition, some of the methods discussed in [Sizing items in CSS](/en-US/docs/Learn/CSS/Building_blocks/Sizing_items_in_CSS) may help you create boxes that scale better with varying amounts of content.
{{EmbedGHLiveSample("css-examples/learn/overflow/scroll-x.html", '100%', 600)}}
As with `scroll`, you get a scrollbar in the scrolling dimension whether or not there is enough content to cause a scrollbar.
> **Note:** You can specify x- and y-axis scrolling using the `overflow` property, passing two values. If two keywords are specified, the first applies to `overflow-x` and the second applies to `overflow-y`. Otherwise, both `overflow-x` and `overflow-y` are set to the same value. For example, `overflow: scroll hidden` would set `overflow-x` to `scroll` and `overflow-y` to `hidden`.
If you only want scrollbars to appear when there is more content than can fit in the box, use `overflow: auto`. This allows the browser to determine if it should display scrollbars.
**In the example below, remove content until it fits into the box. You should see the scrollbars disappear.**
{{EmbedGHLiveSample("css-examples/learn/overflow/auto.html", '100%', 700)}}
## Overflow establishes a Block Formatting Context
When you use the `<overflow>` values `scroll` and `auto`, you create a [**Block Formatting Context** (BFC)](/en-US/docs/Web/CSS/CSS_display/Block_formatting_context). This means that the content of an element box with these `overflow` values acquires a self-contained layout. Content outside such an element box cannot poke into the element box, and nothing from the element box can poke into the surrounding layout. This enables scrolling behavior, as all box content needs to be contained and not overlap to create a consistent scrolling experience.
## Unwanted overflow in web design
Modern layout methods (described in [CSS layout](/en-US/docs/Learn/CSS/CSS_layout)) manage overflow. They largely work without assumptions or dependencies for how much content there will be on a web page.
This was not always the norm. In the past, some sites were built with fixed-height containers to align box bottoms. These boxes may otherwise have had no relationship to each other. This was fragile. If you encounter a box where content is overlaying other content on the page in legacy applications, you will now recognize that this happens with overflow. Ideally, you will refactor the layout to not rely on fixed-height containers.
When developing a site, always keep overflow in mind. Test designs with large and small amounts of content. Increase and decrease font sizes by at least two increments. Ensure your CSS is robust. Changing overflow values to hide content or to add scrollbars is reserved for a few select use cases (for example, where you intend to have a scrolling box).
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Overflow](/en-US/docs/Learn/CSS/Building_blocks/Overflow_Tasks).
## Summary
This lesson introduced the concept of overflow. You should understand that default CSS avoids making overflowing content invisible. You have discovered that you can manage potential overflow, and also, that you should test work to make sure it does not accidentally cause problematic overflow.
In the next article, we'll take a look at the most common [values and units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units) in CSS.
{{PreviousMenuNext("Learn/CSS/Building_blocks/Handling_different_text_directions", "Learn/CSS/Building_blocks/Values_and_units", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/sizing_tasks/index.md | ---
title: "Test your skills: Sizing"
slug: Learn/CSS/Building_blocks/Sizing_tasks
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand the different ways of [sizing items in CSS](/en-US/docs/Learn/CSS/Building_blocks/Sizing_items_in_CSS).
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Task 1
In this task, you have two boxes. The first should be sized so that the height will be at least 100 pixels tall, even if there is less content that would cause it to grow to that height. However, the content should not overflow if there is more content than fits in 100 pixels. Test this box by removing the content from the HTML to make sure you still get a 100 pixel tall box even with no content.
The second box should be fixed at 100 pixels tall, so that content will overflow if there is too much.

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/sizing/height-min-height.html", '100%', 1000)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/sizing/height-min-height-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, you have a box, which contains another box. Your task is to make the inner box 60% of the width of the outer box. The value of the {{cssxref("box-sizing")}} property is set to `border-box`, which means that the total width includes any padding and border. You should also give the inner box padding of 10% using the width (or inline size) as the size from which that percentage is calculated.
Your final result should look like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/sizing/percentages.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/sizing/percentages-download.html) to work in your own editor or in an online editor.
## Task 3
In this task, you have two images in boxes. One image is smaller than the box, the other is larger and breaking out of the box. If you imagine that the box is responsive and therefore could grow and shrink, which property would you apply to the image so that the large image shrinks down into the box but the small image does not stretch.
Your final result should look like the images below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/sizing/max-width.html", '100%', 1200)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/sizing/max-width-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/a_cool_looking_box/index.md | ---
title: A cool-looking box
slug: Learn/CSS/Building_blocks/A_cool_looking_box
page-type: learn-module-assessment
---
{{LearnSidebar}}
{{PreviousMenu("Learn/CSS/Building_blocks/Creating_fancy_letterheaded_paper", "Learn/CSS/Building_blocks")}}
In this assessment, you'll get some more practice in creating cool-looking boxes by trying to create an eye-catching box.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Before attempting this assessment you should have already worked
through all the articles in this module.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To test comprehension of the CSS box model and other box-related
features such as borders and backgrounds.
</td>
</tr>
</tbody>
</table>
## Starting point
To get this assessment started, you should:
- Make local copies of the starting [HTML](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/cool-information-box-start/index.html) and [CSS](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/cool-information-box-start/style.css) — save them as `index.html` and `style.css` in a new directory.
Alternatively, you could use an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
You could paste the HTML and fill in the CSS into one of these online editors.
> **Note:** If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Project brief
Your task is to create a cool, fancy box and explore the fun we can have with CSS.
### General tasks
- Apply the CSS to the HTML.
### Styling the box
We'd like you to style the provided {{htmlelement("div")}}, giving it the following:
- A reasonable width for a large box, say around 200 pixels.
- A reasonable height for a large box, centering the text vertically in the process.
- Center the box horizontally.
- Center the text within the box.
- A slight increase in font size, to around 17-18 pixel computed style. Use rems. Write a comment about how you worked out the value.
- A base color for the design. Give the box this color as its background color.
- A contrasting color for the text and a black text shadow.
- A fairly subtle border radius.
- A 1-pixel solid border with a color similar to the base color, but a slightly darker shade.
- A linear semi-transparent black gradient that goes toward the bottom right corner. Make it completely transparent at the start, grading to around 0.2 opacity by 30% along, and remaining at the same color until the end.
- Multiple box shadows. Give it one standard box shadow to make the box look slightly raised off the page. The other two should be inset box shadows — a semi-transparent white shadow near the top left and a semi-transparent black shadow near the bottom right — to add to the nice raised 3D look of the box.
## Hints and tips
- Use the [W3C CSS Validator](https://jigsaw.w3.org/css-validator/) to catch and fix mistakes in your CSS.
## Example
The following screenshot shows an example of what the finished design could look like:

{{PreviousMenu("Learn/CSS/Building_blocks/Creating_fancy_letterheaded_paper", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/organizing/index.md | ---
title: Organizing your CSS
slug: Learn/CSS/Building_blocks/Organizing
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Debugging_CSS", "Learn/CSS/Building_blocks/Fundamental_CSS_comprehension", "Learn/CSS/Building_blocks")}}
As you start to work on larger stylesheets and big projects you will discover that maintaining a huge CSS file can be challenging. In this article we will take a brief look at some best practices for writing your CSS to make it easily maintainable, and some of the solutions you will find in use by others to help improve maintainability.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn some tips and best practices for organizing stylesheets, and
find out about some of the naming conventions and tools in common usage
to help with CSS organization and team working.
</td>
</tr>
</tbody>
</table>
## Tips to keep your CSS tidy
Here are some general suggestions for ways to keep your stylesheets organized and tidy.
### Does your project have a coding style guide?
If you are working with a team on an existing project, the first thing to check is whether the project has an existing style guide for CSS. The team style guide should always win over your own personal preferences. There often isn't a right or wrong way to do things, but consistency is important.
For example, have a look at the [CSS guidelines for MDN code examples](/en-US/docs/MDN/Writing_guidelines/Writing_style_guide/Code_style_guide/CSS).
### Keep it consistent
If you get to set the rules for the project or are working alone, then the most important thing to do is to keep things consistent. Consistency can be applied in all sorts of ways, such as using the same naming conventions for classes, choosing one method of describing color, or maintaining consistent formatting. (For example, will you use tabs or spaces to indent your code? If spaces, how many spaces?)
Having a set of rules you always follow reduces the amount of mental overhead needed when writing CSS, as some of the decisions are already made.
### Formatting readable CSS
There are a couple of ways you will see CSS formatted. Some developers put all of the rules onto a single line, like so:
```css-nolint
.box {background-color: #567895; }
h2 {background-color: black; color: white; }
```
Other developers prefer to break everything onto a new line:
```css
.box {
background-color: #567895;
}
h2 {
background-color: black;
color: white;
}
```
CSS doesn't mind which one you use. We personally find it is more readable to have each property and value pair on a new line.
### Comment your CSS
Adding comments to your CSS will help any future developer work with your CSS file, but will also help you when you come back to the project after a break.
```css
/* This is a CSS comment
It can be broken onto multiple lines. */
```
A good tip is to add a block of comments between logical sections in your stylesheet too, to help locate different sections quickly when scanning it, or even to give you something to search for to jump right into that part of the CSS. If you use a string that won't appear in the code, you can jump from section to section by searching for it — below we have used `||`.
```css
/* || General styles */
/* … */
/* || Typography */
/* … */
/* || Header and Main Navigation */
/* … */
```
You don't need to comment every single thing in your CSS, as much of it will be self-explanatory. What you should comment are the things where you made a particular decision for a reason.
You may have used a CSS property in a specific way to get around older browser incompatibilities, for example:
```css
.box {
background-color: red; /* fallback for older browsers that don't support gradients */
background-image: linear-gradient(to right, #ff0000, #aa0000);
}
```
Perhaps you followed a tutorial to achieve something, and the CSS isn't very self-explanatory or recognizable. In that case, you could add the URL of the tutorial to the comments. You will thank yourself when you come back to this project in a year or so and can vaguely remember that there was a great tutorial about that thing, but can't recall where it's from.
### Create logical sections in your stylesheet
It is a good idea to have all of the common styling first in the stylesheet. This means all of the styles which will generally apply unless you do something special with that element. You will typically have rules set up for:
- `body`
- `p`
- `h1`, `h2`, `h3`, `h4`, `h5`
- `ul` and `ol`
- The `table` properties
- Links
In this section of the stylesheet we are providing default styling for the type on the site, setting up a default style for data tables and lists and so on.
```css
/* || GENERAL STYLES */
body {
/* … */
}
h1,
h2,
h3,
h4 {
/* … */
}
ul {
/* … */
}
blockquote {
/* … */
}
```
After this section, we could define a few utility classes, for example, a class that removes the default list style for lists we're going to display as flex items or in some other way. If you have a few styling choices you know you will want to apply to lots of different elements, they can be put in this section.
```css
/* || UTILITIES */
.nobullets {
list-style: none;
margin: 0;
padding: 0;
}
/* … */
```
Then we can add everything that is used sitewide. That might be things like the basic page layout, the header, navigation styling, and so on.
```css
/* || SITEWIDE */
.main-nav {
/* … */
}
.logo {
/* … */
}
```
Finally, we will include CSS for specific things, broken down by the context, page, or even component in which they are used.
```css
/* || STORE PAGES */
.product-listing {
/* … */
}
.product-box {
/* … */
}
```
By ordering things in this way, we at least have an idea in which part of the stylesheet we will be looking for something that we want to change.
### Avoid overly-specific selectors
If you create very specific selectors, you will often find that you need to duplicate chunks of your CSS to apply the same rules to another element. For example, you might have something like the selector below, which applies the rule to a `<p>` with a class of `box` inside an `<article>` with a class of `main`.
```css
article.main p.box {
border: 1px solid #ccc;
}
```
If you then wanted to apply the same rules to something outside of `main`, or to something other than a `<p>`, you would have to add another selector to these rules or create a whole new ruleset. Instead, you could use the selector `.box` to apply your rule to any element that has the class `box`:
```css
.box {
border: 1px solid #ccc;
}
```
There will be times when making something more specific makes sense; however, this will generally be an exception rather than usual practice.
### Break large stylesheets into multiple smaller ones
In cases where you have very different styles for distinct parts of the site, you might want to have one stylesheet that includes all the global rules, as well as some smaller stylesheets that include the specific rules needed for those sections. You can link to multiple stylesheets from one page, and the normal rules of the cascade apply, with rules in stylesheets linked later coming after rules in stylesheets linked earlier.
For example, we might have an online store as part of the site, with a lot of CSS used only for styling the product listings and forms needed for the store. It would make sense to have those things in a different stylesheet, only linked to on store pages.
This can make it easier to keep your CSS organized, and also means that if multiple people are working on the CSS, you will have fewer situations where two people need to work on the same stylesheet at once, leading to conflicts in source control.
## Other tools that can help
CSS itself doesn't have much in the way of in-built organization; therefore, the level of consistency in your CSS will largely depend on you. The web community has developed various tools and approaches that can help you to manage larger CSS projects. Since you are likely to come across these aids when working with other people, and since they are often of help generally, we've included a short guide to some of them.
### CSS methodologies
Instead of needing to come up with your own rules for writing CSS, you may benefit from adopting one of the approaches already designed by the community and tested across many projects. These methodologies are essentially CSS coding guides that take a very structured approach to writing and organizing CSS. Typically they tend to render CSS more verbosely than you might have if you wrote and optimized every selector to a custom set of rules for that project.
However, you do gain a lot of structure by adopting one. Since many of these systems are widely used, other developers are more likely to understand the approach you are using and be able to write their own CSS in the same way, rather than having to work out your own personal methodology from scratch.
#### OOCSS
Most of the approaches you will encounter owe something to the concept of Object Oriented CSS (OOCSS), an approach made popular by [the work of Nicole Sullivan](https://github.com/stubbornella/oocss/wiki). The basic idea of OOCSS is to separate your CSS into reusable objects, which can be used anywhere you need on your site. The standard example of OOCSS is the pattern described as [The Media Object](/en-US/docs/Web/CSS/Layout_cookbook/Media_objects). This is a pattern with a fixed size image, video or other element on one side, and flexible content on the other. It's a pattern we see all over websites for comments, listings, and so on.
If you are not taking an OOCSS approach you might create a custom CSS for the different places this pattern is used, for example, by creating two classes, one called `comment` with a bunch of rules for the component parts, and another called `list-item` with almost the same rules as the `comment` class except for some tiny differences. The differences between these two components are the list-item has a bottom border, and images in comments have a border whereas list-item images do not.
```css
.comment {
display: grid;
grid-template-columns: 1fr 3fr;
}
.comment img {
border: 1px solid grey;
}
.comment .content {
font-size: 0.8rem;
}
.list-item {
display: grid;
grid-template-columns: 1fr 3fr;
border-bottom: 1px solid grey;
}
.list-item .content {
font-size: 0.8rem;
}
```
In OOCSS, you would create one pattern called `media` that would have all of the common CSS for both patterns — a base class for things that are generally the shape of the media object. Then we'd add an additional class to deal with those tiny differences, thus extending that styling in specific ways.
```css
.media {
display: grid;
grid-template-columns: 1fr 3fr;
}
.media .content {
font-size: 0.8rem;
}
.comment img {
border: 1px solid grey;
}
.list-item {
border-bottom: 1px solid grey;
}
```
In your HTML, the comment would need both the `media` and `comment` classes applied:
```html
<div class="media comment">
<img src="" alt="" />
<div class="content"></div>
</div>
```
The list-item would have `media` and `list-item` applied:
```html
<ul>
<li class="media list-item">
<img src="" alt="" />
<div class="content"></div>
</li>
</ul>
```
The work that Nicole Sullivan did in describing this approach and promoting it means that even people who are not strictly following an OOCSS approach today will generally be reusing CSS in this way — it has entered our understanding as a good way to approach things in general.
#### BEM
BEM stands for Block Element Modifier. In BEM a block is a stand-alone entity such as a button, menu, or logo. An element is something like a list item or a title that is tied to the block it is in. A modifier is a flag on a block or element that changes the styling or behavior. You will be able to recognize code that uses BEM due to the extensive use of dashes and underscores in the CSS classes. For example, look at the classes applied to this HTML from the page about [BEM Naming conventions](https://getbem.com/naming/):
```html
<form class="form form--theme-xmas form--simple">
<label class="label form__label" for="inputId"></label>
<input class="form__input" type="text" id="inputId" />
<input
class="form__submit form__submit--disabled"
type="submit"
value="Submit" />
</form>
```
The additional classes are similar to those used in the OOCSS example; however, they use the strict naming conventions of BEM.
BEM is widely used in larger web projects and many people write their CSS in this way. It is likely that you will come across examples, even in tutorials, that use BEM syntax, without mentioning why the CSS is structured in such a way.
Read more about this system [BEM 101](https://css-tricks.com/bem-101/) on CSS Tricks.
#### Other common systems
There are a large number of these systems in use. Other popular approaches include [Scalable and Modular Architecture for CSS (SMACSS)](https://smacss.com/), created by Jonathan Snook, [ITCSS](https://itcss.io/) from Harry Roberts, and [Atomic CSS (ACSS)](https://acss.io/), originally created by Yahoo!. If you come across a project that uses one of these approaches, then the advantage is that you will be able to search and find many articles and guides to help you understand how to code in the same style.
The disadvantage of using such a system is that they can seem overly complex, especially for smaller projects.
### Build systems for CSS
Another way to organize CSS is to take advantage of some of the tooling that is available for front-end developers, which allows you to take a slightly more programmatic approach to writing CSS. There are a number of tools, which we refer to as _pre-processors_ and _post-processors_. A pre-processor runs over your raw files and turns them into a stylesheet, whereas a post-processor takes your finished stylesheet and does something to it — perhaps to optimize it in order that it will load faster.
Using any of these tools will require that your development environment be able to run the scripts that do the pre- and post-processing. Many code editors can do this for you, or you can install command line tools to help.
The most popular pre-processor is [Sass](https://sass-lang.com/). This is not a Sass tutorial, so I will briefly explain a couple of the things that Sass can do, which are really helpful in terms of organization even if you don't use any of the other Sass features. If you want to learn a lot more about Sass, start with the [Sass basics](https://sass-lang.com/guide) article, then move on to their other documentation.
#### Defining variables
CSS now has native [custom properties](/en-US/docs/Web/CSS/Using_CSS_custom_properties), making this feature increasingly less important. However, one of the reasons you might use Sass is to be able to define all of the colors and fonts used in a project as settings, then to use that variable around the project. This means that if you realize you have used the wrong shade of blue, you only need change it in one place.
If we created a variable called `$base-color`, as in the first line below, we could then use it through the stylesheet anywhere that required that color.
```scss
$base-color: #c6538c;
.alert {
border: 1px solid $base-color;
}
```
Once compiled to CSS, you would end up with the following CSS in the final stylesheet.
```css
.alert {
border: 1px solid #c6538c;
}
```
#### Compiling component stylesheets
I mentioned above that one way to organize CSS is to break down stylesheets into smaller stylesheets. When using Sass you can take this to another level and have lots of very small stylesheets — even going as far as having a separate stylesheet for each component. By using the included functionality in Sass (partials), these can all be compiled together into one or a small number of stylesheets to actually link into your website.
So, for example, with [partials](https://sass-lang.com/documentation/at-rules/use#partials), you could have several style files inside a directory, say `foundation/_code.scss`, `foundation/_lists.scss`, `foundation/_footer.scss`, `foundation/_links.scss`, etc. You could then use the Sass `@use` rule to load them into other stylesheets:
```scss
// foundation/_index.scss
@use "code";
@use "lists";
@use "footer";
@use "links";
```
If the partials are all loaded into an index file, as implied above, you can then load that entire directory into another stylesheet in one go:
```scss
// style.scss
@use "foundation";
```
> **Note:** A simple way to try out Sass is to use [CodePen](https://codepen.io) — you can enable Sass for your CSS in the Settings for a Pen, and CodePen will then run the Sass parser for you in order that you can see the resulting webpage with regular CSS applied. Sometimes you will find that CSS tutorials have used Sass rather than plain CSS in their CodePen demos, so it is handy to know a little bit about it.
#### Post-processing for optimization
If you are concerned about adding size to your stylesheets, for example, by adding a lot of additional comments and whitespace, then a post-processing step could be to optimize the CSS by stripping out anything unnecessary in the production version. An example of a post-processor solution for doing this would be [cssnano](https://cssnano.co/).
## Summary
This is the final part of our building blocks module, and as you can see there are many ways in which your exploration of CSS can continue from this point — but now you can go on to testing yourself with our assessments: the first one is linked below.
To learn more about layout in CSS, see the [CSS Layout](/en-US/docs/Learn/CSS/CSS_layout) module.
You should also now have the skills to explore the rest of the [MDN CSS](/en-US/docs/Web/CSS) material. You can look up properties and values, explore our [CSS Cookbook](/en-US/docs/Web/CSS/Layout_cookbook) for patterns to use, or continue reading in some of the specific guides, such as our [Guide to CSS Grid Layout](/en-US/docs/Web/CSS/CSS_grid_layout).
{{PreviousMenuNext("Learn/CSS/Building_blocks/Debugging_CSS", "Learn/CSS/Building_blocks/Fundamental_CSS_comprehension", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/values_and_units/index.md | ---
title: CSS values and units
slug: Learn/CSS/Building_blocks/Values_and_units
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Overflowing_content", "Learn/CSS/Building_blocks/Sizing_items_in_CSS", "Learn/CSS/Building_blocks")}}
CSS rules contain [declarations](/en-US/docs/Web/CSS/Syntax#css_declarations), which in turn are composed of properties and values.
Each property used in CSS has a **value type** that describes what kind of values it is allowed to have.
In this lesson, we will take a look at some of the most frequently used value types, what they are, and how they work.
> **Note:** Each [CSS property page](/en-US/docs/Web/CSS/Reference#index) has a syntax section that lists the value types you can use with that property.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>).
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn about the different types of values and units used in CSS
properties.
</td>
</tr>
</tbody>
</table>
## What is a CSS value?
In CSS specifications and on the property pages here on MDN you will be able to spot value types as they will be surrounded by angle brackets, such as [`<color>`](/en-US/docs/Web/CSS/color_value) or {{cssxref("length")}}. When you see the value type `<color>` as valid for a particular property, that means you can use any valid color as a value for that property, as listed on the [`<color>`](/en-US/docs/Web/CSS/color_value) reference page.
> **Note:** You'll see CSS value types referred to as _data types_. The terms are basically interchangeable — when you see something in CSS referred to as a data type, it is really just a fancy way of saying value type. The term _value_ refers to any particular expression supported by a value type that you choose to use.
> **Note:** CSS value types tend to be enclosed in angle brackets (`<`, `>`) to differentiate them from CSS properties.
> For example there is a {{cssxref("color")}} property and a [`<color>`](/en-US/docs/Web/CSS/color_value) data type.
> This is not to be confused with HTML elements, as they also use angle brackets, but this is something to keep in mind that the context should make clear.
In the following example, we have set the color of our heading using a keyword, and the background using the `rgb()` function:
```css
h1 {
color: black;
background-color: rgb(197 93 161);
}
```
A value type in CSS is a way to define a collection of allowable values. This means that if you see `<color>` as valid you don't need to wonder which of the different types of color value can be used — keywords, hex values, `rgb()` functions, etc. You can use _any_ available `<color>` values, assuming they are supported by your browser. The page on MDN for each value will give you information about browser support. For example, if you look at the page for [`<color>`](/en-US/docs/Web/CSS/color_value) you will see that the browser compatibility section lists different types of color values and support for them.
Let's have a look at some of the types of values and units you may frequently encounter, with examples so that you can try out different possible values.
## Numbers, lengths, and percentages
There are various numeric value types that you might find yourself using in CSS. The following are all classed as numeric:
<table class="standard-table no-markdown">
<thead>
<tr>
<th scope="col">Data type</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code><a href="/en-US/docs/Web/CSS/integer"><integer></a></code>
</td>
<td>
An <code><integer></code> is a whole number such as
<code>1024</code> or <code>-55</code>.
</td>
</tr>
<tr>
<td>
<code><a href="/en-US/docs/Web/CSS/number"><number></a></code>
</td>
<td>
A <code><number></code> represents a decimal number — it may or may
not have a decimal point with a fractional component. For
example, <code>0.255</code>, <code>128</code>, or <code>-1.2</code>.
</td>
</tr>
<tr>
<td>
<code
><a href="/en-US/docs/Web/CSS/dimension"><dimension></a></code
>
</td>
<td>
A <code><dimension></code> is a <code><number></code> with a
unit attached to it. For example, <code>45deg</code>, <code>5s</code>,
or <code>10px</code>. <code><dimension></code> is an umbrella
category that includes the {{cssxref("length")}}, <code><a href="/en-US/docs/Web/CSS/angle"><angle></a></code
>, <code><a href="/en-US/docs/Web/CSS/time"><time></a></code
>, and
<code
><a href="/en-US/docs/Web/CSS/resolution"><resolution></a></code
>
types.
</td>
</tr>
<tr>
<td>{{cssxref("percentage")}}</td>
<td>
A <code><percentage></code> represents a fraction of some other
value. For example, <code>50%</code>. Percentage values are always
relative to another quantity. For example, an element's length is
relative to its parent element's length.
</td>
</tr>
</tbody>
</table>
### Lengths
The numeric type you will come across most frequently is {{cssxref("length")}}. For example, `10px` (pixels) or `30em`. There are two types of lengths used in CSS — relative and absolute. It's important to know the difference in order to understand how big things will become.
#### Absolute length units
The following are all **absolute** length units — they are not relative to anything else, and are generally considered to always be the same size.
| Unit | Name | Equivalent to |
| ---- | ------------------- | ------------------------ |
| `cm` | Centimeters | 1cm = 37.8px = 25.2/64in |
| `mm` | Millimeters | 1mm = 1/10th of 1cm |
| `Q` | Quarter-millimeters | 1Q = 1/40th of 1cm |
| `in` | Inches | 1in = 2.54cm = 96px |
| `pc` | Picas | 1pc = 1/6th of 1in |
| `pt` | Points | 1pt = 1/72nd of 1in |
| `px` | Pixels | 1px = 1/96th of 1in |
Most of these units are more useful when used for print, rather than screen output. For example, we don't typically use `cm` (centimeters) on screen. The only value that you will commonly use is `px` (pixels).
#### Relative length units
Relative length units are relative to something else, perhaps the size of the parent element's font, or the size of the viewport. The benefit of using relative units is that with some careful planning you can make it so the size of text or other elements scales relative to everything else on the page. Some of the most useful units for web development are listed in the table below.
<table class="standard-table no-markdown">
<thead>
<tr>
<th scope="col">Unit</th>
<th scope="col">Relative to</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>em</code></td>
<td>
Font size of the parent, in the case of typographical properties like
<code><a href="/en-US/docs/Web/CSS/font-size">font-size</a></code
>, and font size of the element itself, in the case of other properties
like <code><a href="/en-US/docs/Web/CSS/width">width</a></code
>.
</td>
</tr>
<tr>
<td><code>ex</code></td>
<td>x-height of the element's font.</td>
</tr>
<tr>
<td><code>ch</code></td>
<td>
The advance measure (width) of the glyph "0" of the element's font.
</td>
</tr>
<tr>
<td><code>rem</code></td>
<td>Font size of the root element.</td>
</tr>
<tr>
<td><code>lh</code></td>
<td>Line height of the element.</td>
</tr>
<tr>
<td><code>rlh</code></td>
<td>Line height of the root element. When used on the <code><a href="/en-US/docs/Web/CSS/font-size">font-size</a></code> or <code><a href="/en-US/docs/Web/CSS/line-height">line-height</a></code
> properties of the root element, it refers to the properties' initial value.</td>
</tr>
<tr>
<td><code>vw</code></td>
<td>1% of the viewport's width.</td>
</tr>
<tr>
<td><code>vh</code></td>
<td>1% of the viewport's height.</td>
</tr>
<tr>
<td><code>vmin</code></td>
<td>1% of the viewport's smaller dimension.</td>
</tr>
<tr>
<td><code>vmax</code></td>
<td>1% of the viewport's larger dimension.</td>
</tr>
<tr>
<td><code>vb</code></td>
<td>1% of the size of the initial containing block in the direction of the root element's <a href="/en-US/docs/Web/CSS/CSS_logical_properties_and_values#block_vs._inline">block axis</a>.</td>
</tr>
<tr>
<td><code>vi</code></td>
<td>1% of the size of the initial containing block in the direction of the root element's <a href="/en-US/docs/Web/CSS/CSS_logical_properties_and_values#block_vs._inline">inline axis</a>.</td>
</tr>
<tr>
<td><code>svw, svh</code></td>
<td>1% of the <a href="/en-US/docs/Web/CSS/length#relative_length_units_based_on_viewport">small viewport</a>'s width and height, respectively.</td>
</tr>
<tr>
<td><code>lvw, lvh</code></td>
<td>1% of the <a href="/en-US/docs/Web/CSS/length#relative_length_units_based_on_viewport">large viewport</a>'s width and height, respectively.</td>
</tr>
<tr>
<td><code>dvw, dvh</code></td>
<td>1% of the <a href="/en-US/docs/Web/CSS/length#relative_length_units_based_on_viewport">dynamic viewport</a>'s width and height, respectively.</td>
</tr>
</tbody>
</table>
#### Exploring an example
In the example below, you can see how some relative and absolute length units behave. The first box has a {{cssxref("width")}} set in pixels. As an absolute unit, this width will remain the same no matter what else changes.
The second box has a width set in `vw` (viewport width) units. This value is relative to the viewport width, and so 10vw is 10 percent of the width of the viewport. If you change the width of your browser window, the size of the box should change. However this example is embedded into the page using an [`<iframe>`](/en-US/docs/Web/HTML/Element/iframe), so this won't work. To see this in action you'll have to [try the example after opening it in its own browser tab](https://mdn.github.io/css-examples/learn/values-units/length.html).
The third box uses `em` units. These are relative to the font size. I've set a font size of `1em` on the containing {{htmlelement("div")}}, which has a class of `.wrapper`. Change this value to `1.5em` and you will see that the font size of all the elements increases, but only the last item will get wider, as its width is relative to that font size.
After following the instructions above, try playing with the values in other ways, to see what you get.
{{EmbedGHLiveSample("css-examples/learn/values-units/length.html", '100%', 900)}}
#### ems and rems
`em` and `rem` are the two relative lengths you are likely to encounter most frequently when sizing anything from boxes to text. It's worth understanding how these work, and the differences between them, especially when you start getting on to more complex subjects like [styling text](/en-US/docs/Learn/CSS/Styling_text) or [CSS layout](/en-US/docs/Learn/CSS/CSS_layout). The below example provides a demonstration.
The HTML illustrated below is a set of nested lists — we have two lists in total and both examples have the same HTML. The only difference is that the first has a class of _ems_ and the second a class of _rems_.
To start with, we set 16px as the font size on the `<html>` element.
**To recap, the em unit means "my parent element's font-size"** in the case of typography. The {{htmlelement("li")}} elements inside the {{htmlelement("ul")}} with a `class` of `ems` take their sizing from their parent. So each successive level of nesting gets progressively larger, as each has its font size set to `1.3em` — 1.3 times its parent's font size.
**To recap, the rem unit means "The root element's font-size"** (rem stands for "root em"). The {{htmlelement("li")}} elements inside the {{htmlelement("ul")}} with a `class` of `rems` take their sizing from the root element (`<html>`). This means that each successive level of nesting does not keep getting larger.
However, if you change the `<html>` element's `font-size` in the CSS you will see that everything else changes relative to it — both `rem`- and `em`-sized text.
{{EmbedGHLiveSample("css-examples/learn/values-units/em-rem.html", '100%', 1100)}}
#### Line height units
`lh` and `rlh` are relative lengths units similar to `em` and `rem`. The difference between `lh` and `rlh` is that the first one is relative to the line height of the element itself, while the second one is relative to the line height of the root element, usually `<html>`.
Using these units, we can precisely align box decoration to the text. In this example, we use `lh` unit to create notepad-like lines using [`repeating-linear-gradient()`](/en-US/docs/Web/CSS/gradient/repeating-linear-gradient). It doesn't matter what's the line height of the text, the lines will always start in the right place.
```css hidden
body {
margin: 0;
display: grid;
grid-template-columns: 1fr 1fr;
padding: 24px;
gap: 24px;
background-color: floralwhite;
font-family: sans-serif;
}
@supports not (height: 1lh) {
body::before {
grid-column: 1 / -1;
padding: 8px;
border-radius: 4px;
background-color: tomato;
color: white;
content: "You browser doesn’t support lh unit just yet";
}
}
```
```css
p {
margin: 0;
background-image: repeating-linear-gradient(
to top,
lightskyblue 0 2px,
transparent 2px 1lh
);
}
```
```html
<p style="line-height: 2em">
Summer is a time for adventure, and this year was no exception. I had many
exciting experiences, but two of my favorites were my trip to the beach and my
week at summer camp.
</p>
<p style="line-height: 4em">
At the beach, I spent my days swimming, collecting shells, and building
sandcastles. I also went on a boat ride and saw dolphins swimming alongside
us.
</p>
```
{{EmbedLiveSample("line_height_units", "100%", "370")}}
### Percentages
In a lot of cases, a percentage is treated in the same way as a length. The thing with percentages is that they are always set relative to some other value. For example, if you set an element's `font-size` as a percentage, it will be a percentage of the `font-size` of the element's parent. If you use a percentage for a `width` value, it will be a percentage of the `width` of the parent.
In the below example the two percentage-sized boxes and the two pixel-sized boxes have the same class names. The sets are 40% and 200px wide respectively.
The difference is that the second set of two boxes is inside a wrapper that is 400 pixels wide. The second 200px wide box is the same width as the first one, but the second 40% box is now 40% of 400px — a lot narrower than the first one!
**Try changing the width of the wrapper or the percentage value to see how this works.**
{{EmbedGHLiveSample("css-examples/learn/values-units/percentage.html", '100%', 1000)}}
The next example has font sizes set in percentages. Each `<li>` has a `font-size` of 80%; therefore, the nested list items become progressively smaller as they inherit their sizing from their parent.
{{EmbedGHLiveSample("css-examples/learn/values-units/percentage-fonts.html", '100%', 800)}}
Note that, while many value types accept a length or a percentage, there are some that only accept length. You can see which values are accepted on the MDN property reference pages. If the allowed value includes {{cssxref("length-percentage")}} then you can use a length or a percentage. If the allowed value only includes `<length>`, it is not possible to use a percentage.
### Numbers
Some value types accept numbers, without any unit added to them. An example of a property which accepts a unitless number is the `opacity` property, which controls the opacity of an element (how transparent it is). This property accepts a number between `0` (fully transparent) and `1` (fully opaque).
**In the below example, try changing the value of `opacity` to various decimal values between `0` and `1` and see how the box and its contents become more or less opaque.**
{{EmbedGHLiveSample("css-examples/learn/values-units/opacity.html", '100%', 600)}}
> **Note:** When you use a number in CSS as a value it should not be surrounded in quotes.
## Color
Color values can be used in many places in CSS, whether you are specifying the color of text, backgrounds, borders, and lots more.
There are many ways to set color in CSS, allowing you to control plenty of exciting properties.
The standard color system available in modern computers supports 24-bit colors, which allows displaying about 16.7 million distinct colors via a combination of different red, green, and blue channels with 256 different values per channel (256 x 256 x 256 = 16,777,216).
In this section, we'll first look at the most commonly seen ways of specifying colors: using keywords, hexadecimal, and `rgb()` values.
We'll also take a quick look at additional color functions, enabling you to recognize them when you see them or experiment with different ways of applying color.
You will likely decide on a color palette and then use those colors — and your favorite way of specifying color — throughout your project.
You can mix and match color models, but it's usually best if your entire project uses the same method of declaring colors for consistency!
### Color keywords
You will see the color keywords (or 'named colors') used in many MDN code examples. As the [`<named-color>`s](/en-US/docs/Web/CSS/named-color) data type contains a very finite number of color values, these are not commonly used on production websites. As the keyword represents the color as a human-readable text value, named colors are used in code examples to clearly tell the user what color is expected so the learner can focus on the content being taught.
**Try playing with different color values in the live examples below, to get more of an idea how they work.**
{{EmbedGHLiveSample("css-examples/learn/values-units/color-keywords.html", '100%', 800)}}
### Hexadecimal RGB values
The next type of color value you are likely to encounter is hexadecimal codes.
Hexadecimal uses 16 characters from `0-9` and `a-f`, so the entire range is `0123456789abcdef`.
Each hex color value consists of a hash/pound symbol (`#`) followed by three or six hexadecimal characters (`#fcc` or `#ffc0cb`, for example), with an optional one or two hexadecimal characters representing the alpha-transparency of the previous three or six character color values.
When using hexadecimal to describe RGB values, each **pair** of hexadecimal characters is a decimal number representing one of the channels — red, green and blue — and allows us to specify any of the 256 available values for each (16 x 16 = 256).
These values are less intuitive than keywords for defining colors, but they are a lot more versatile because you can represent any RGB color with them.
{{EmbedGHLiveSample("css-examples/learn/values-units/color-hex.html", '100%', 800)}}
**Again, try changing the values to see how the colors vary.**
### RGB values
To create RGB values directly, the [`rgb()`](/en-US/docs/Web/CSS/color_value/rgb) function takes three parameters representing **red**, **green**, and **blue** channel values of the colors, with an optional fourth value separated by a slash ('/') representing opacity, in much the same way as hex values. The difference with RGB is that each channel is represented not by two hex digits, but by a decimal number between 0 and 255 or a percent between 0% and 100% inclusive (but not a mixture of the two).
Let's rewrite our last example to use RGB colors:
{{EmbedGHLiveSample("css-examples/learn/values-units/color-rgb.html", '100%', 800)}}
You can pass a fourth parameter to `rgb()`, which represents the alpha channel of the color, which controls opacity. If you set this value to `0` it will make the color fully transparent, whereas `1` will make it fully opaque. Values in between give you different levels of transparency.
> **Note:** Setting an alpha channel on a color has one key difference to using the {{cssxref("opacity")}} property we looked at earlier. When you use opacity you make the element and everything inside it opaque, whereas using RGB with an alpha parameter colors only makes the color you are specifying opaque.
In the example below, we have added a background image to the containing block of our colored boxes. We have then set the boxes to have different opacity values — notice how the background shows through more when the alpha channel value is smaller.
{{EmbedGHLiveSample("css-examples/learn/values-units/color-rgba.html", '100%', 900)}}
**In this example, try changing the alpha channel values to see how it affects the color output.**
> **Note:** In older versions of CSS, the `rgb()` syntax didn't support an alpha parameter - you needed to use a different function called `rgba()` for that. These days you can pass an alpha parameter to `rgb()`, but for backwards compatibility with old websites, the `rgba()` syntax is still supported, and has exactly the same behavior as `rgb()`.
### SRGB values
The `sRGB` color space defines colors in the **red** (r), **green** (g), and **blue** (b) color space.
### Using hues to specify a color
If you want to go beyond keywords, hexadecimal, and `rgb()` for colors, you might want to try using [`<hue>`](/en-US/docs/Web/CSS/hue).
Hue is the property that allows us to tell the difference or similarity between colors like red, orange, yellow, green, blue, etc.
The key concept is that you can specify a hue in an [`<angle>`](/en-US/docs/Web/CSS/angle) because most of the color models describe hues using a {{glossary("color wheel")}}.
There are several color functions that include a [`<hue>`](/en-US/docs/Web/CSS/hue) component, including `hsl()`,`hwb()`, and [`lch()`](/en-US/docs/Web/CSS/color_value/lch). Other color functions, like [`lab()`](/en-US/docs/Web/CSS/color_value/lab), define colors based on what humans can see.
If you want to find out more about these functions and color spaces, see the [Applying color to HTML elements using CSS](/en-US/docs/Web/CSS/CSS_colors/Applying_color) guide, the [`<color>`](/en-US/docs/Web/CSS/color_value) reference that lists all the different ways you can use colors in CSS, and the [CSS color module](/en-US/docs/Web/CSS/CSS_colors) that provides an overview of all the color types in CSS and the properties that use color values.
### HWB
A great starting point for using hues in CSS is the [`hwb()`](/en-US/docs/Web/CSS/color_value/hwb) function which specifies an `srgb()` color.
The three parts are:
- **Hue**: The base shade of the color. This takes a [`<hue>`](/en-US/docs/Web/CSS/hue) value between 0 and 360, representing the angles around a color wheel.
- **Whiteness**: How white is the color? This takes a value from `0%` (no whiteness) to `100%` (full whiteness).
- **Blackness**: How black is the color? This takes a value from 0% (no blackness) to 100% (full blackness).
### HSL
Similar to the `hwb()` function is the [`hsl()`](/en-US/docs/Web/CSS/color_value/hsl) function which also specifies an `srgb()` color.
HSL uses `Hue`, in addition to `Saturation` and `Lightness`:
- **Hue**
- **Saturation**: How saturated is the color? This takes a value from 0–100%, where 0 is no color (it will appear as a shade of grey), and 100% is full color saturation.
- **Lightness**: How light or bright is the color? This takes a value from 0–100%, where 0 is no light (it will appear completely black) and 100% is full light (it will appear completely white).
The `hsl()` color value also has an optional fourth value, separated from the color with a slash (`/`), representing the alpha transparency.
Let's update the RGB example to use HSL colors instead:
{{EmbedGHLiveSample("css-examples/learn/values-units/color-hsl.html", '100%', 800)}}
Just like with `rgb()` you can pass an alpha parameter to `hsl()` to specify opacity:
{{EmbedGHLiveSample("css-examples/learn/values-units/color-hsla.html", '100%', 900)}}
> **Note:** In older versions of CSS, the `hsl()` syntax didn't support an alpha parameter - you needed to use a different function called `hsla()` for that. These days you can pass an alpha parameter to `hsl()`, but for backwards compatibility with old websites, the `hsla()` syntax is still supported, and has exactly the same behavior as `hsl()`.
## Images
The [`<image>`](/en-US/docs/Web/CSS/image) value type is used wherever an image is a valid value. This can be an actual image file pointed to via a `url()` function, or a gradient.
In the example below, we have demonstrated an image and a gradient in use as a value for the CSS `background-image` property.
{{EmbedGHLiveSample("css-examples/learn/values-units/image.html", '100%', 900)}}
> **Note:** There are some other possible values for `<image>`, however these are newer and currently have poor browser support. Check out the page on MDN for the [`<image>`](/en-US/docs/Web/CSS/image) data type if you want to read about them.
## Position
The [`<position>`](/en-US/docs/Web/CSS/position_value) value type represents a set of 2D coordinates, used to position an item such as a background image (via [`background-position`](/en-US/docs/Web/CSS/background-position)). It can take keywords such as `top`, `left`, `bottom`, `right`, and `center` to align items with specific bounds of a 2D box, along with lengths, which represent offsets from the top and left-hand edges of the box.
A typical position value consists of two values — the first sets the position horizontally, the second vertically. If you only specify values for one axis the other will default to `center`.
In the following example we have positioned a background image 40px from the top and to the right of the container using a keyword.
{{EmbedGHLiveSample("css-examples/learn/values-units/position.html", '100%', 800)}}
**Play around with these values to see how you can push the image around.**
## Strings and identifiers
Throughout the examples above, we've seen places where keywords are used as a value (for example `<color>` keywords like `red`, `black`, `rebeccapurple`, and `goldenrod`). These keywords are more accurately described as _identifiers_, a special value that CSS understands. As such they are not quoted — they are not treated as strings.
There are places where you use strings in CSS. For example, [when specifying generated content](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements#generating_content_with_before_and_after). In this case, the value is quoted to demonstrate that it is a string. In the example below, we use unquoted color keywords along with a quoted generated content string.
{{EmbedGHLiveSample("css-examples/learn/values-units/strings-idents.html", '100%', 600)}}
## Functions
In programming, a function is a piece of code that does a specific task.
Functions are useful because you can write code once, then reuse it many times instead of writing the same logic over and over.
Most programming languages not only support functions but also come with convenient built-in functions for common tasks so you don't have to write them yourself from scratch.
CSS also has [functions](/en-US/docs/Web/CSS/CSS_Functions), which work in a similar way to functions in other languages.
In fact, we've already seen CSS functions in the [Color](#color) section above with [`rgb()`](/en-US/docs/Web/CSS/color_value#rgb_function) and [`hsl()`](/en-US/docs/Web/CSS/color_value#hsl_function) functions.
Aside from applying colors, you can use functions in CSS to do a lot of other things.
For example [Transform functions](/en-US/docs/Web/CSS/CSS_Functions#transform_functions) are a common way to move, rotate, and scale elements on a page.
You might see [`translate()`](/en-US/docs/Web/CSS/transform-function/translate) for moving something horizontally or vertically, [`rotate()`](/en-US/docs/Web/CSS/transform-function/rotate) to rotate something, or [`scale()`](/en-US/docs/Web/CSS/transform-function/scale) to make something bigger or smaller.
### Math functions
When you are creating styles for a project, you will probably start off with numbers like `300px` for lengths or `200ms` for durations.
If you want to have these values change based on other values, you will need to do some math.
You could calculate the percentage of a value or add a number to another number, then update your CSS with the result.
CSS has support for [Math functions](/en-US/docs/Web/CSS/CSS_Functions#math_functions), which allow us to perform calculations instead of relying on static values or doing the math in JavaScript.
One of the most common math functions is [`calc()`](/en-US/docs/Web/CSS/calc) which lets you do operations like addition, subtraction, multiplication, and division.
For example, let's say we want to set the width of an element to be 20% of its parent container plus 100px.
We can't specify this width with a static value — if the parent uses a percentage width (or a relative unit like `em` or `rem`) then it will vary depending on the context it is used in, and other factors such as the user's device or browser window width.
However, we can use `calc()` to set the width of the element to be 20% of its parent container plus 100px.
The 20% is based on the width of the parent container (`.wrapper`) and if that width changes, the calculation will change too:
{{EmbedGHLiveSample("css-examples/learn/values-units/calc.html", '100%', 500)}}
There are many other math functions that you can use in CSS, such as [`min()`](/en-US/docs/Web/CSS/min), [`max()`](/en-US/docs/Web/CSS/max), and [`clamp()`](/en-US/docs/Web/CSS/clamp); respectively these let you pick the smallest, largest, or middle value from a set of values.
You can also use [Trigonometric functions](/en-US/docs/Web/CSS/CSS_Functions#trigonometric_functions) like [`sin()`](/en-US/docs/Web/CSS/sin), [`cos()`](/en-US/docs/Web/CSS/cos), and [`tan()`](/en-US/docs/Web/CSS/tan) to calculate angles for rotating elements around a point, or choose colors that take a [hue angle](/en-US/docs/Web/CSS/hue) as a parameter.
[Exponential functions](/en-US/docs/Web/CSS/CSS_Functions#exponential_functions) might also be used for animations and transitions, when you require very specific control over how something moves and looks.
Knowing about CSS functions is useful so you recognize them when you see them. You should start experimenting with them in your projects — they will help you avoid writing custom or repetitive code to achieve results that you can get with regular CSS.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Values and units](/en-US/docs/Learn/CSS/Building_blocks/Values_tasks).
## Summary
This has been a quick run-through of the most common types of values and units you might encounter. You can have a look at all of the different types on the [CSS Values and units](/en-US/docs/Web/CSS/CSS_Values_and_Units) reference page — you will encounter many of these in use as you work through these lessons.
The key thing to remember is that each property has a defined list of allowed value types, and each value type has a definition explaining what the values are. You can then look up the specifics here on MDN. For example, understanding that [`<image>`](/en-US/docs/Web/CSS/image) also allows you to create a color gradient is useful but perhaps non-obvious knowledge to have!
In the next article, we'll take a look at how [items are sized](/en-US/docs/Learn/CSS/Building_blocks/Sizing_items_in_CSS) in CSS.
{{PreviousMenuNext("Learn/CSS/Building_blocks/Overflowing_content", "Learn/CSS/Building_blocks/Sizing_items_in_CSS", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/css/building_blocks | data/mdn-content/files/en-us/learn/css/building_blocks/images_media_form_elements/index.md | ---
title: Images, media, and form elements
slug: Learn/CSS/Building_blocks/Images_media_form_elements
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Sizing_items_in_CSS", "Learn/CSS/Building_blocks/Styling_tables", "Learn/CSS/Building_blocks")}}
In this lesson we will take a look at how certain special elements are treated in CSS. Images, other media, and form elements behave a little differently from regular boxes in terms of your ability to style them with CSS. Understanding what is and isn't possible can save some frustration, and this lesson will highlight some of the main things that you need to know.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an idea of how CSS works (study
<a href="/en-US/docs/Learn/CSS/First_steps">CSS first steps</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the way that some elements behave unusually when styled
with CSS.
</td>
</tr>
</tbody>
</table>
## Replaced elements
Images and video are described as **[replaced elements](/en-US/docs/Web/CSS/Replaced_element)**. This means that CSS cannot affect the internal layout of these elements — only their position on the page amongst other elements. As we will see however, there are various things that CSS can do with an image.
Certain replaced elements, such as images and video, are also described as having an **aspect ratio**. This means that it has a size in both the horizontal (x) and vertical (y) dimensions, and will be displayed using the intrinsic dimensions of the file by default.
## Sizing images
As you already know from following these lessons, everything in CSS generates a box. If you place an image inside a box that is smaller or larger than the intrinsic dimensions of the image file in either direction, it will either appear smaller than the box, or overflow the box. You need to make a decision about what happens with the overflow.
In the example below we have two boxes, both 200 pixels in size:
- One contains an image which is smaller than 200 pixels — it is smaller than the box and doesn't stretch to fill it.
- The other is larger than 200 pixels and overflows the box.
{{EmbedGHLiveSample("css-examples/learn/images/size.html", '100%', 1000)}}
So what can we do about the overflowing issue?
As we learned in [our previous lesson](/en-US/docs/Learn/CSS/Building_blocks/Sizing_items_in_CSS), a common technique is to make the {{cssxref("max-width")}} of an image 100%. This will enable the image to become smaller in size than the box but not larger. This technique will also work with other replaced elements such as [`<video>`](/en-US/docs/Web/HTML/Element/video)s, or [`<iframe>`](/en-US/docs/Web/HTML/Element/iframe)s.
**Try adding `max-width: 100%` to the `<img>` element in the example above. You will see that the smaller image remains unchanged, but the larger one becomes smaller to fit into the box.**
You can make other choices about images inside containers. For example, you may want to size an image so it completely covers a box.
The {{cssxref("object-fit")}} property can help you here. When using `object-fit` the replaced element can be sized to fit a box in a variety of ways.
Below we have used the value `cover`, which sizes the image down, maintaining the aspect ratio so that it neatly fills the box. As the aspect ratio is maintained, some parts of the image will be cropped by the box.
{{EmbedGHLiveSample("css-examples/learn/images/object-fit.html", '100%', 1000)}}
If we use `contain` as a value, the image will be scaled down until it is small enough to fit inside the box. This will result in "letterboxing" if it is not the same aspect ratio as the box.
You could also try the value of `fill`, which will fill the box but not maintain the aspect ratio.
## Replaced elements in layout
When using various CSS layout techniques on replaced elements, you may well find that they behave slightly differently from other elements. For example, in a flex or grid layout, elements are stretched by default to fill the entire area. Images will not stretch, and instead will be aligned to the start of the grid area or flex container.
You can see this happening in the example below where we have a two column, two row grid container, which has four items in it. All of the `<div>` elements have a background color and stretch to fill the row and column. The image, however, does not stretch.
{{EmbedGHLiveSample("css-examples/learn/images/layout.html", '100%', 1000)}}
If you are following these lessons in order then you may not have looked at layout yet. Just keep in mind that replaced elements, when they become part of a grid or flex layout, have different default behaviors, essentially to avoid them being stretched strangely by the layout.
To force the image to stretch to fill the grid cell it is in, you'd have to do something like the following:
```css
img {
width: 100%;
height: 100%;
}
```
This would, however, stretch the image, so it's probably not what you'd want to do.
## Form elements
Form elements can be a tricky issue when it comes to styling with CSS. The [Web Forms module](/en-US/docs/Learn/Forms) contains detailed guides to the trickier aspects of styling these, which I will not fully reproduce here. There are, however, a few key basics worth highlighting in this section.
Many form controls are added to your page by way of the [`<input>`](/en-US/docs/Web/HTML/Element/input) element — this defines simple form fields such as text inputs, through to more complex fields such as color and date pickers. There are some additional elements, such as [`<textarea>`](/en-US/docs/Web/HTML/Element/textarea) for multiline text input, and also elements used to contain and label parts of forms such as [`<fieldset>`](/en-US/docs/Web/HTML/Element/fieldset) and [`<legend>`](/en-US/docs/Web/HTML/Element/legend).
HTML also contains attributes that enable web developers to indicate which fields are required, and even the type of content that needs to be entered. If the user enters something unexpected, or leaves a required field blank, the browser can show an error message. Different browsers vary with one another in how much styling and customization they allow for such items.
### Styling text input elements
Elements that allow for text input, such as `<input type="text">`, and the more specific `<input type="email">`, and the `<textarea>` element are quite easy to style and tend to behave just like other boxes on your page. The default styling of these elements will differ, however, based on the operating system and browser that your user visits the site with.
In the example below we have styled some text inputs using CSS — you can see that things such as borders, margins and padding all apply as you would expect. We are using attribute selectors to target the different input types. Try changing how this form looks by adjusting the borders, adding background colors to the fields, and changing fonts and padding.
{{EmbedGHLiveSample("css-examples/learn/images/form.html", '100%', 1000)}}
> **Warning:** You should take care when changing the styling of form elements to make sure it is still obvious to the user they are form elements. You could create a form input with no borders and background that is almost indistinguishable from the content around it, but this would make it very hard to recognize and fill in.
As explained in the lessons on [styling web forms](/en-US/docs/Learn/Forms/Styling_web_forms), many of the more complex input types are rendered by the operating system and are inaccessible to styling. You should, therefore, always assume that forms are going to look quite different for different visitors and test complex forms in a number of browsers.
### Inheritance and form elements
In some browsers, form elements do not inherit font styling by default. Therefore, if you want to be sure that your form fields use the font defined on the body, or on a parent element, you should add this rule to your CSS.
```css
button,
input,
select,
textarea {
font-family: inherit;
font-size: 100%;
}
```
### Form elements and box-sizing
Across browsers, form elements use different box sizing rules for different widgets. You learned about the `box-sizing` property in [our box model lesson](/en-US/docs/Learn/CSS/Building_blocks/The_box_model) and you can use this knowledge when styling forms to ensure a consistent experience when setting widths and heights on form elements.
For consistency, it is a good idea to set margins and padding to `0` on all elements, then add these back in when styling particular controls:
```css
button,
input,
select,
textarea {
box-sizing: border-box;
padding: 0;
margin: 0;
}
```
### Other useful settings
In addition to the rules mentioned above, you should also set `overflow: auto` on `<textarea>`s to stop IE showing a scrollbar when there is no need for one:
```css
textarea {
overflow: auto;
}
```
### Putting it all together into a "reset"
As a final step, we can wrap up the various properties discussed above into the following "form reset" to provide a consistent base to work from. This includes all the items mentioned in the last three sections:
```css
button,
input,
select,
textarea {
font-family: inherit;
font-size: 100%;
box-sizing: border-box;
padding: 0;
margin: 0;
}
textarea {
overflow: auto;
}
```
> **Note:** Normalizing stylesheets are used by many developers to create a set of baseline styles to use on all projects. Typically these do similar things to those described above, making sure that anything different across browsers is set to a consistent default before you do your own work on the CSS. They are not as important as they once were, as browsers are typically more consistent than in the past. However if you want to take a look at one example, check out [Normalize.css](https://necolas.github.io/normalize.css/), which is a very popular stylesheet used as a base by many projects.
For further information on styling forms, take a look at the two articles in the HTML section of these guides.
- [Styling web forms](/en-US/docs/Learn/Forms/Styling_web_forms)
- [Advanced form styling](/en-US/docs/Learn/Forms/Advanced_form_styling)
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Images and form elements](/en-US/docs/Learn/CSS/Building_blocks/Images_tasks).
## Summary
This lesson has highlighted some of the differences you will encounter when working with images, media, and other unusual elements in CSS.
In the next article, we'll learn how to [style HTML tables](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables).
{{PreviousMenuNext("Learn/CSS/Building_blocks/Sizing_items_in_CSS", "Learn/CSS/Building_blocks/Styling_tables", "Learn/CSS/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn | data/mdn-content/files/en-us/learn/getting_started_with_the_web/index.md | ---
title: Getting started with the web
slug: Learn/Getting_started_with_the_web
page-type: learn-module
---
{{LearnSidebar}}
_Getting started with the web_ is a concise series introducing you to the practicalities of web development. You'll set up the tools you need to construct a simple webpage and publish your own simple code.
## The story of your first website
It's a lot of work to create a professional website, so if you're new to web development, we encourage you to start small. You won't build another Facebook right away, but it's not hard to make your own simple website online, so we'll start there.
## Guides
By working through the articles listed below, you will go from nothing to getting your first webpage online. Let's begin our journey!
- [Installing basic software](/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software)
- : When it comes to tools for building a website, there's a lot to pick from. If you're just starting, you might be confused by the array of code editors, frameworks, and testing tools out there. In this article, we will show you step-by-step how to install the software you need to begin some basic web development.
- [What will your website look like?](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like)
- : Before you start writing the code for your website, you should plan it first. What information are you showcasing? What fonts and colors are you using? Here we'll outline a simple method that you can follow to plan out your site's content and design.
- [Dealing with files](/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files)
- : A website consists of many files: text content, code, stylesheets, media content, and so on. When you're building a website, you need to assemble these files into a sensible structure and make sure they can talk to one another. This article explains how to set up a sensible file structure for your website and what issues you should be aware of.
- [HTML basics](/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics)
- : HyperText Markup Language (HTML) is the code that you use to structure your web content and give it meaning and purpose. For example, is my content a set of paragraphs or a list of bullet points? Do I have images inserted on my page? Do I have a data table? Without overwhelming you, this article will provide enough information to make you familiar with HTML.
- [CSS basics](/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics)
- : Cascading Style Sheets (CSS) is the code that you use to style your website. For example, do you want the text to be black or red? Where should content be drawn on the screen? What background images and colors should be used to decorate your website? In this article, we'll take you through what you need to get started.
- [JavaScript basics](/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics)
- : JavaScript is the programming language that you use to add interactive features to your website. Some examples could be games, things that happen when buttons are pressed or data is entered in forms, dynamic styling effects, animation, and much more. In this article, we'll give you an idea of what is possible with this exciting language, and how to get started.
- [Publishing your sample code](/en-US/docs/Learn/Getting_started_with_the_web/Publishing_your_website)
- : Once you have finished writing the code and organizing the files that make up your website, you need to put it all online so people can find it. This article describes how to get your simple sample code online with minimum effort.
- [How the web works](/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works)
- : When you access your favorite website, a lot of complicated things happen in the background that you may not know about. Here we will outline what happens when you view a webpage on your computer.
## See also
- [Web Demystified](https://www.youtube.com/playlist?list=PLo3w8EB99pqLEopnunz-dOOBJ8t-Wgt2g): A great series of videos explaining web fundamentals, aimed at complete beginners to web development. Created by [Jérémie Patonnier](https://github.com/JeremiePat).
- [The web and web standards](/en-US/docs/Learn/Getting_started_with_the_web/The_web_and_web_standards): This article provides some useful background on the Web — how it came about, what web standard technologies are, how they work together, why "web developer" is a great career to choose, and what kinds of best practices you'll learn about through the course.
| 0 |
data/mdn-content/files/en-us/learn/getting_started_with_the_web | data/mdn-content/files/en-us/learn/getting_started_with_the_web/what_will_your_website_look_like/index.md | ---
title: What will your website look like?
slug: Learn/Getting_started_with_the_web/What_will_your_website_look_like
page-type: learn-module-chapter
status:
- deprecated
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Getting_started_with_the_web/Installing_basic_software", "Learn/Getting_started_with_the_web/Dealing_with_files", "Learn/Getting_started_with_the_web")}}
_What will your website look like?_ discusses the planning and design work you have to do for your website before writing code, including "What information does my website offer?", "What fonts and colors do I want?", and "What does my site do?"
## First things first: planning
Before doing anything, you need some ideas. What should your website actually do? A website can do basically anything, but, for your first try, you should keep things simple. We'll start by creating a simple webpage with a heading, an image, and a few paragraphs.
To begin, you'll need to answer these questions:
1. **What is your website about?** Do you like dogs, New York, or Pac-Man?
2. **What information are you presenting on the subject?** Write a title and a few paragraphs and think of an image you'd like to show on your page.
3. **What does your website look like,** in simple high-level terms? What's the background color? What kind of font is appropriate: formal, cartoony, bold and loud, subtle?
> **Note:** Complex projects need detailed guidelines that go into all the details of colors, fonts, spacing between items on a page, appropriate writing style, and so on. This is sometimes called a design guide, design system, or brand book, and you can see an example at the [Firefox Photon Design System](https://design.firefox.com/photon/).
## Sketching out your design
Next, grab pen and paper and sketch out roughly how you want your site to look. For your first simple webpage, there's not much to sketch out, but you should get in the habit of doing this now. It really helps — you don't have to be Van Gogh!

> **Note:** Even on real, complex websites, the design teams usually start out with rough sketches on paper and later on build digital mockups using a graphics editor or web technologies.
>
> Web teams often include both a graphic designer and a {{Glossary("UX", "user experience")}} (UX) designer. Graphic designers put together the visuals of the website. UX designers have a somewhat more abstract role in addressing how users will experience and interact with the website.
## Choosing your assets
At this point, it's good to start putting together the content that will eventually appear on your webpage.
### Text
You should still have your paragraphs and title from earlier. Keep these close by.
### Theme color
To choose a color, go to [the Color Picker](/en-US/docs/Web/CSS/CSS_colors/Color_picker_tool) and find a color you like. When you click on a color, you'll see a strange six-character code like `#660066`. That's called a _hex code_ (short for hexadecimal), and represents your color. Copy the code down somewhere safe for now.

### Images
To choose an image, go to [Google Images](https://www.google.com/imghp) and search for something suitable.
1. When you find the image you want, click on the image to get an enlarged view of it.
2. Right-click the image (Ctrl + click on a Mac), choose _Save Image As…_, and choose a safe place to save your image. Alternatively, copy the image's web address from your browser's address bar for later use.

Note that most images on the web, including in Google Images, are copyrighted. To reduce your likelihood of violating copyright, you can use Google's license filter. Click on the _Tools_ button, then on the resulting _Usage rights_ option that appears below. You should choose the option _Creative Commons licenses_.

### Font
As with images, many fonts are protected by licenses, meaning you cannot freely use them in your site. [Google Fonts](https://developers.google.com/fonts) is a web service owned by Google that provides access to many fonts.
Once you have found a font, there are two main ways of using it:
1. Add a reference in your code to load the font from Google's servers.
2. Download the font file to your own system, host the font yourself, and use your hosted copy in your website's code.
> **Note:** Serving fonts hosted on Google Fonts may be incompatible with the European Union's data privacy regulation [GDPR](https://gdpr.eu/what-is-gdpr/) as the font service exposes the user's IP address. If this is a potential problem for you, choose the second option.
Alternatively you can use [safe web fonts](https://web.mit.edu/jmorzins/www/fonts.html) such as Arial, Times New Roman, or Courier New.
{{PreviousMenuNext("Learn/Getting_started_with_the_web/Installing_basic_software", "Learn/Getting_started_with_the_web/Dealing_with_files", "Learn/Getting_started_with_the_web")}}
| 0 |
data/mdn-content/files/en-us/learn/getting_started_with_the_web | data/mdn-content/files/en-us/learn/getting_started_with_the_web/installing_basic_software/index.md | ---
title: Installing basic software
slug: Learn/Getting_started_with_the_web/Installing_basic_software
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/Getting_started_with_the_web/What_will_your_website_look_like", "Learn/Getting_started_with_the_web")}}
In _Installing basic software_, we show you what tools you need to do simple web development and how to install them properly.
## What tools do I actually need, right now?
In this article, we'll set you up with the bare minimum — a text editor and some modern web browsers.
### Installing a text editor
You probably already have a basic text editor on your computer. By default Windows includes [Notepad](https://en.wikipedia.org/wiki/Microsoft_Notepad) and macOS comes with [TextEdit](https://en.wikipedia.org/wiki/TextEdit). Linux distros vary; the Ubuntu 22.04 LTS release comes with [GNOME Text Editor](https://en.wikipedia.org/wiki/GNOME_Text_Editor) by default.
For web development, you can probably do better than Notepad or TextEdit. We recommend starting with [Visual Studio Code](https://code.visualstudio.com/), which is a free editor, that offers live previews and code hints.
### Installing modern web browsers
For now, we'll install a couple of desktop web browsers to test our code in. Choose your operating system below and click the relevant links to download installers for your favorite browsers:
- Linux: [Firefox](https://www.mozilla.org/en-US/firefox/new/), [Chrome](https://www.google.com/chrome/), [Opera](https://www.opera.com/), [Brave](https://brave.com).
- Windows: [Firefox](https://www.mozilla.org/en-US/firefox/new/), [Chrome](https://www.google.com/chrome/), [Opera](https://www.opera.com/), [Microsoft Edge](https://www.microsoft.com/edge), [Brave](https://brave.com) (Windows 10 comes with Edge by default; otherwise, you should install an alternative browser).
- macOS: [Firefox](https://www.mozilla.org/en-US/firefox/new/), [Chrome](https://www.google.com/chrome/), [Opera](https://www.opera.com/), [Safari](https://www.apple.com/safari/), [Brave](https://brave.com) (macOS and iOS come with Safari by default).
Before going on, you should install at least two of these browsers and have them ready for testing.
### Installing a local web server
Some examples will need to be run by a web server to work successfully. You can find out how to do this in [How do you set up a local testing server?](/en-US/docs/Learn/Common_questions/Tools_and_setup/set_up_a_local_testing_server)
## What tools do the professionals use?
The following looks like a scary list, but fortunately, you can get started in web development without knowing anything about most of these.
- **A computer**. Maybe that sounds obvious to some people, but some of you are reading this article on your phone or a library computer. For serious web development, it's better to invest in a desktop or laptop computer running Windows, macOS or Linux.
- **A text editor**, to write code in. This could be a text editor (e.g. [Visual Studio Code](https://code.visualstudio.com/), [Notepad++](https://notepad-plus-plus.org/), [Sublime Text](https://www.sublimetext.com/), [GNU Emacs](https://www.gnu.org/software/emacs/), or [VIM](https://www.vim.org/)), or a hybrid editor (e.g. [Dreamweaver](https://www.adobe.com/products/dreamweaver.html) or [WebStorm](https://www.jetbrains.com/webstorm/)). Office document editors are not suitable for this use, as they rely on hidden elements that interfere with the rendering engines used by web browsers.
- **Web browsers**, to test code in. Currently, the most-used browsers are [Firefox](https://www.mozilla.org/en-US/firefox/new/), [Chrome](https://www.google.com/chrome/), [Safari](https://www.apple.com/safari/), and [Microsoft Edge](https://www.microsoft.com/edge). You should also test how your site performs on mobile devices and on any old browsers your target audience may still be using (such as IE 8–10). [Lynx](https://lynx.browser.org/), a text-based terminal web browser, is great for seeing how your site is experienced by visually-impaired users.
- **A graphics editor**, like [GIMP](https://www.gimp.org/), [Figma](https://www.figma.com/), [Paint.NET](https://www.getpaint.net/), [Photoshop](https://www.adobe.com/products/photoshop.html), [Sketch](https://www.sketch.com) or [XD](https://www.adobe.com/products/xd.html), to make images or graphics for your web pages.
- **A version control system**, to manage files on servers, collaborate on a project with a team, share code and assets and avoid editing conflicts. Right now, [Git](https://git-scm.com/) is the most popular version control system along with the [GitHub](https://github.com/) or [GitLab](https://about.gitlab.com/) hosting service.
- **An FTP program**, used on older web hosting accounts to manage files on servers ([Git](https://git-scm.com/) is increasingly replacing FTP for this purpose). There are loads of (S)FTP programs available including [Cyberduck](https://cyberduck.io/), [Fetch](https://fetchsoftworks.com/) and [FileZilla](https://filezilla-project.org/).
- **An automation system,** like [Webpack](https://webpack.js.org/), [Grunt](https://gruntjs.com/), or [Gulp](https://gulpjs.com/) to automatically perform repetitive tasks, such as minifying code and running tests.
- Libraries, frameworks, etc., to speed up writing common functionality. A library tends to be an existing JavaScript or CSS file that provides ready-rolled functionality for you to make use of in your code. A framework tends to take this idea further, offering a complete system with some custom syntaxes for you to write a web app on top of.
- More tools besides!
{{NextMenu("Learn/Getting_started_with_the_web/What_will_your_website_look_like", "Learn/Getting_started_with_the_web")}}
| 0 |
data/mdn-content/files/en-us/learn/getting_started_with_the_web | data/mdn-content/files/en-us/learn/getting_started_with_the_web/the_web_and_web_standards/index.md | ---
title: The web and web standards
slug: Learn/Getting_started_with_the_web/The_web_and_web_standards
page-type: guide
---
{{learnsidebar}}
This article provides some useful background on the Web — how it came about, what web standard technologies are, how they work together, why "web developer" is a great career to choose, and what kinds of best practices you'll learn about through the course.
## Brief history of the web
We'll keep this very brief, as there are many (more) detailed accounts of the web's history out there, which we'll link to later on (also try searching for "history of the web" in your favorite search engine and see what you get, if you are interested in more detail.)
In the late 1960s, the US military developed a communication network called [ARPANET](/en-US/docs/Glossary/Arpanet). This can be considered a forerunner of the Web, as it worked on [packet switching](https://en.wikipedia.org/wiki/Packet_switching), and featured the first implementation of the [TCP/IP](https://en.wikipedia.org/wiki/Internet_protocol_suite) protocol suite. These two technologies form the basis of the infrastructure that the internet is built on.
In 1980, Tim Berners-Lee (often referred to as TimBL) wrote a notebook program called ENQUIRE, which featured the concept of links between different nodes. Sound familiar?
Fast forward to 1989, and TimBL wrote [Information Management: A Proposal](https://www.w3.org/History/1989/proposal.html) and HyperText at CERN; these two publications together provided the background for how the web would work. They received a fair amount of interest, enough to convince TimBL's bosses to allow him to go ahead and create a global hypertext system.
By late 1990, TimBL had created all the things needed to run the first version of the web — [HTTP](/en-US/docs/Web/HTTP), [HTML](/en-US/docs/Web/HTML), the first web browser, which was called [WorldWideWeb](https://en.wikipedia.org/wiki/WorldWideWeb), an HTTP server, and some web pages to look at.
In the next few years that followed, the web exploded, with multiple browsers being released, thousands of web servers being set up, and millions of web pages being created. OK, that's a very simple summary of what happened, but we did promise you a brief summary.
One last significant data point to share is that in 1994, TimBL founded the [World Wide Web Consortium](https://en.wikipedia.org/wiki/World_Wide_Web_Consortium) (W3C), an organization that brings together representatives from many different technology companies to work together on the creation of web technology specifications. After that other technologies followed such as [CSS](/en-US/docs/Web/CSS) and [JavaScript](/en-US/docs/Web/JavaScript), and the web started to look more like the web we know today.
## Web standards
**Web standards** are the technologies we use to build websites. These standards exist as long technical documents called specifications, which detail exactly how the technology should work. These documents are not very useful for learning how to use the technologies they describe (this is why we have sites like MDN Web Docs), but instead are intended to be used by software engineers to implement these technologies (usually in web browsers).
For example, the [HTML Living Standard](https://html.spec.whatwg.org/multipage/) describes exactly how HTML (all the HTML elements, and their associated APIs, and other surrounding technologies) should be implemented.
Web standards are created by standards bodies — institutions that invite groups of people from different technology companies to come together and agree on how the technologies should work in the best way to fulfill all of their use cases. The W3C is the best known web standards body, but there are others such as the [WHATWG](https://whatwg.org/) (who maintain the living standards for the HTML language), [ECMA](https://www.ecma-international.org/) (who publish the standard for ECMAScript, which JavaScript is based on), [Khronos](https://www.khronos.org/) (who publish technologies for 3D graphics, such as WebGL), and others.
### "Open" standards
One of the key aspects of web standards, which TimBL and the W3C agreed on from the start, is that the web (and web technologies) should be free to both contribute and use, and not encumbered by patents/licensing. Therefore anyone can write the code to build a website for free, and anyone can contribute to the standards creation process, where the specs are written.
Because web technologies are created openly, in collaboration between many different companies, it means that no one company gets to control them, which is a really good thing. You wouldn't want a single company suddenly deciding to put the entire web behind a paywall, or releasing a new version of HTML that everyone has to buy to continue making websites, or worse still, just deciding they aren't interested any more and just turning it off.
This allows the web to remain a freely-available public resource.
### Don't break the web
Another phrase you'll hear around open web standards is "don't break the web" — the idea is that any new web technology that is introduced should be backwards compatible with what went before it (i.e. old websites will still continue to work), and forwards compatible (future technologies in turn will be compatible with what we currently have). As you go through the learning material presented here, you'll start to learn how this is made possible with some very clever design and implementation work.
## Being a web developer is good
The web industry is a very attractive market to enter if you are looking for a job. Recent published figures say that there are currently around 19 million web developers in the world, and that figure is set more than double in the next decade. And at the same time, there is a skill shortage in the industry — so what better time to learn web development?
It isn't all fun and games however — building websites is a more complicated proposition than it used to be, and you'll have to put some time in to studying all the different technologies you need to use, all the techniques and best practices you need to know, and all the typical patterns you'll be called upon to implement. It'll take you a few months to really start to get into it, and then you'll need to keep learning so that your knowledge stays up-to-date with all the new tools and features that appear on the web platform, and keep practicing and refining your craft.
_The only constant is change._
Does this sound hard? Don't worry — we aim to give you everything you need to know to get started, and things will get easier. Once you embrace the constant change and uncertainty of the web, you'll start to enjoy yourself. As a part of the web community, you'll have an entire web of contacts and useful material to help you, and you'll start to enjoy the creative possibilities it brings.
You're a digital creative now. Enjoy the experience, and the potential for earning a living.
## Overview of modern web technologies
There are a number of technologies to learn if you want to be a front-end web developer. In this section we will describe them briefly. For a more detailed explanation of how some of them work together, read our article [How the web works](/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works).
### Browsers
You are probably reading these words inside a web browser in this very moment (unless you've printed it out, or are using assistive technology, such as a screen reader to read it out to you). Web browsers are the software programs people use to consume the web, and include [Firefox](https://www.mozilla.org/en-US/firefox/), [Chrome](https://www.google.com/chrome/), [Opera](https://www.opera.com/), [Safari](https://www.apple.com/safari/), and [Edge](https://www.microsoft.com/en-us/edge).
### HTTP
Hypertext Transfer Protocol, or [HTTP](/en-US/docs/Web/HTTP/Basics_of_HTTP), is a messaging protocol that allows web browsers to communicate with web servers (where websites are stored). A typical conversation goes something like
```plain
"Hello web server. Can you give me the files I need to render bbc.co.uk"?
"Sure thing web browser — here you go"
[Downloads files and renders web page]
```
The actual syntax for HTTP messages (called requests and responses) is not that human-readable, but this gives you the basic idea.
### HTML, CSS, and JavaScript
[HTML](/en-US/docs/Web/HTML), [CSS](/en-US/docs/Web/CSS), and [JavaScript](/en-US/docs/Web/JavaScript) are the main three technologies you'll use to build a website:
- HyperText Markup Language, or **HTML**, is a markup language consisting of different elements you can wrap (mark up) content in to give it meaning (semantics) and structure. Simple HTML looks like this:
```html
<h1>This is a top-level heading</h1>
<p>This is a paragraph of text.</p>
<img src="cat.jpg" alt="A picture of my cat" />
```
If we adopted a house-building analogy, HTML would be like the foundations and walls of the house, which give it structure and hold it together.
- Cascading Style Sheets (**CSS**) is a rule-based language used to apply styles to your HTML — for example, setting text and background colors, adding borders, animating things, or laying out a page in a certain way. As a simple example, the following code would turn our HTML paragraph red:
```css
p {
color: red;
}
```
In the house analogy, CSS is like the paint, wallpaper, carpets and paintings you'd use to make the house look nice.
- **JavaScript** is the programming language we use to add interactivity to websites, from dynamic style switching, to fetching updates from the server, right through to complex 3D graphics. The following simple JavaScript will store a reference to our paragraph in memory and change the text inside it:
```js
let pElem = document.querySelector("p");
pElem.textContent = "We changed the text!";
```
In the house analogy, JavaScript is like the cooker, TV, Microwave, or hairdryer — the things that give your house useful functionality.
### Tools
Once you've learned the "raw" technologies that can be used to build web pages (such as HTML, CSS, and JavaScript), you'll soon start to come across various tools that can be used to make your work easier or more efficient. Examples include:
- The [developer tools](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools) inside modern browsers that can be used to debug your code.
- [Testing tools](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing) that can be used to run tests to show whether your code is behaving as you intended it to.
- Libraries and frameworks built on top of JavaScript that allow you to build certain types of website much more quickly and effectively.
- So-called "Linters", which take a set of rules, look at your code, and highlight places where you haven't followed the rules properly.
- Minifiers, which remove all the whitespace from your code files to make it so that they are smaller and therefore download from the server more quickly.
### Server-side languages and frameworks
HTML, CSS, and JavaScript are front-end (or client-side) languages, which means they are run by the browser to produce a website front-end that your users can use.
There are another class of languages called back-end (or server-side) languages, meaning that they are run on the server before the result is then sent to the browser to be displayed. A typical use for a server-side language is to get some data out of a database and generate some HTML to contain the data, before then sending the HTML over to the browser to display it to the user.
Example server-side frameworks include ASP.NET (in C#), Django (in Python), Laravel (in PHP), and Next.js (in JavaScript).
## Web best practices
We have briefly talked about the technologies that you'll use to build websites. Now let's discuss the best practices you should employ to make sure you are using those technologies in the best way that you can.
When doing web development, the main cause of uncertainty comes from the fact that you don't know what combination of technology each user will use to view your website:
- User 1 might be looking at it on an iPhone, with a small, narrow screen.
- User 2 might be looking at it on a Windows laptop with a widescreen monitor attached to it.
- User 3 might be blind, and using a screen reader to read the web page out to them.
- User 4 might be using a really old desktop machine that can't run modern browsers.
Because you don't know exactly what your users will use, you need to design defensively — make your website as flexible as possible, so that all of the above users can make use of it, even if they might not all get the same experience. In short, we are trying to make the web work for all, as much as possible.
You'll come across the below concepts at some point in your studies.
- **Cross-browser compatibility** is the practice of trying to make sure your webpage works across as many devices as possible. This includes using technologies that all the browsers support, delivering better experiences to browsers that can handle them (progressive enhancement), and/or writing code so that it falls back to a simpler but still usable experience in older browsers (graceful degradation). It also involves a lot of testing to see if anything fails in certain browsers, and then more work to fix those failures.
- **Responsive web design** is the practice of making your functionality and layouts flexible so they can automatically adapt to different browsers. An obvious example is a website that is laid out one way in a widescreen browser on the desktop, but displays as a more compact, single-column layout on mobile phone browsers. Try adjusting the width of your browser window now, and see what happens.
- **Performance** means getting websites to load as quickly as possible, but also making them intuitive and easy to use so that users don't get frustrated and go somewhere else.
- **Accessibility** means making your websites usable by as many different kinds of people as possible (related concepts are diversity and inclusion, and inclusive design). This includes people with visual impairments, hearing impairments, cognitive disabilities, or physical disabilities. It also goes beyond people with disabilities — how about young or old people, people from different cultures, people using mobile devices, or people with unreliable or slow network connections?
- **Internationalization** means making websites usable by people from different cultures, who speak different languages to your own. There are technical considerations here (such as altering your layout so that it still works OK for right-to-left, or even vertical languages), and human ones (such as using simple, non-slang language so that people who have your language as their second or third language are more likely to understand your text).
- **Privacy & Security**. These two concepts are related but different. Privacy refers to allowing people to go about their business privately and not spying on them or collecting more of their data than you absolutely need to. Security refers to constructing your website in a secure way so that malicious users cannot steal information contained on it from you or your users.
## See also
- [History of the World Wide Web](https://en.wikipedia.org/wiki/History_of_the_World_Wide_Web)
- [How does the internet work?](/en-US/docs/Learn/Common_questions/Web_mechanics/How_does_the_Internet_work)
| 0 |
data/mdn-content/files/en-us/learn/getting_started_with_the_web | data/mdn-content/files/en-us/learn/getting_started_with_the_web/publishing_your_website/index.md | ---
title: Publishing your website
slug: Learn/Getting_started_with_the_web/Publishing_your_website
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Getting_started_with_the_web/JavaScript_basics", "Learn/Getting_started_with_the_web/How_the_Web_works", "Learn/Getting_started_with_the_web")}}
Once you finish writing the code and organizing the files that make up your website, you need to put it all online so people can find it. This article explains how to get your simple sample code online with little effort.
## What are the options?
Publishing a website is a complex topic because there are many ways to go about it. This article doesn't attempt to document all the possible methods. Instead, it explains the advantages and disadvantages of three approaches that are practical for beginners. Then it steps through one method that can work right away for many readers.
### Getting hosting and a domain name
To have more control over content and website appearance, most people choose to buy web hosting and a domain name:
- Web hosting is rented file space on a hosting company's [web server](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_web_server). You put website files on the web server. The web server provides website content to website visitors.
- A [domain name](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_domain_name) is the unique address where people find your website, such as `https://www.mozilla.org` or `https://www.bbc.co.uk`. You can rent your domain name for as many years as you want from a **domain registrar**.
Many professional websites go online this way.
In addition, you will need a {{Glossary("FTP", "File Transfer Protocol (FTP)")}} program (see [How much does it cost: software](/en-US/docs/Learn/Common_questions/Tools_and_setup/How_much_does_it_cost#software) for more details) to actually transfer the website files over to the server. FTP programs vary widely, but generally, you have to connect to your web server using details provided by your hosting company (typically username, password, hostname). Then the program shows you your local files and the web server's files in two windows, and provides a way for you to transfer files back and forth.

#### Tips for finding hosting and domains
- MDN does not promote specific commercial hosting companies or domain name registrars. To find hosting companies and registrars, just search for "web hosting" and "domain names". All registrars will have a feature to allow you to check if the domain name you want is available.
- Your home or office {{Glossary("ISP", "internet service provider")}} may provide some limited hosting for a small website. The available feature set will be limited, but it might be perfect for your first experiments.
- There are also free services available like [Neocities](https://neocities.org/), [Google Sites](https://sites.google.com/), [Blogger](https://www.blogger.com), and [WordPress](https://wordpress.com/). Sometimes you get what you pay for, but sometimes these resources are good enough for your initial experiments.
- Many companies provide hosting and domains.
### Using an online tool like GitHub or Google App Engine
Some tools let you publish your website online:
- [GitHub](https://github.com/) is a "social coding" site. It allows you to upload code repositories for storage in the [Git](https://git-scm.com/) **version control system.** You can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your GitHub code, use it, learn from it, and improve on it. GitHub has a very useful feature called [GitHub Pages](https://pages.github.com/), which allows you to expose website code live on the web.
- [Google App Engine](https://cloud.google.com/appengine/) is a powerful platform that lets you build and run applications on Google's infrastructure — whether you need to build a multi-tiered web application from scratch or host a static website. See [How do you host your website on Google App Engine?](/en-US/docs/Learn/Common_questions/Tools_and_setup/How_do_you_host_your_website_on_Google_App_Engine) for more information.
These options are usually free, but you may outgrow the limited feature-set.
### Using a web-based IDE such as CodePen
There are a number of web apps that emulate a website development environment, allowing you to enter HTML, CSS and JavaScript, and then display the result of that code as a website — all in one browser tab. Generally speaking, these tools are relatively easy, great for learning, good for sharing code (for example, if you want to share a technique with or ask for debugging help from colleagues in a different office), and free (for basic features). They host your rendered page at a unique web address. However, the features are limited, and these apps usually don't provide hosting space for assets (like images).
Try playing with some of these examples to find out which one works best for you:
- [JSFiddle](https://jsfiddle.net/)
- [Glitch](https://glitch.com/)
- [JS Bin](https://jsbin.com/)
- [CodePen](https://codepen.io/)

## Publishing via GitHub
Now let's examine how to easily publish your site via GitHub Pages.
1. First of all, [sign up for GitHub](https://github.com/) and verify your email address.
2. Next, you need to [create a repository](https://github.com/new) to store files.
3. On this page, in the _Repository name_ box, enter _username_.github.io, where _username_ is your username. For example, our friend Bob Smith would enter _bobsmith.github.io_.
Check the "_Initialize this repository with a README"_ box. Then click _Create repository_.
4. Drag and drop the content of your website folder into your repository. Then click _Commit changes_.
> **Note:** Make sure your folder has an `index.html` file.
5. Navigate your browser to _username_.github.io to see your website online. For example, for the username _chrisdavidmills_, go to [_chrisdavidmills_.github.io](https://chrisdavidmills.github.io/).
> **Note:** It may take a few minutes for your website to go live. If your website does not display immediately, wait a few minutes. Try again.
To learn more, see [GitHub Pages Help](https://docs.github.com/en/pages/getting-started-with-github-pages).
## Further reading
- [What is a web server](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_web_server)
- [Understanding domain names](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_domain_name)
- [How much does it cost to do something on the web?](/en-US/docs/Learn/Common_questions/Tools_and_setup/How_much_does_it_cost)
- [Deploy a Website](https://www.codecademy.com/learn/deploy-a-website): A nice tutorial from Codecademy that goes a bit further and shows some additional techniques.
{{PreviousMenuNext("Learn/Getting_started_with_the_web/JavaScript_basics", "Learn/Getting_started_with_the_web/How_the_Web_works", "Learn/Getting_started_with_the_web")}}
| 0 |
data/mdn-content/files/en-us/learn/getting_started_with_the_web | data/mdn-content/files/en-us/learn/getting_started_with_the_web/html_basics/index.md | ---
title: HTML basics
slug: Learn/Getting_started_with_the_web/HTML_basics
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Getting_started_with_the_web/Dealing_with_files", "Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web")}}
HTML (**H**yper**T**ext **M**arkup **L**anguage) is the code that is used to structure a web page and its content. For example, content could be structured within a set of paragraphs, a list of bulleted points, or using images and data tables. As the title suggests, this article will give you a basic understanding of HTML and its functions.
## So what is HTML?
HTML is a _markup language_ that defines the structure of your content. HTML consists of a series of **{{Glossary("element", "elements")}}**, which you use to enclose, or wrap, different parts of the content to make it appear a certain way, or act a certain way. The enclosing {{Glossary("tag", "tags")}} can make a word or image hyperlink to somewhere else, can italicize words, can make the font bigger or smaller, and so on. For example, take the following line of content:
```plain
My cat is very grumpy
```
If we wanted the line to stand by itself, we could specify that it is a paragraph by enclosing it in paragraph tags:
```html
<p>My cat is very grumpy</p>
```
### Anatomy of an HTML element
Let's explore this paragraph element a bit further.

The main parts of our element are as follows:
1. **The opening tag:** This consists of the name of the element (in this case, p), wrapped in opening and closing **angle brackets**. This states where the element begins or starts to take effect — in this case where the paragraph begins.
2. **The closing tag:** This is the same as the opening tag, except that it includes a _forward slash_ before the element name. This states where the element ends — in this case where the paragraph ends. Failing to add a closing tag is one of the standard beginner errors and can lead to strange results.
3. **The content:** This is the content of the element, which in this case, is just text.
4. **The element:** The opening tag, the closing tag, and the content together comprise the element.
Elements can also have attributes that look like the following:

Attributes contain extra information about the element that you don't want to appear in the actual content. Here, `class` is the attribute _name_ and `editor-note` is the attribute _value_. The `class` attribute allows you to give the element a non-unique identifier that can be used to target it (and any other elements with the same `class` value) with style information and other things.
Some attributes have no value, such as [`required`](/en-US/docs/Web/HTML/Attributes/required).
Attributes that set a value always have:
1. A space between it and the element name (or the previous attribute, if the element already has one or more attributes).
2. The attribute name followed by an equal sign.
3. The attribute value wrapped by opening and closing quotation marks.
> **Note:** Simple attribute values that don't contain {{Glossary("ASCII")}} whitespace (or any of the characters `"` `'` `` ` `` `=` `<` `>`) can remain unquoted, but it is recommended that you quote all attribute values, as it makes the code more consistent and understandable.
### Nesting elements
You can put elements inside other elements too — this is called **nesting**. If we wanted to state that our cat is **very** grumpy, we could wrap the word "very" in a {{htmlelement("strong")}} element, which means that the word is to be strongly emphasized:
```html
<p>My cat is <strong>very</strong> grumpy.</p>
```
You do however need to make sure that your elements are properly nested. In the example above, we opened the {{htmlelement("p")}} element first, then the {{htmlelement("strong")}} element; therefore, we have to close the {{htmlelement("strong")}} element first, then the {{htmlelement("p")}} element. The following is incorrect:
```html-nolint example-bad
<p>My cat is <strong>very grumpy.</p></strong>
```
The elements have to open and close correctly so that they are clearly inside or outside one another. If they overlap as shown above, then your web browser will try to make the best guess at what you were trying to say, which can lead to unexpected results. So don't do it!
### Void elements
Some elements have no content and are called **{{glossary("void element", "void elements")}}**. Take the {{htmlelement("img")}} element that we already have in our HTML page:
```html
<img src="images/firefox-icon.png" alt="My test image" />
```
This contains two attributes, but there is no closing `</img>` tag and no inner content. This is because an image element doesn't wrap content to affect it. Its purpose is to embed an image in the HTML page in the place it appears.
### Anatomy of an HTML document
That wraps up the basics of individual HTML elements, but they aren't handy on their own. Now we'll look at how individual elements are combined to form an entire HTML page. Let's revisit the code we put into our `index.html` example (which we first met in the [Dealing with files](/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files) article):
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>My test page</title>
</head>
<body>
<img src="images/firefox-icon.png" alt="My test image" />
</body>
</html>
```
Here, we have the following:
- `<!DOCTYPE html>` — [doctype](/en-US/docs/Glossary/Doctype). It is a required preamble. In the mists of time, when HTML was young (around 1991/92), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other useful things. However, these days, they don't do much and are basically just needed to make sure your document behaves correctly. That's all you need to know for now.
- `<html></html>` — the {{htmlelement("html")}} element. This element wraps all the content on the entire page and is sometimes known as the root element. It also includes the `lang` attribute, setting the primary language of the document.
- `<head></head>` — the {{htmlelement("head")}} element. This element acts as a container for all the stuff you want to include on the HTML page that _isn't_ the content you are showing to your page's viewers. This includes things like {{Glossary("keyword", "keywords")}} and a page description that you want to appear in search results, CSS to style our content, character set declarations, and more.
- `<meta charset="utf-8">` — This element sets the character set your document should use to UTF-8 which includes most characters from the vast majority of written languages. Essentially, it can now handle any textual content you might put on it. There is no reason not to set this, and it can help avoid some problems later on.
- `<meta name="viewport" content="width=device-width">` — This [viewport element](/en-US/docs/Web/CSS/Viewport_concepts#mobile_viewports) ensures the page renders at the width of viewport, preventing mobile browsers from rendering pages wider than the viewport and then shrinking them down.
- `<title></title>` — the {{htmlelement("title")}} element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in. It is also used to describe the page when you bookmark/favorite it.
- `<body></body>` — the {{htmlelement("body")}} element. This contains _all_ the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks, or whatever else.
## Images
Let's turn our attention to the {{htmlelement("img")}} element again:
```html
<img src="images/firefox-icon.png" alt="My test image" />
```
As we said before, it embeds an image into our page in the position it appears. It does this via the `src` (source) attribute, which contains the path to our image file.
We have also included an `alt` (alternative) attribute. In the [`alt` attribute](/en-US/docs/Web/HTML/Element/img#authoring_meaningful_alternate_descriptions), you specify descriptive text for users who cannot see the image, possibly because of the following reasons:
1. They are visually impaired. Users with significant visual impairments often use tools called screen readers to read out the alt text to them.
2. Something has gone wrong causing the image not to display. For example, try deliberately changing the path inside your `src` attribute to make it incorrect. If you save and reload the page, you should see something like this in place of the image:

The keywords for alt text are "descriptive text". The alt text you write should provide the reader with enough information to have a good idea of what the image conveys. In this example, our current text of "My test image" is no good at all. A much better alternative for our Firefox logo would be "The Firefox logo: a flaming fox surrounding the Earth."
Try coming up with some better alt text for your image now.
> **Note:** Find out more about accessibility in our [accessibility learning module](/en-US/docs/Learn/Accessibility).
## Marking up text
This section will cover some essential HTML elements you'll use for marking up the text.
### Headings
Heading elements allow you to specify that certain parts of your content are headings — or subheadings. In the same way that a book has the main title, chapter titles, and subtitles, an HTML document can too. HTML contains 6 heading levels, {{htmlelement("Heading_Elements", "<h1> - <h6>")}}, although you'll commonly only use 3 to 4 at most:
```html
<!-- 4 heading levels: -->
<h1>My main title</h1>
<h2>My top level heading</h2>
<h3>My subheading</h3>
<h4>My sub-subheading</h4>
```
> **Note:** Anything in HTML between `<!--` and `-->` is an **HTML comment**. The browser ignores comments as it renders the code. In other words, they are not visible on the page - just in the code. HTML comments are a way for you to write helpful notes about your code or logic.
Now try adding a suitable title to your HTML page just above your {{htmlelement("img")}} element.
> **Note:** You'll see that your heading level 1 has an implicit style. Don't use heading elements to make text bigger or bold, because they are used for [accessibility](/en-US/docs/Learn/Accessibility/HTML#text_content) and [other reasons such as SEO](/en-US/docs/Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals#why_do_we_need_structure). Try to create a meaningful sequence of headings on your pages, without skipping levels.
### Paragraphs
As explained above, {{htmlelement("p")}} elements are for containing paragraphs of text; you'll use these frequently when marking up regular text content:
```html
<p>This is a single paragraph</p>
```
Add your sample text (you should have it from [_What will your website look like?_](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like)) into one or a few paragraphs, placed directly below your {{htmlelement("img")}} element.
### Lists
A lot of the web's content is lists and HTML has special elements for these. Marking up lists always consists of at least 2 elements. The most common list types are ordered and unordered lists:
1. **Unordered lists** are for lists where the order of the items doesn't matter, such as a shopping list. These are wrapped in a {{htmlelement("ul")}} element.
2. **Ordered lists** are for lists where the order of the items does matter, such as a recipe. These are wrapped in an {{htmlelement("ol")}} element.
Each item inside the lists is put inside an {{htmlelement("li")}} (list item) element.
For example, if we wanted to turn the part of the following paragraph fragment into a list
```html
<p>
At Mozilla, we're a global community of technologists, thinkers, and builders
working together…
</p>
```
We could modify the markup to this
```html
<p>At Mozilla, we're a global community of</p>
<ul>
<li>technologists</li>
<li>thinkers</li>
<li>builders</li>
</ul>
<p>working together…</p>
```
Try adding an ordered or unordered list to your example page.
## Links
Links are very important — they are what makes the web a web! To add a link, we need to use a simple element — {{htmlelement("a")}} — "a" being the short form for "anchor". To make text within your paragraph into a link, follow these steps:
1. Choose some text. We chose the text "Mozilla Manifesto".
2. Wrap the text in an {{htmlelement("a")}} element, as shown below:
```html
<a>Mozilla Manifesto</a>
```
3. Give the {{htmlelement("a")}} element an `href` attribute, as shown below:
```html
<a href="">Mozilla Manifesto</a>
```
4. Fill in the value of this attribute with the web address that you want the link to:
```html
<a href="https://www.mozilla.org/en-US/about/manifesto/">
Mozilla Manifesto
</a>
```
You might get unexpected results if you omit the `https://` or `http://` part, called the _protocol_, at the beginning of the web address. After making a link, click it to make sure it is sending you where you wanted it to.
> **Note:** `href` might appear like a rather obscure choice for an attribute name at first. If you are having trouble remembering it, remember that it stands for _**h**ypertext **ref**erence_.
Add a link to your page now, if you haven't already done so.
## Conclusion
If you have followed all the instructions in this article, you should end up with a page that looks like the one below (you can also [view it here](https://mdn.github.io/beginner-html-site/)):

If you get stuck, you can always compare your work with our [finished example code](https://github.com/mdn/beginner-html-site/blob/gh-pages/index.html) on GitHub.
Here, we have only really scratched the surface of HTML. To find out more, go to our [Learning HTML](/en-US/docs/Learn/HTML) topic.
{{PreviousMenuNext("Learn/Getting_started_with_the_web/Dealing_with_files", "Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web")}}
| 0 |
data/mdn-content/files/en-us/learn/getting_started_with_the_web | data/mdn-content/files/en-us/learn/getting_started_with_the_web/how_the_web_works/index.md | ---
title: How the web works
slug: Learn/Getting_started_with_the_web/How_the_Web_works
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenu("Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}
_How the web works_ provides a simplified view of what happens when you view a webpage in a web browser on your computer or phone.
This theory is not essential to writing web code in the short term, but before long you'll really start to benefit from understanding what's happening in the background.
## Clients and servers
Computers connected to the internet are called **clients** and **servers**. A simplified diagram of how they interact might look like this:

- Clients are the typical web user's internet-connected devices (for example, your computer connected to your Wi-Fi, or your phone connected to your mobile network) and web-accessing software available on those devices (usually a web browser like Firefox or Chrome).
- Servers are computers that store webpages, sites, or apps. When a client device wants to access a webpage, a copy of the webpage is downloaded from the server onto the client machine to be displayed in the user's web browser.
## The other parts of the toolbox
The client and server we've described above don't tell the whole story. There are many other parts involved, and we'll describe them below.
For now, let's imagine that the web is a road. On one end of the road is the client, which is like your house. On the other end of the road is the server, which is a shop you want to buy something from.

In addition to the client and the server, we also need to say hello to:
- **Your internet connection**: Allows you to send and receive data on the web. It's basically like the street between your house and the shop.
- **TCP/IP**: Transmission Control Protocol and Internet Protocol are communication protocols that define how data should travel across the internet. This is like the transport mechanisms that let you place an order, go to the shop, and buy your goods. In our example, this is like a car or a bike (or however else you might get around).
- **DNS**: Domain Name System is like an address book for websites. When you type a web address in your browser, the browser looks at the DNS to find the website's IP address before it can retrieve the website. The browser needs to find out which server the website lives on, so it can send HTTP messages to the right place (see below). This is like looking up the address of the shop so you can access it.
- **HTTP**: Hypertext Transfer Protocol is an application {{Glossary("Protocol", "protocol")}} that defines a language for clients and servers to speak to each other. This is like the language you use to order your goods.
- **Component files**: A website is made up of many different files, which are like the different parts of the goods you buy from the shop. These files come in two main types:
- **Code files**: Websites are built primarily from HTML, CSS, and JavaScript, though you'll meet other technologies a bit later.
- **Assets**: This is a collective name for all the other stuff that makes up a website, such as images, music, video, Word documents, and PDFs.
## So what happens, exactly?
When you type a web address into your browser (for our analogy that's like walking to the shop):
1. The browser goes to the DNS server, and finds the real address of the server that the website lives on (you find the address of the shop).
2. The browser sends an HTTP request message to the server, asking it to send a copy of the website to the client (you go to the shop and order your goods). This message, and all other data sent between the client and the server, is sent across your internet connection using TCP/IP.
3. If the server approves the client's request, the server sends the client a "200 OK" message, which means "Of course you can look at that website! Here it is", and then starts sending the website's files to the browser as a series of small chunks called data packets (the shop gives you your goods, and you bring them back to your house).
4. The browser assembles the small chunks into a complete web page and displays it to you (the goods arrive at your door — new shiny stuff, awesome!).
## Order in which component files are parsed
When browsers send requests to servers for HTML files, those HTML files often contain {{htmlelement("link")}} elements referencing external [CSS](/en-US/docs/Learn/CSS) stylesheets and {{htmlelement("script")}} elements referencing external [JavaScript](/en-US/docs/Learn/JavaScript) scripts. It's important to know the order in which those files are [parsed by the browser](/en-US/docs/Web/Performance/How_browsers_work#parsing) as the browser loads the page:
- The browser parses the HTML file first, and that leads to the browser recognizing any `<link>`-element references to external CSS stylesheets and any `<script>`-element references to scripts.
- As the browser parses the HTML, it sends requests back to the server for any CSS files it has found from `<link>` elements, and any JavaScript files it has found from `<script>` elements, and from those, then parses the CSS and JavaScript.
- The browser generates an in-memory [DOM](/en-US/docs/Web/API/Document_Object_Model) tree from the parsed HTML, generates an in-memory [CSSOM](/en-US/docs/Glossary/CSSOM) structure from the parsed CSS, and [compiles and executes](/en-US/docs/Web/Performance/How_browsers_work#javascript_compilation) the parsed JavaScript.
- As the browser builds the DOM tree and applies the styles from the CSSOM tree and executes the JavaScript, a visual representation of the page is painted to the screen, and the user sees the page content and can begin to interact with it.
## DNS explained
Real web addresses aren't the nice, memorable strings you type into your address bar to find your favorite websites. They are special numbers that look like this: `192.0.2.172`.
This is called an {{Glossary("IP Address", "IP address")}}, and it represents a unique location on the web. However, it's not very easy to remember, is it? That's why the Domain Name System was invented. This system uses special servers that match up a web address you type into your browser (like "mozilla.org") to the website's real (IP) address.
Websites can be reached directly via their IP addresses. You can use a [DNS lookup tool](https://www.nslookup.io/website-to-ip-lookup/) to find the IP address of a website.
## Packets explained
Earlier we used the term "packets" to describe the format in which the data is transferred between the client and server. What do we mean here? Basically, when data is sent across the web, it is sent in thousands of small chunks. There are multiple reasons why data is sent in small packets. They are sometimes dropped or corrupted, and it's easier to replace small chunks when this happens. Additionally, the packets can be routed along different paths, making the exchange faster and allowing many different users to download the same website at the same time. If each website was sent as a single big chunk, only one user could download it at a time, which obviously would make the web very inefficient and not much fun to use.
## See also
- [How the Internet works](/en-US/docs/Learn/Common_questions/Web_mechanics/How_does_the_Internet_work)
- [HTTP — an Application-Level Protocol](https://dev.opera.com/articles/http-basic-introduction/)
- [HTTP: Let's GET It On!](https://dev.opera.com/articles/http-lets-get-it-on/)
- [HTTP: Response Codes](https://dev.opera.com/articles/http-response-codes/)
## Credit
Street photo: [Street composing](https://www.pinterest.com/pin/400538960580676851/), by [kevin digga](https://www.pinterest.com/kevindigga/).
{{PreviousMenu("Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}
| 0 |
data/mdn-content/files/en-us/learn/getting_started_with_the_web | data/mdn-content/files/en-us/learn/getting_started_with_the_web/css_basics/index.md | ---
title: CSS basics
slug: Learn/Getting_started_with_the_web/CSS_basics
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Getting_started_with_the_web/HTML_basics", "Learn/Getting_started_with_the_web/JavaScript_basics", "Learn/Getting_started_with_the_web")}}
CSS (Cascading Style Sheets) is the code that styles web content. _CSS basics_ walks through what you need to get started. We'll answer questions like: How do I make text red? How do I make content display at a certain location in the (webpage) layout? How do I decorate my webpage with background images and colors?
## What is CSS?
Like HTML, CSS is not a programming language. It's not a markup language either. **CSS is a style sheet language.** CSS is what you use to selectively style HTML elements. For example, this CSS selects paragraph text, setting the color to red:
```css
p {
color: red;
}
```
Let's try it out! Using a text editor, paste the three lines of CSS (above) into a new file. Save the file as `style.css` in a directory named `styles`.
To make the code work, we still need to apply this CSS (above) to your HTML document. Otherwise, the styling won't change the appearance of the HTML. (If you haven't been following our project, pause here to read [Dealing with files](/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files) and [HTML basics](/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics).)
1. Open your `index.html` file. Paste the following line in the head (between the {{HTMLElement("head")}} and `</head>` tags):
```html
<link href="styles/style.css" rel="stylesheet" />
```
2. Save `index.html` and load it in your browser. You should see something like this:
If your paragraph text is red, congratulations! Your CSS is working.
### Anatomy of a CSS ruleset
Let's dissect the CSS code for red paragraph text to understand how it works:

The whole structure is called a **ruleset**. (The term _ruleset_ is often referred to as just _rule_.) Note the names of the individual parts:
- Selector
- : This is the HTML element name at the start of the ruleset. It defines the element(s) to be styled (in this example, {{HTMLElement("p")}} elements). To style a different element, change the selector.
- Declaration
- : This is a single rule like `color: red;`. It specifies which of the element's **properties** you want to style.
- Properties
- : These are ways in which you can style an HTML element. (In this example, `color` is a property of the {{htmlelement("p")}} elements.) In CSS, you choose which properties you want to affect in the rule.
- Property value
- : To the right of the property—after the colon—there is the **property value**. This chooses one out of many possible appearances for a given property. (For example, there are many `color` values in addition to `red`.)
Note the other important parts of the syntax:
- Apart from the selector, each ruleset must be wrapped in curly braces. (`{}`)
- Within each declaration, you must use a colon (`:`) to separate the property from its value or values.
- Within each ruleset, you must use a semicolon (`;`) to separate each declaration from the next one.
To modify multiple property values in one ruleset, write them separated by semicolons, like this:
```css
p {
color: red;
width: 500px;
border: 1px solid black;
}
```
### Selecting multiple elements
You can also select multiple elements and apply a single ruleset to all of them. Separate multiple selectors by commas. For example:
```css
p,
li,
h1 {
color: red;
}
```
### Different types of selectors
There are many different types of selectors. The examples above use **element selectors**, which select all elements of a given type. But we can make more specific selections as well. Here are some of the more common types of selectors:
<table class="standard-table no-markdown">
<thead>
<tr>
<th scope="col">Selector name</th>
<th scope="col">What does it select</th>
<th scope="col">Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>Element selector (sometimes called a tag or type selector)</td>
<td>All HTML elements of the specified type.</td>
<td><code>p</code><br />selects <code><p></code></td>
</tr>
<tr>
<td>ID selector</td>
<td>
The element on the page with the specified ID. On a given HTML page,
each id value should be unique.
</td>
<td>
<code>#my-id</code><br />selects <code><p id="my-id"></code> or
<code><a id="my-id"></code>
</td>
</tr>
<tr>
<td>Class selector</td>
<td>
The element(s) on the page with the specified class. Multiple instances
of the same class can appear on a page.
</td>
<td>
<code>.my-class</code><br />selects
<code><p class="my-class"></code> and
<code><a class="my-class"></code>
</td>
</tr>
<tr>
<td>Attribute selector</td>
<td>The element(s) on the page with the specified attribute.</td>
<td>
<code>img[src]</code><br />selects
<code><img src="myimage.png"></code> but not
<code><img></code>
</td>
</tr>
<tr>
<td>Pseudo-class selector</td>
<td>
The specified element(s), but only when in the specified state. (For
example, when a cursor hovers over a link.)
</td>
<td>
<code>a:hover</code><br />selects <code><a></code>, but only when
the mouse pointer is hovering over the link.
</td>
</tr>
</tbody>
</table>
There are many more selectors to discover. To learn more, see the MDN [Selectors guide](/en-US/docs/Learn/CSS/Building_blocks/Selectors).
## Fonts and text
Now that we've explored some CSS fundamentals, let's improve the appearance of the example by adding more rules and information to the `style.css` file.
1. First, find the [output from Google Fonts](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like#font) that you previously saved from [What will your website look like?](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like). Add the {{htmlelement("link")}} element somewhere inside your `index.html`'s head (anywhere between the {{HTMLElement("head")}} and `</head>` tags). It looks something like this:
```html
<link
href="https://fonts.googleapis.com/css?family=Open+Sans"
rel="stylesheet" />
```
This code links your page to a style sheet that loads the Open Sans font family with your webpage.
2. Next, delete the existing rule you have in your `style.css` file. It was a good test, but let's not continue with lots of red text.
3. Add the following lines (shown below), replacing the `font-family` assignment with your `font-family` selection from [What will your website look like?](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like#font). The property `font-family` refers to the font(s) you want to use for text. This rule defines a global base font and font size for the whole page. Since {{HTMLElement("html")}} is the parent element of the whole page, all elements inside it inherit the same `font-size` and `font-family`.
```css
html {
font-size: 10px; /* px means "pixels": the base font size is now 10 pixels high */
font-family: "Open Sans", sans-serif; /* this should be the rest of the output you got from Google Fonts */
}
```
> **Note:** Anything in CSS between `/*` and `*/` is a **CSS comment**. The browser ignores comments as it renders the code. CSS comments are a way for you to write helpful notes about your code or logic.
4. Now let's set font sizes for elements that will have text inside the HTML body ({{htmlelement("Heading_Elements", "<h1>")}}, {{htmlelement("li")}}, and {{htmlelement("p")}}). We'll also center the heading. Finally, let's expand the second ruleset (below) with settings for line height and letter spacing to make body content more readable.
```css
h1 {
font-size: 60px;
text-align: center;
}
p,
li {
font-size: 16px;
line-height: 2;
letter-spacing: 1px;
}
```
Adjust the `px` values as you like. Your work-in-progress should look similar to this:

## CSS: all about boxes
Something you'll notice about writing CSS: a lot of it is about boxes. This includes setting size, color, and position. Most HTML elements on your page can be thought of as boxes sitting on top of other boxes.

Photo from [https://www.geograph.org.uk/photo/3418115](https://www.geograph.org.uk/photo/3418115) Copyright © [Jim Barton](https://www.geograph.org.uk/profile/26362) [cc-by-sa/2.0](https://creativecommons.org/licenses/by-sa/2.0/)
CSS layout is mostly based on the _box model._ Each box taking up space on your page has properties like:
- `padding`, the space around the content. In the example below, it is the space around the paragraph text.
- `border`, the solid line that is just outside the padding.
- `margin`, the space around the outside of the border.

In this section we also use:
- `width` (of an element).
- `background-color`, the color behind an element's content and padding.
- `color`, the color of an element's content (usually text).
- `text-shadow` sets a drop shadow on the text inside an element.
- `display` sets the display mode of an element. (keep reading to learn more)
To continue, let's add more CSS. Keep adding these new rules at the bottom of `style.css`. Experiment with changing values to see what happens.
### Changing the page color
```css
html {
background-color: #00539f;
}
```
This rule sets a background color for the entire page. Change the color code to [the color you chose in What will my website look like?](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like#theme_color).
### Styling the body
```css
body {
width: 600px;
margin: 0 auto;
background-color: #ff9500;
padding: 0 20px 20px 20px;
border: 5px solid black;
}
```
There are several declarations for the {{htmlelement("body")}} element. Let's go through these line-by-line:
- `width: 600px;` This forces the body to always be 600 pixels wide.
- `margin: 0 auto;` When you set two values on a property like `margin` or `padding`, the first value affects the element's top _and_ bottom side (setting it to `0` in this case); the second value affects the left _and_ right side. (Here, `auto` is a special value that divides the available horizontal space evenly between left and right). You can also use one, two, three, or four values, as documented in [Margin Syntax](/en-US/docs/Web/CSS/margin#syntax).
- `background-color: #FF9500;` This sets the element's background color. This project uses a reddish orange for the body background color, as opposed to dark blue for the {{htmlelement("html")}} element. (Feel free to experiment.)
- `padding: 0 20px 20px 20px;` This sets four values for padding. The goal is to put some space around the content. In this example, there is no padding on the top of the body, and 20 pixels on the right, bottom and left. The values set top, right, bottom, left, in that order. As with `margin`, you can use one, two, three, or four values, as documented in [Padding Syntax](/en-US/docs/Web/CSS/padding#syntax).
- `border: 5px solid black;` This sets values for the width, style and color of the border. In this case, it's a five-pixel–wide, solid black border, on all sides of the body.
### Positioning and styling the main page title
```css
h1 {
margin: 0;
padding: 20px 0;
color: #00539f;
text-shadow: 3px 3px 1px black;
}
```
You may have noticed there's a horrible gap at the top of the body. That happens because browsers apply default styling to the {{htmlelement("Heading_Elements", "h1")}} element (among others). That might seem like a bad idea, but the intent is to provide basic readability for unstyled pages. To eliminate the gap, we overwrite the browser's default styling with the setting `margin: 0;`.
Next, we set the heading's top and bottom padding to 20 pixels.
Following that, we set the heading text to be the same color as the HTML background color.
Finally, `text-shadow` applies a shadow to the text content of the element. Its four values are:
- The first pixel value sets the **horizontal offset** of the shadow from the text: how far it moves across.
- The second pixel value sets the **vertical offset** of the shadow from the text: how far it moves down.
- The third pixel value sets the **blur radius** of the shadow. A larger value produces a more fuzzy-looking shadow.
- The fourth value sets the base color of the shadow.
Try experimenting with different values to see how it changes the appearance.
### Centering the image
```css
img {
display: block;
margin: 0 auto;
}
```
Next, we center the image to make it look better. We could use the `margin: 0 auto` trick again as we did for the body. But there are differences that require an additional setting to make the CSS work.
The {{htmlelement("body")}} is a **block** element, meaning it takes up space on the page. The margin applied to a block element will be respected by other elements on the page. In contrast, images are **inline** elements, for the auto margin trick to work on this image, we must give it block-level behavior using `display: block;`.
> **Note:** The instructions above assume that you're using an image smaller than the width set on the body. (600 pixels) If your image is larger, it will overflow the body, spilling into the rest of the page. To fix this, you can either: 1) reduce the image width using a [graphics editor](https://en.wikipedia.org/wiki/Raster_graphics_editor), or 2) use CSS to size the image by setting the {{cssxref("width")}} property on the `<img>` element with a smaller value.
> **Note:** Don't be too concerned if you don't completely understand `display: block;` or the differences between a block element and an inline element. It will make more sense as you continue your study of CSS. You can find more information about different display values on MDN's [display reference page](/en-US/docs/Web/CSS/display).
## Conclusion
If you followed all the instructions in this article, you should have a page that looks similar to this one:

(You can [view our version here](https://mdn.github.io/beginner-html-site-styled/).) If you get stuck, you can always compare your work with our [finished example code on GitHub](https://github.com/mdn/beginner-html-site-styled/blob/gh-pages/styles/style.css).
In this exercise, we have just scratched the surface of CSS. To go further, see [Learning to style HTML using CSS](/en-US/docs/Learn/CSS).
{{PreviousMenuNext("Learn/Getting_started_with_the_web/HTML_basics", "Learn/Getting_started_with_the_web/JavaScript_basics", "Learn/Getting_started_with_the_web")}}
| 0 |
data/mdn-content/files/en-us/learn/getting_started_with_the_web | data/mdn-content/files/en-us/learn/getting_started_with_the_web/javascript_basics/index.md | ---
title: JavaScript basics
slug: Learn/Getting_started_with_the_web/JavaScript_basics
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}
JavaScript is a programming language that adds interactivity to your website. This happens in games, in the behavior of responses when buttons are pressed or with data entry on forms; with dynamic styling; with animation, etc.
This article helps you get started with JavaScript and furthers your understanding of what is possible.
## What is JavaScript?
{{Glossary("JavaScript")}} is a powerful programming language that can add interactivity to a website.
It was invented by Brendan Eich.
JavaScript is versatile and beginner-friendly.
With more experience, you'll be able to create games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more!
JavaScript itself is relatively compact, yet very flexible. Developers have written a variety of tools on top of the core JavaScript language, unlocking a vast amount of functionality with minimum effort. These include:
- Browser Application Programming Interfaces ({{Glossary("API","APIs")}}) built into web browsers, providing functionality such as dynamically creating HTML and setting CSS styles; collecting and manipulating a video stream from a user's webcam, or generating 3D graphics and audio samples.
- Third-party APIs that allow developers to incorporate functionality in sites from other content providers, such as [Disqus](https://disqus.com/) or Facebook.
- Third-party frameworks and libraries that you can apply to HTML to accelerate the work of building sites and applications.
It's outside the scope of this article—as a light introduction to JavaScript—to present the details of how the core JavaScript language is different from the tools listed above. You can learn more in MDN's [JavaScript learning area](/en-US/docs/Learn/JavaScript), as well as in other parts of MDN.
The section below introduces some aspects of the core language and offers an opportunity to play with a few browser API features too. Have fun!
## A "Hello world!" example
JavaScript is one of the most popular modern web technologies! As your JavaScript skills grow, your websites will enter a new dimension of power and creativity.
However, getting comfortable with JavaScript is more challenging than getting comfortable with HTML and CSS. You may have to start small, and progress gradually. To begin, let's examine how to add JavaScript to your page for creating a _Hello world!_ example. (_Hello world!_ is [the standard for introductory programming examples](https://en.wikipedia.org/wiki/%22Hello,_World!%22_program).)
> **Warning:** If you haven't been following along with the rest of our course, [download this example code](https://codeload.github.com/mdn/beginner-html-site-styled/zip/refs/heads/gh-pages) and use it as a starting point.
1. Go to your test site and create a new folder named `scripts`. Within the scripts folder, create a new text document called `main.js`, and save it.
2. In your `index.html` file, enter this code on a new line, just before the closing `</body>` tag:
```html
<script src="scripts/main.js"></script>
```
3. This is doing the same job as the {{htmlelement("link")}} element for CSS. It applies the JavaScript to the page, so it can have an effect on the HTML (along with the CSS, and anything else on the page).
4. Add this code to the `main.js` file:
```js
const myHeading = document.querySelector("h1");
myHeading.textContent = "Hello world!";
```
5. Make sure the HTML and JavaScript files are saved. Then load `index.html` in your browser. You should see something like this:

> **Note:** The reason the instructions (above) place the {{htmlelement("script")}} element near the bottom of the HTML file is that **the browser reads code in the order it appears in the file**.
>
> If the JavaScript loads first and it is supposed to affect the HTML that hasn't loaded yet, there could be problems. Placing JavaScript near the bottom of an HTML page is one way to accommodate this dependency. To learn more about alternative approaches, see [Script loading strategies](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#script_loading_strategies).
### What happened?
The heading text changed to _Hello world!_ using JavaScript. You did this by using a function called {{domxref("Document.querySelector", "querySelector()")}} to grab a reference to your heading, and then store it in a variable called `myHeading`. This is similar to what we did using CSS selectors. When you want to do something to an element, you need to select it first.
Following that, the code set the value of the `myHeading` variable's {{domxref("Node.textContent", "textContent")}} property (which represents the content of the heading) to _Hello world!_.
> **Note:** Both of the features you used in this exercise are parts of the [Document Object Model (DOM) API](/en-US/docs/Web/API/Document_Object_Model), which has the capability to manipulate documents.
## Language basics crash course
To give you a better understanding of how JavaScript works, let's explain some of the core features of the language. It's worth noting that these features are common to all programming languages. If you master these fundamentals, you have a head start on coding in other languages too!
> **Warning:** In this article, try entering the example code lines into your JavaScript console to see what happens. For more details on JavaScript consoles, see [Discover browser developer tools](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools).
### Variables
{{Glossary("Variable", "Variables")}} are containers that store values. You start by declaring a variable with the [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) keyword, followed by the name you give to the variable:
```js
let myVariable;
```
A semicolon at the end of a line indicates where a statement ends. It is only required when you need to separate statements on a single line. However, some people believe it's good practice to have semicolons at the end of each statement. There are other rules for when you should and shouldn't use semicolons. For more details, see [Your Guide to Semicolons in JavaScript](https://www.codecademy.com/resources/blog/your-guide-to-semicolons-in-javascript/).
You can name a variable nearly anything, but there are some restrictions. (See [this section about naming rules](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variables).) If you are unsure, you can [check your variable name](https://mothereff.in/js-variables) to see if it's valid.
JavaScript is case sensitive. This means `myVariable` is not the same as `myvariable`. If you have problems in your code, check the case!
After declaring a variable, you can give it a value:
```js
myVariable = "Bob";
```
Also, you can do both these operations on the same line:
```js
let myVariable = "Bob";
```
You retrieve the value by calling the variable name:
```js
myVariable;
```
After assigning a value to a variable, you can change it later in the code:
```js
let myVariable = "Bob";
myVariable = "Steve";
```
Note that variables may hold values that have different [data types](/en-US/docs/Web/JavaScript/Data_structures):
<table class="standard-table">
<thead>
<tr>
<th scope="row">Variable</th>
<th scope="col">Explanation</th>
<th scope="col">Example</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">{{Glossary("String")}}</th>
<td>
This is a sequence of text known as a string. To signify that the value
is a string, enclose it in single or double quote marks.
</td>
<td><code>let myVariable = 'Bob';</code> or <br/><code>let myVariable = "Bob";</code></td>
</tr>
<tr>
<th scope="row">{{Glossary("Number")}}</th>
<td>This is a number. Numbers don't have quotes around them.</td>
<td><code>let myVariable = 10;</code></td>
</tr>
<tr>
<th scope="row">{{Glossary("Boolean")}}</th>
<td>
This is a True/False value. The words <code>true</code> and
<code>false</code> are special keywords that don't need quote marks.
</td>
<td><code>let myVariable = true;</code></td>
</tr>
<tr>
<th scope="row">{{Glossary("Array")}}</th>
<td>
This is a structure that allows you to store multiple values in a single
reference.
</td>
<td>
<code>let myVariable = [1,'Bob','Steve',10];</code><br />Refer to each
member of the array like this:<br /><code>myVariable[0]</code>,
<code>myVariable[1]</code>, etc.
</td>
</tr>
<tr>
<th scope="row">{{Glossary("Object")}}</th>
<td>
This can be anything. Everything in JavaScript is an object and can be
stored in a variable. Keep this in mind as you learn.
</td>
<td>
<code>let myVariable = document.querySelector('h1');</code><br />All of
the above examples too.
</td>
</tr>
</tbody>
</table>
So why do we need variables? Variables are necessary to do anything interesting in programming. If values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change an image displayed in an image gallery.
### Comments
Comments are snippets of text that can be added along with code. The browser ignores text marked as comments. You can write comments in JavaScript just as you can in CSS:
```js
/*
Everything in between is a comment.
*/
```
If your comment contains no line breaks, it's an option to put it behind two slashes like this:
```js
// This is a comment
```
### Operators
An `{{Glossary("operator")}}` is a mathematical symbol that produces a result based on two values (or variables). In the following table, you can see some of the simplest operators, along with some examples to try in the JavaScript console.
<table class="standard-table">
<thead>
<tr>
<th scope="row">Operator</th>
<th scope="col">Explanation</th>
<th scope="col">Symbol(s)</th>
<th scope="col">Example</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Addition</th>
<td>Add two numbers together or combine two strings.</td>
<td><code>+</code></td>
<td>
<code>6 + 9;<br />'Hello ' + 'world!';</code>
</td>
</tr>
<tr>
<th scope="row">Subtraction, Multiplication, Division</th>
<td>These do what you'd expect them to do in basic math.</td>
<td><code>-</code>, <code>*</code>, <code>/</code></td>
<td>
<code
>9 - 3;<br />8 * 2; // multiply in JS is an asterisk<br />9 / 3;</code
>
</td>
</tr>
<tr>
<th scope="row">Assignment</th>
<td>As you've seen already: this assigns a value to a variable.</td>
<td><code>=</code></td>
<td><code>let myVariable = 'Bob';</code></td>
</tr>
<tr>
<th scope="row">Strict equality</th>
<td>
This performs a test to see if two values are equal and of the same data type. It returns a
<code>true</code>/<code>false</code> (Boolean) result.
</td>
<td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality"><code>===</code></a></td>
<td>
<code>let myVariable = 3;<br />myVariable === 4;</code>
</td>
</tr>
<tr>
<th scope="row">Not, Does-not-equal</th>
<td>
This returns the logically opposite value of what it precedes. It turns
a <code>true</code> into a <code>false</code>, etc.. When it is used
alongside the Equality operator, the negation operator tests whether two
values are <em>not</em> equal.
</td>
<td><code>!</code>, <code>!==</code></td>
<td>
<p>
For "Not", the basic expression is <code>true</code>, but the
comparison returns <code>false</code> because we negate it:
</p>
<p>
<code>let myVariable = 3;<br />!(myVariable === 3);</code>
</p>
<p>
"Does-not-equal" gives basically the same result with different
syntax. Here we are testing "is <code>myVariable</code> NOT equal to
3". This returns<code> false</code> because <code>myVariable</code> IS
equal to 3:
</p>
<p>
<code>let myVariable = 3;<br />myVariable !== 3;</code>
</p>
</td>
</tr>
</tbody>
</table>
There are a lot more operators to explore, but this is enough for now. See [Expressions and operators](/en-US/docs/Web/JavaScript/Reference/Operators) for a complete list.
> **Note:** Mixing data types can lead to some strange results when performing calculations. Be careful that you are referring to your variables correctly, and getting the results you expect. For example, enter `'35' + '25'` into your console. Why don't you get the result you expected? Because the quote marks turn the numbers into strings, so you've ended up concatenating strings rather than adding numbers. If you enter `35 + 25` you'll get the total of the two numbers.
### Conditionals
Conditionals are code structures used to test if an expression returns true or not. A very common form of conditionals is the `if...else` statement. For example:
```js
let iceCream = "chocolate";
if (iceCream === "chocolate") {
alert("Yay, I love chocolate ice cream!");
} else {
alert("Awwww, but chocolate is my favorite…");
}
```
The expression inside the `if ()` is the test. This uses the strict equality operator (as described above) to compare the variable `iceCream` with the string `chocolate` to see if the two are equal. If this comparison returns `true`, the first block of code runs. If the comparison is not true, the second block of code—after the `else` statement—runs instead.
### Functions
{{Glossary("Function", "Functions")}} are a way of packaging functionality that you wish to reuse. It's possible to define a body of code as a function that executes when you call the function name in your code. This is a good alternative to repeatedly writing the same code. You have already seen some uses of functions. For example:
```js
let myVariable = document.querySelector("h1");
```
```js
alert("hello!");
```
These functions, `document.querySelector` and `alert`, are built into the browser.
If you see something which looks like a variable name, but it's followed by parentheses— `()` —it is likely a function. Functions often take {{Glossary("Argument", "arguments")}}: bits of data they need to do their job. Arguments go inside the parentheses, separated by commas if there is more than one argument.
For example, the `alert()` function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what message to display.
You can also define your own functions. In the next example, we create a simple function which takes two numbers as arguments and multiplies them:
```js
function multiply(num1, num2) {
let result = num1 * num2;
return result;
}
```
Try running this in the console; then test with several arguments. For example:
```js
multiply(4, 7);
multiply(20, 20);
multiply(0.5, 3);
```
> **Note:** The [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement tells the browser to return the `result` variable out of the function so it is available to use. This is necessary because variables defined inside functions are only available inside those functions. This is called variable {{Glossary("Scope", "scoping")}}. (Read more about [variable scoping](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variable_scope).)
### Events
Real interactivity on a website requires event handlers. These are code structures that listen for activity in the browser, and run code in response. The most obvious example is handling the [click event](/en-US/docs/Web/API/Element/click_event), which is fired by the browser when you click on something with your mouse. To demonstrate this, enter the following into your console, then click on the current webpage:
```js
document.querySelector("html").addEventListener("click", function () {
alert("Ouch! Stop poking me!");
});
```
There are a number of ways to attach an event handler to an element.
Here we select the {{htmlelement("html")}} element. We then call its [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) function, passing in the name of the event to listen to (`'click'`) and a function to run when the event happens.
The function we just passed to `addEventListener()` here is called an _anonymous function_, because it doesn't have a name. There's an alternative way of writing anonymous functions, which we call an _arrow function_.
An arrow function uses `() =>` instead of `function ()`:
```js
document.querySelector("html").addEventListener("click", () => {
alert("Ouch! Stop poking me!");
});
```
## Supercharging our example website
With this review of JavaScript basics completed (above), let's add some new features to our example site.
Before going any further, delete the current contents of your `main.js` file — the bit you added earlier during the "Hello world!" example — and save the empty file. If you don't, the existing code will clash with the new code you are about to add.
### Adding an image changer
In this section, you will learn how to use JavaScript and DOM API features to alternate the display of one of two images. This change will happen as a user clicks the displayed image.
1. Choose an image you want to feature on your example site. Ideally, the image will be the same size as the image you added previously, or as close as possible.
2. Save this image in your `images` folder.
3. Rename the image _firefox2.png_.
4. Add the following JavaScript code to your `main.js` file.
```js
const myImage = document.querySelector("img");
myImage.onclick = () => {
const mySrc = myImage.getAttribute("src");
if (mySrc === "images/firefox-icon.png") {
myImage.setAttribute("src", "images/firefox2.png");
} else {
myImage.setAttribute("src", "images/firefox-icon.png");
}
};
```
5. Save all files and load `index.html` in the browser. Now when you click the image, it should change to the other one.
This is what happened. You stored a reference to your {{htmlelement("img")}} element in `myImage`. Next, you made its `onclick` event handler property equal to a function with no name (an "anonymous" function). So every time this element is clicked:
1. The code retrieves the value of the image's `src` attribute.
2. The code uses a conditional to check if the `src` value is equal to the path of the original image:
1. If it is, the code changes the `src` value to the path of the second image, forcing the other image to be loaded inside the {{htmlelement("img")}} element.
2. If it isn't (meaning it must already have changed), the `src` value swaps back to the original image path, to the original state.
### Adding a personalized welcome message
Next, let's change the page title to a personalized welcome message when the user first visits the site. This welcome message will persist. Should the user leave the site and return later, we will save the message using the [Web Storage API](/en-US/docs/Web/API/Web_Storage_API). We will also include an option to change the user, and therefore, the welcome message.
1. In `index.html`, add the following line just before the {{htmlelement("script")}} element:
```html
<button>Change user</button>
```
2. In `main.js`, place the following code at the bottom of the file, exactly as it is written. This takes references to the new button and the heading, storing each inside variables:
```js
let myButton = document.querySelector("button");
let myHeading = document.querySelector("h1");
```
3. Add the following function to set the personalized greeting. This won't do anything yet, but this will change soon.
```js
function setUserName() {
const myName = prompt("Please enter your name.");
localStorage.setItem("name", myName);
myHeading.textContent = `Mozilla is cool, ${myName}`;
}
```
The `setUserName()` function contains a [`prompt()`](/en-US/docs/Web/API/Window/prompt) function, which displays a dialog box, similar to `alert()`. This `prompt()` function does more than `alert()`, asking the user to enter data, and storing it in a variable after the user clicks _OK_. In this case, we are asking the user to enter a name. Next, the code calls on an API `localStorage`, which allows us to store data in the browser and retrieve it later. We use localStorage's `setItem()` function to create and store a data item called `'name'`, setting its value to the `myName` variable which contains the user's entry for the name. Finally, we set the `textContent` of the heading to a string, plus the user's newly stored name.
4. Add the following condition block after the function declaration. We could call this initialization code, as it structures the app when it first loads.
```js
if (!localStorage.getItem("name")) {
setUserName();
} else {
const storedName = localStorage.getItem("name");
myHeading.textContent = `Mozilla is cool, ${storedName}`;
}
```
This first line of this block uses the negation operator (logical NOT, represented by the `!`) to check whether the `name` data exists. If not, the `setUserName()` function runs to create it. If it exists (that is, the user set a user name during a previous visit), we retrieve the stored name using `getItem()` and set the `textContent` of the heading to a string, plus the user's name, as we did inside `setUserName()`.
5. Put this `onclick` event handler (below) on the button. When clicked, `setUserName()` runs. This allows the user to enter a different name by pressing the button.
```js
myButton.onclick = () => {
setUserName();
};
```
### A user name of null?
When you run the example and get the dialog box that prompts you to enter your user name, try pressing the _Cancel_ button. You should end up with a title that reads _Mozilla is cool, null_. This happens because—when you cancel the prompt—the value is set as [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null). _Null_ is a special value in JavaScript that refers to the absence of a value.
Also, try clicking _OK_ without entering a name. You should end up with a title that reads _Mozilla is cool,_ for fairly obvious reasons.
To avoid these problems, you could check that the user hasn't entered a blank name. Update your `setUserName()` function to this:
```js
function setUserName() {
const myName = prompt("Please enter your name.");
if (!myName) {
setUserName();
} else {
localStorage.setItem("name", myName);
myHeading.textContent = `Mozilla is cool, ${myName}`;
}
}
```
In human language, this means: If `myName` has no value, run `setUserName()` again from the start. If it does have a value (if the above statement is not true), then store the value in `localStorage` and set it as the heading's text.
## Conclusion
If you have followed all the instructions in this article, you should end up with a page that looks something like the image below. You can also [view our version](https://mdn.github.io/beginner-html-site-scripted/).

If you get stuck, you can compare your work with our [finished example code on GitHub](https://github.com/mdn/beginner-html-site-scripted/blob/gh-pages/scripts/main.js).
We have just scratched the surface of JavaScript. If you enjoyed playing, and wish to go further, take advantage of the resources listed below.
## See also
- [Dynamic client-side scripting with JavaScript](/en-US/docs/Learn/JavaScript)
- : Dive into JavaScript in much more detail.
- [Learn JavaScript](https://learnjavascript.online/)
- : This is an excellent resource for aspiring web developers! Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by an automated assessment. The first 40 lessons are free. The complete course is available for a small one-time payment.
{{PreviousMenuNext("Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}
| 0 |
data/mdn-content/files/en-us/learn/getting_started_with_the_web | data/mdn-content/files/en-us/learn/getting_started_with_the_web/dealing_with_files/index.md | ---
title: Dealing with files
slug: Learn/Getting_started_with_the_web/Dealing_with_files
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Getting_started_with_the_web/What_will_your_website_look_like", "Learn/Getting_started_with_the_web/HTML_basics", "Learn/Getting_started_with_the_web")}}
A website consists of many files: text content, code, stylesheets, media content, and so on. When you're building a website, you need to assemble these files into a sensible structure on your local computer, make sure they can talk to one another, and get all your content looking right before you eventually [upload them to a server](/en-US/docs/Learn/Getting_started_with_the_web/Publishing_your_website). _Dealing with files_ discusses some issues you should be aware of so you can set up a sensible file structure for your website.
## Where should your website live on your computer?
When you are working on a website locally on your computer, you should keep all the related files in a single folder that mirrors the published website's file structure on the server. This folder can live anywhere you like, but you should put it somewhere where you can easily find it, maybe on your Desktop, in your Home folder, or at the root of your hard drive.
1. Choose a place to store your website projects. Inside your chosen place, create a new folder called `web-projects` (or similar). This is where all your website projects will live.
2. Inside this first folder, create another folder to store your first website in. Call it `test-site` (or something more imaginative).
## An aside on casing and spacing
You'll notice that throughout this article, we ask you to name folders and files completely in lowercase with no spaces. This is because:
1. Many computers, particularly web servers, are case-sensitive. So for example, if you put an image on your website at `test-site/MyImage.jpg` and then in a different file you try to invoke the image as `test-site/myimage.jpg`, it may not work.
2. Browsers, web servers, and programming languages do not handle spaces consistently. For example, if you use spaces in your filename, some systems may treat the filename as two filenames. Some servers will replace the spaces in your filenames with "%20" (the character code for spaces in URLs), resulting in all your links being broken. It's better to separate words with hyphens, rather than underscores: `my-file.html` vs. `my_file.html`.
The short answer is that you should use a hyphen for your file names. The Google search engine treats a hyphen as a word separator but does not regard an underscore that way. For these reasons, it is best to get into the habit of writing your folder and file names in lowercase with no spaces and with words separated by hyphens, at least until you know what you're doing. That way you'll bump into fewer problems down the road.
## What structure should your website have?
Next, let's look at what structure our test site should have. The most common things we'll have on any website project we create are an index HTML file and folders to contain images, style files, and script files. Let's create these now:
1. **`index.html`**: This file will generally contain your homepage content, that is, the text and images that people see when they first go to your site. Using your text editor, create a new file called `index.html` and save it just inside your `test-site` folder.
2. **`images` folder**: This folder will contain all the images that you use on your site. Create a folder called `images`, inside your `test-site` folder.
3. **`styles` folder**: This folder will contain the CSS code used to style your content (for example, setting text and background colors). Create a folder called `styles`, inside your `test-site` folder.
4. **`scripts` folder**: This folder will contain all the JavaScript code used to add interactive functionality to your site (e.g. buttons that load data when clicked). Create a folder called `scripts`, inside your `test-site` folder.
> **Note:** On Windows computers, you might have trouble seeing the file names, because Windows has an option called **Hide extensions for known file types** turned on by default. Generally, you can turn this off by going to Windows Explorer, selecting the **Folder options…** option, unchecking the **Hide extensions for known file types** check box, then clicking **OK**. For more specific information covering your version of Windows, you can search on the web.
## File paths
To make files talk to one another, you have to provide a file path between them — basically a route, so one file knows where another one is. To demonstrate this, we will insert a little bit of HTML into our `index.html` file, and make it display the image you chose in the article ["What will your website look like?"](/en-US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like) Alternatively, you can choose an existing image at your disposal, on your computer or from the Web, and use it in the following steps:
1. Copy the image you chose earlier into your `images` folder.
2. Open up your `index.html` file, and insert the following code into the file exactly as shown. Don't worry about what it all means for now — we'll look at the structures in more detail later in the series.
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>My test page</title>
</head>
<body>
<img src="" alt="My test image" />
</body>
</html>
```
3. The line `<img src="" alt="My test image">` is the HTML code that inserts an image into the page. We need to tell the HTML where the image is. The image is inside the _images_ directory, which is in the same directory as `index.html`. To walk down the file structure from `index.html` to our image, the file path we'd need is `images/your-image-filename`. For example, our image is called `firefox-icon.png`, so the file path is `images/firefox-icon.png`.
4. Insert the file path into your HTML code between the double quote marks of the `src=""` code.
5. Change the contents of the `alt` attribute to a [description of the image](/en-US/docs/Web/HTML/Element/img#authoring_meaningful_alternate_descriptions) you are including. In this case, `alt="Firefox logo: flaming fox wrapping the world"`.
6. Save your HTML file, then load it in your web browser (double-click the file). You should see your new webpage displaying your image!

Some general rules for file paths:
- To link to a target file in the same directory as the invoking HTML file, just use the filename, e.g. `my-image.jpg`.
- To reference a file in a subdirectory, write the directory name in front of the path, plus a forward slash, e.g. `subdirectory/my-image.jpg`.
- To link to a target file in the directory **above** the invoking HTML file, write two dots. So for example, if `index.html` was inside a subfolder of `test-site` and `my-image.jpg` was inside `test-site`, you could reference `my-image.jpg` from `index.html` using `../my-image.jpg`.
- You can combine these as much as you like, for example `../subdirectory/another-subdirectory/my-image.jpg`.
For now, this is about all you need to know.
> **Note:** The Windows file system tends to use backslashes, not forward slashes, e.g. `C:\Windows`. This doesn't matter in HTML — even if you are developing your website on Windows, you should still use forward slashes in your code.
## What else should be done?
That is about it for now. Your folder structure should look something like this:

{{PreviousMenuNext("Learn/Getting_started_with_the_web/What_will_your_website_look_like", "Learn/Getting_started_with_the_web/HTML_basics", "Learn/Getting_started_with_the_web")}}
| 0 |
data/mdn-content/files/en-us/learn | data/mdn-content/files/en-us/learn/mathml/index.md | ---
title: Writing mathematics with MathML
slug: Learn/MathML
page-type: learn-topic
---
{{LearnSidebar}}
Mathematical Markup Language — or {{glossary("MathML")}} — is the markup language used to write mathematical formulas in web pages using fractions, scripts, radicals, matrices, integrals, series, etc. Although it was originally designed as an independent XML language, MathML is generally embedded inside {{Glossary('HTML')}} documents and can be seen as an extension of HTML.
> **Warning:** In practice, MathML content is generated from [lightweight markup languages](https://en.wikipedia.org/wiki/Lightweight_markup_language) (e.g. [LaTeX](https://en.wikipedia.org/wiki/LaTeX)) or using [graphical user interface](https://en.wikipedia.org/wiki/Graphical_user_interface): if you just need to integrate mathematical formulas in your web pages, the tips from the [Authoring MathML](/en-US/docs/Web/MathML/Authoring) page should be enough.
> **Callout:**
>
> #### Looking to become a front-end web developer?
>
> We have put together a course that includes all the essential information you need to work towards your goal.
>
> [**Get started**](/en-US/docs/Learn/Front-end_web_developer)
## Prerequisites
Before attempting to learn MathML, it is assumed that you have some basic knowledge of [HTML](/en-US/docs/Learn/HTML) and [CSS](/en-US/docs/Learn/CSS). Consequently, you are strongly advised to get familiar with at least these two technologies first. Start by working through the following modules:
- [Getting started with the Web](/en-US/docs/Learn/Getting_started_with_the_web)
- [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML)
- [Introduction to CSS](/en-US/docs/Learn/CSS/First_steps)
Some familiarity with mathematical notations and [TeX](https://en.wikipedia.org/wiki/TeX) rendering rules might also come in handy, even though required concepts will be explained as needed.
## Modules
- [MathML first steps](/en-US/docs/Learn/MathML/First_steps)
- : MathML is the markup language used to write mathematical formulas in Web pages. This module provides a gentle beginning to your path towards MathML mastery with the basics of how it works, what the syntax looks like, and how you can start using it inside HTML.
## See also
- [MathML on MDN](/en-US/docs/Web/MathML)
- : The main entry point for MathML documentation on MDN, where you'll find detailed reference documentation for all features of the MathML language. Want to know all the values a property can take? This is a good place to go.
| 0 |
data/mdn-content/files/en-us/learn/mathml | data/mdn-content/files/en-us/learn/mathml/first_steps/index.md | ---
title: MathML first steps overview
slug: Learn/MathML/First_steps
page-type: learn-module
---
{{LearnSidebar}}
MathML is the markup language used to write mathematical formulas in web pages. This module provides a gentle beginning to your path towards MathML mastery with the basics of how it works, what the syntax looks like, and how you can start using it inside HTML.
> **Callout:**
>
> #### Looking to become a front-end web developer?
>
> We have put together a course that includes all the essential information you need to work towards your goal.
>
> [**Get started**](/en-US/docs/Learn/Front-end_web_developer)
## Prerequisites
Before starting this module, you should have:
1. Basic familiarity with using computers and using the Web passively (i.e. looking at it, consuming the content.)
2. A basic work environment set up, as detailed in [Installing basic software](/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software), and an understanding of how to create and manage files, as detailed in [Dealing with files](/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files).
3. Basic familiarity with HTML, as described in [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML).
> **Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out the code examples in an online coding program such as [JSBin](https://jsbin.com/) or [Glitch](https://glitch.com/).
## Guides
This module contains the following articles, which will take you through all the basic theory of MathML, and provide opportunities for you to test out some skills.
- [Getting started with MathML](/en-US/docs/Learn/MathML/First_steps/Getting_started)
- : In this article, we will take a simple HTML document and see how to add MathML formulas into it, introducing a few elements along the way.
- [Text containers](/en-US/docs/Learn/MathML/First_steps/Text_containers)
- : Now that you get a better idea of MathML, we move on to text containers (variables, numbers, operators, ...) which are used as building blocks of MathML formulas.
- [Fractions and roots](/en-US/docs/Learn/MathML/First_steps/Fractions_and_roots)
- : Relying on text containers, this article describes how to build more complex MathML expressions by nesting fractions and roots.
- [Scripts](/en-US/docs/Learn/MathML/First_steps/Scripts)
- : We continue the review of basic math notations and focuses on building MathML elements with scripts.
- [Tables](/en-US/docs/Learn/MathML/First_steps/Tables)
- : Once all basic math notations are known, it remains to consider tabular layout which can be used for matrix-like expressions and other advanced math layout.
## Assessments
The following assessment will test your understanding of the MathML basics covered in the guides above.
- [Three famous mathematical formulas](/en-US/docs/Learn/MathML/First_steps/Three_famous_mathematical_formulas)
- : With the things you have learned in the last few articles, you should already be able to write relatively sophisticated MathML formulas. This assessment gives you a chance to do that.
| 0 |
data/mdn-content/files/en-us/learn/mathml/first_steps | data/mdn-content/files/en-us/learn/mathml/first_steps/three_famous_mathematical_formulas/index.md | ---
title: Three famous mathematical formulas
slug: Learn/MathML/First_steps/Three_famous_mathematical_formulas
page-type: learn-module-assessment
---
{{LearnSidebar}}{{PreviousMenu("Learn/MathML/First_steps/Tables", "Learn/MathML/First_steps")}}
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Before attempting this assessment you should have already worked through
all the articles in this module, and also have an understanding of HTML
basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>).
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To have a play with some MathML and test your new-found
knowledge.</td>
</tr>
</tbody>
</table>
## A small math article
The goal is to rewrite the following math article using HTML and MathML:

Although you don't need to be familiar with [LaTeX](https://en.wikipedia.org/wiki/LaTeX), it might be useful to know the LaTeX source from which it was generated:
```latex
\documentclass{article}
\usepackage{amsmath}
\usepackage{amssymb}
\begin{document}
To solve the cubic equation $t^3 + pt + q = 0$ (where the real numbers
$p, q$ satisfy ${4p^3 + 27q^2} > 0$) one can use Cardano's formula:
\[
\sqrt[{3}]{
-\frac{q}{2}
+\sqrt{\frac{q^2}{4} + {\frac{p^{3}}{27}}}
}+
\sqrt[{3}]{
-\frac{q}{2}
-\sqrt{\frac{q^2}{4} + {\frac{p^{3}}{27}}}
}
\]
For any $u_1, \dots, u_n \in \mathbb{C}$ and
$v_1, \dots, v_n \in \mathbb{C}$, the Cauchy–Bunyakovsky–Schwarz
inequality can be written as follows:
\[
\left| \sum_{k=1}^n {u_k \bar{v_k}} \right|^2
\leq
{
\left( \sum_{k=1}^n {|u_k|} \right)^2
\left( \sum_{k=1}^n {|v_k|} \right)^2
}
\]
Finally, the determinant of a Vandermonde matrix can be calculated
using the following expression:
\[
\begin{vmatrix}
1 & x_1 & x_1^2 & \dots & x_1^{n-1} \\
1 & x_2 & x_2^2 & \dots & x_2^{n-1} \\
1 & x_3 & x_3^2 & \dots & x_3^{n-1} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
1 & x_n & x_n^2 & \dots & x_n^{n-1} \\
\end{vmatrix}
= {\prod_{1 \leq {i,j} \leq n} {(x_i - x_j)}}
\]
\end{document}
```
## Starting point
To get this assessment started, you can rely on our usual HTML template. By default it uses UTF-8 encoding, special Web fonts for the `<body>` and `<math>` tags (with similar look & feel as the LaTeX output). The goal is to replace the question marks `???` with actual MathML content.
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Three famous mathematical formulas</title>
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
</head>
<body class="htmlmathparagraph">
<p>
To solve the cubic equation ??? (where the real numbers ??? satisfy ???)
one can use Cardano's formula: ???
</p>
<p>
For any ??? and ???, the Cauchy–Bunyakovsky–Schwarz inequality can be
written as follows: ???
</p>
<p>
Finally, the determinant of a Vandermonde matrix can be calculated using
the following expression: ???
</p>
</body>
</html>
```
## Hints and tips
- Start by inserting empty `<math>` tags, deciding whether they should have a `display="block"` attribute or not.
- Check the text used and find their [Unicode characters](https://en.wikipedia.org/wiki/Mathematical_operators_and_symbols_in_Unicode) ("−", "ℂ", "∑", ...).
- Analyze the semantics of each portion of text (variable? operator? number?) and determine the proper token element to use for each of them.
- Look for advanced constructions (fractions? roots? scripts? matrices?) and determine the proper MathML element to use for each of them.
- Don't forget to rely on `<mrow>` for grouping subexpressions.
- Pay attention to stretchy and large operators!
- Use the [W3C validator](https://validator.w3.org/nu/) to catch unintended mistakes in your HTML/MathML markup.
- If you are stuck, or realize how painful it is to write MathML by hand, feel free to use tools to help [write MathML](/en-US/docs/Web/MathML/Authoring) such as [TeXZilla](https://fred-wang.github.io/TeXZilla/).
{{LearnSidebar}}{{PreviousMenu("Learn/MathML/First_steps/Tables", "Learn/MathML/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/mathml/first_steps | data/mdn-content/files/en-us/learn/mathml/first_steps/fractions_and_roots/index.md | ---
title: MathML fractions and roots
slug: Learn/MathML/First_steps/Fractions_and_roots
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/MathML/First_steps/Text_containers", "Learn/MathML/First_steps/Scripts", "Learn/MathML/First_steps")}}
Relying on text containers, this article describes how to build more complex MathML expressions by nesting fractions and roots.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, and HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To get familiar with MathML elements used for writing fractions and
square roots.
</td>
</tr>
</tbody>
</table>
## Subtrees of \<mfrac>, \<msqrt> and \<mroot>
In the [getting started with MathML](/en-US/docs/Learn/MathML/First_steps/Getting_started) article, we've already met the `<mfrac>` element to describe a fraction. Let's consider a basic example which adds new elements for roots (`<msqrt>` and `<mroot>`):
```html
<math>
<mfrac>
<mtext>child1</mtext>
<mtext>child2</mtext>
</mfrac>
</math>
<br />
<math>
<msqrt>
<mtext>child1</mtext>
<mtext>child2</mtext>
<mtext>...</mtext>
<mtext>childN</mtext>
</msqrt>
</math>
<br />
<math>
<mroot>
<mtext>child1</mtext>
<mtext>child2</mtext>
</mroot>
</math>
```
Below is a screenshot of how it is rendered by a browser:

- We already know that the `<mfrac>` element is rendered as a fraction: The first child (the numerator) is drawn above the second child (the denominator) separated by a horizontal bar.
- The `<msqrt>` is rendered as a square root: its children are laid out like an [`<mrow>`](/en-US/docs/Learn/MathML/First_steps/Getting_started#grouping_with_the_mrow_element), prefixed by a root symbol √ and completely covered by an overbar.
- Finally, the `<mroot>` element is rendered as an nth root: The first element is covered by the radical symbol while the second element is used as the degree of the root and rendered as a prefix superscript.
### Active learning: nesting different elements
Here is a simple exercise to verify whether you understood the relation between a MathML subtree and its visual rendering. The document contains a MathML formula and you must check all subtrees corresponding to a subtree in that MathML formula. Once you are done, you can inspect the source of the MathML formula and verify if it matches your expectation.
```html hidden
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<title>My page with math characters</title>
<link rel="stylesheet" href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css">
</head>
<body>
<p>
<math>
<mfrac id="mfrac1">
<msqrt id="msqrt1">
<mn>2</mn>
</msqrt>
<mroot id="mroot1">
<mn>4</mn>
<mn>3</mn>
</mroot>
</mfrac>
<mo>+</mo>
<mroot id="mroot2">
<mn>5</mn>
<mfrac id="mfrac2">
<mn>6</mn>
<mn>7</mn>
</mfrac>
</mroot>
<mo>+</mo>
<msqrt id="msqrt2">
<mn>8</mn>
<mo>−</mo>
<mn>9</mn>
</msqrt>
</p>
<ol id="options">
<li>
<input type="checkbox" data-comment="Verify the order of children in an mfrac!">
An mfrac with an mroot as its first child and an msqrt as its second child.
</li>
<li>
<input type="checkbox" data-highlight="mroot2" data-comment="The '6 over 7'-th root of five.">
An mroot with an mn as its first child and mfrac as its second child.
</li>
<li>
<input type="checkbox" data-comment="This formula does not contain any fraction inside a square root!">
An msqrt containing an mfrac element.
</li>
<li>
<input type="checkbox" data-comment="The square root of two." data-highlight="msqrt1">
An msqrt with one mn child.
</li>
<li>
<input type="checkbox" data-comment="Verify the order of children in an mroot!">
An mroot with an mfrac as its first child and mn as its second child.
</li>
<li>
<input type="checkbox" data-comment="The square root of 'eight minus nine'." data-highlight="msqrt2">
An msqrt with the following list of children: mn, mo, mn.
</li>
<li>
<input type="checkbox" data-comment="The square root of two over the cubic root of four." data-highlight="mfrac1">
An mfrac with an msqrt as its first child and an mroot as its second child.
</li>
<li>
<input type="checkbox" data-comment="mfrac must have exactly two children!">
An mfrac with the following list of children: msqrt, mn, msqrt.
</li>
<li>
<input type="checkbox" data-comment="mroot must have exactly two children!">
An mroot with one mn child.
</li>
<li>
<input type="checkbox" data-comment="The fraction six over seven." data-highlight="mfrac2">
An mfrac with two mn children.
</li>
<li>
<input type="checkbox" data-comment="This formula does not contain any square root with more than two numbers!">
An msqrt with five mn children.
</li>
<li>
<input type="checkbox" data-highlight="mroot1" data-comment="The cubic root of four.">
An mroot with two mn children.
</li>
</ol>
<p>
<strong id="comment"></strong>
</p>
<p>
<strong id="status"></strong>
</p>
</body>
```
```css hidden
math {
font-family:
Latin Modern Math,
STIX Two Math;
font-size: 200%;
}
math .highlight {
background: pink;
}
math [id] .highlight {
background: lightblue;
}
p {
padding: 0.5em;
}
```
```js hidden
const options = document.getElementById("options");
const comment = document.getElementById("comment");
const checkboxes = Array.from(options.getElementsByTagName("input"));
const status = document.getElementById("status");
function verifyOption(checkbox) {
let mathml = checkbox.dataset.highlight;
if (mathml) {
mathml = document.getElementById(mathml);
}
if (checkbox.checked) {
comment.textContent = checkbox.dataset.comment;
if (mathml) {
mathml.classList.add("highlight");
} else {
checkbox.checked = false;
}
} else {
comment.textContent = "";
if (mathml) {
mathml.classList.remove("highlight");
}
}
const finished = checkboxes.every(
(checkbox) => !!checkbox.checked === !!checkbox.dataset.highlight,
);
status.textContent = finished
? "Congratulations, you checked all the correct answers!"
: "";
}
checkboxes.forEach((checkbox) => {
checkbox.addEventListener("change", () => {
verifyOption(checkbox);
});
});
```
{{ EmbedLiveSample('Active_learning_nesting_different_elements', 700, 600, "", "") }}
## Stretchy radical symbols
As previously seen, the overbar of the `<msqrt>` and `<mroot>` elements stretches horizontally to cover their content. But actually the root symbol √ also stretches to be as tall as their content.
```html hidden
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
```
```html
<math display="block">
<mroot>
<msqrt>
<mfrac>
<mn>1</mn>
<mn>2</mn>
</mfrac>
</msqrt>
<mn>3</mn>
</mroot>
</math>
```
{{ EmbedLiveSample('Stretchy_radical_symbols', 700, 200, "", "") }}
> **Warning:** Special [math fonts](/en-US/docs/Web/MathML/Fonts) are generally required to make that stretching possible, the previous example relies on [web fonts](/en-US/docs/Learn/CSS/Styling_text/Web_fonts).
## Fractions without bar
Some mathematical concepts are sometimes written using fraction-like notations such [binomial coefficients](https://en.wikipedia.org/wiki/Combination) or [Legendre symbols](https://en.wikipedia.org/wiki/Legendre_symbol). It is appropriate to use an `<mfrac>` element to markup such notations. For fraction-like notations that don't draw a horizontal bar, attach a `linethickness="0"` attribute to the `<mfrac>` element:
```html hidden
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
```
```html
<math display="block">
<mrow>
<mo>(</mo>
<mfrac linethickness="0">
<mn>3</mn>
<mn>2</mn>
</mfrac>
<mo>)</mo>
</mrow>
<mo>=</mo>
<mn>3</mn>
<mo>≠</mo>
<mfrac>
<mn>3</mn>
<mn>2</mn>
</mfrac>
</math>
```
{{ EmbedLiveSample('Fraction_without_bar', 700, 200, "", "") }}
> **Note:** Although the `linethickness` attribute can be used to specify an arbitrary thickness, it is better to keep the default value, which is calculated from parameters specified in the math font.
## Summary
In this lesson, we've seen how to build fractions and roots using the `<mfrac>`, `<msqrt>` and `<mroot>` elements. We noticed some special feature of these elements, namely the fraction and radical symbol. We've seen how to use the `linethickness` attribute to draw fractions without bars. In the next article, we will continue with basic math notations and consider [scripts](/en-US/docs/Learn/MathML/First_steps/Scripts).
{{LearnSidebar}}{{PreviousMenuNext("Learn/MathML/First_steps/Text_containers", "Learn/MathML/First_steps/Scripts", "Learn/MathML/First_steps")}}
## See also
- [The `<mfrac>` element](/en-US/docs/Web/MathML/Element/mfrac)
- [The `<msqrt>` element](/en-US/docs/Web/MathML/Element/msqrt)
- [The `<mroot>` element](/en-US/docs/Web/MathML/Element/mroot)
| 0 |
data/mdn-content/files/en-us/learn/mathml/first_steps | data/mdn-content/files/en-us/learn/mathml/first_steps/scripts/index.md | ---
title: MathML scripted elements
slug: Learn/MathML/First_steps/Scripts
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/MathML/First_steps/Fractions_and_roots", "Learn/MathML/First_steps/Tables", "Learn/MathML/First_steps")}}
We continue the review of basic math notations and focus on building MathML elements with scripts.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, and HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To get familiar with basic MathML elements producing scripted elements.
</td>
</tr>
</tbody>
</table>
## Subscripts and superscripts
Similarly to what we saw in the [previous article](/en-US/docs/Learn/MathML/First_steps/Fractions_and_roots), the `<msub>`, `<msup>` and `<msubsup>` have a special structure expecting exactly two elements (for `<msub>`, `<msup>`) or three elements (for `<msubsup>`):
```html
<p>
msub:
<math>
<msub>
<mtext>child1</mtext>
<mtext>child2</mtext>
</msub>
</math>
</p>
<p>
msup:
<math>
<msup>
<mtext>child1</mtext>
<mtext>child2</mtext>
</msup>
</math>
</p>
<p>
msubsup:
<math>
<msubsup>
<mtext>child1</mtext>
<mtext>child2</mtext>
<mtext>child3</mtext>
</msubsup>
</math>
</p>
```
Below is the rendering of the above example in your browser.
{{ EmbedLiveSample('Subtrees_of_msub_msup_msubsup', 700, 200, "", "") }}
You should notice that:
- The second child of the `<msub>` element is attached as a subscript of its first child.
- The second child of the `<msup>` element is attached as a superscript of its first child.
- The second and third children of the `<msubsup>` element are respectively attached as a subscript and superscript of its first child.
- The text inside scripts is scaled down.
> **Note:** The MathML elements `<msub>` and `<msup>` are different from the HTML elements [`<sub>`](/en-US/docs/Web/HTML/Element/sub) and [`<sup>`](/en-US/docs/Web/HTML/Element/sup). They allow authors to provide arbitrary MathML subtrees as scripts, not just text.
## Underscripts and overscripts
The `<munder>`, `<mover>` and `<munderover>` elements are very similar except that they are used to attach underscripts and overscripts. Instead of giving details, we will let you figure out their definitions yourself with the following exercise.
### Active learning: Recognize under/over scripts
In the following example, try to guess the names of the mystery elements (written as question marks) and click the button to reveal the solution:
```html hidden
<p>
<code><<span>????????</span>></code> element with exactly two children
(child1, child2):
<math>
<mover>
<mtext>child1</mtext>
<mtext>child2</mtext>
</mover>
</math>
</p>
<p>
<code><<span>????????</span>></code> element with exactly three children
(child1, child2 and child3):
<math>
<munderover>
<mtext>child1</mtext>
<mtext>child2</mtext>
<mtext>child3</mtext>
</munderover>
</math>
</p>
<p>
<code><<span>????????</span>></code> element with exactly two children
(child1, child2):
<math>
<munder>
<mtext>child1</mtext>
<mtext>child2</mtext>
</munder>
</math>
</p>
<p><input type="button" id="showSolution" value="Show solution" /></p>
```
```css hidden
p {
padding: 0.5em;
}
```
```js hidden
document.getElementById("showSolution").addEventListener("click", () => {
const maths = Array.from(document.getElementsByTagName("math"));
Array.from(document.getElementsByTagName("span")).forEach((span, index) => {
span.textContent = maths[index].firstElementChild.tagName;
});
});
```
{{ EmbedLiveSample('Subtrees_of_munder_mover_munderover', 700, 400, "", "") }}
### Active learning: Recognize scripted elements
The following MathML formula contains a more complex expression, nesting fractions, roots and scripts. Try to guess the elements laid out with scripted elements `<msub>`, `<msup>`, `<msubsup>`, `<munder>`, `<mover>`, `<munderover>`. Each time you click such an element, it is highlighted and a confirmation message is displayed. Finally, read the MathML source to verify whether that corresponds to your expectation.
```html hidden
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My page with scripted elements</title>
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
</head>
<body>
<math display="block">
<mroot>
<mrow>
<munder>
<mi>β</mi>
<mo>⎵</mo>
</munder>
</mrow>
<mn>3</mn>
</mroot>
<mo>+</mo>
<mfrac>
<mrow
><mo>|</mo>
<mover>
<mi>α</mi>
<mo>→</mo>
</mover>
<mo>|</mo>
</mrow>
<msup>
<mi>s</mi>
<mn>3</mn>
</msup>
</mfrac>
<mo>−</mo>
<mrow>
<munderover>
<mo>∑</mo>
<mrow>
<mi>i</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mi>n</mi>
</munderover>
<msqrt>
<mrow>
<msub>
<mi>a</mi>
<mi>i</mi>
</msub>
<mo>−</mo>
<msubsup>
<mi>K</mi>
<mn>0</mn>
<mi>i</mi>
</msubsup>
</mrow>
</msqrt>
</mrow>
</math>
<input type="button" id="clearOutput" value="Reset" />
<div id="output"></div>
</body>
</html>
```
```css hidden
.highlight {
color: red;
}
math {
font-size: 200%;
}
```
```js hidden
const scriptedElements = Array.from(
document.querySelectorAll("msub, msup, msubsup, munder, mover, munderover"),
);
const outputDiv = document.getElementById("output");
function clearHighlight() {
scriptedElements.forEach((scripted) => {
scripted.classList.remove("highlight");
});
}
scriptedElements.forEach((scripted) => {
scripted.addEventListener("click", () => {
clearHighlight();
scripted.classList.add("highlight");
outputDiv.insertAdjacentHTML(
"beforeend",
`<p><strong>You clicked an <code><${scripted.tagName}></code> element.</strong></p>`,
);
});
});
document.getElementById("clearOutput").addEventListener("click", () => {
clearHighlight();
outputDiv.innerHTML = "";
});
```
{{ EmbedLiveSample('Active_learning_recognize_scripted_elements', 700, 400, "", "") }}
## More operator properties
We have previously seen some [properties of the `<mo>` element](/en-US/docs/Learn/MathML/First_steps/Text_containers#operator_properties_of_mo) namely stretching in the vertical direction and spacing. Now that scripted elements are available, we can extend that list. We will do that by tweaking our [previous example](#active_learning_recognize_scripted_elements).
### Stretching in horizontal direction
Let's first perform the substitutions <math> <mi>β</mi> <mo>≔</mo> <mrow> <msub> <mi>z</mi> <mn>1</mn> </msub> <mo>+</mo> <msub> <mi>z</mi> <mn>2</mn> </msub> </mrow> </math> and <math> <mi>α</mi> <mo>≔</mo> <mrow> <msub> <mi>v</mi> <mn>1</mn> </msub> <mo>+</mo> <msub> <mi>v</mi> <mn>2</mn> </msub> </mrow> </math>:
```html hidden
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My page with horizontal stretchy operators</title>
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
</head>
<body>
<math display="block">
<mroot>
<mrow>
<munder>
<mrow>
<msub>
<mi>z</mi>
<mn>1</mn>
</msub>
<mo>+</mo>
<msub>
<mi>z</mi>
<mn>2</mn>
</msub>
</mrow>
<mo>⎵</mo>
</munder>
</mrow>
<mn>3</mn>
</mroot>
<mo>+</mo>
<mfrac>
<mrow
><mo>|</mo>
<mover>
<mrow>
<msub>
<mi>v</mi>
<mn>1</mn>
</msub>
<mo>+</mo>
<msub>
<mi>v</mi>
<mn>2</mn>
</msub>
</mrow>
<mo>→</mo>
</mover>
<mo>|</mo>
</mrow>
<msup>
<mi>s</mi>
<mn>3</mn>
</msup>
</mfrac>
<mo>−</mo>
<mrow>
<munderover>
<mo>∑</mo>
<mrow>
<mi>i</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mi>n</mi>
</munderover>
<msqrt>
<mrow>
<msub>
<mi>a</mi>
<mi>i</mi>
</msub>
<mo>−</mo>
<msubsup>
<mi>K</mi>
<mn>0</mn>
<mi>i</mi>
</msubsup>
</mrow>
</msqrt>
</mrow>
</math>
</body>
</html>
```
```css hidden
.highlight {
color: red;
}
math {
font-size: 200%;
}
```
{{ EmbedLiveSample('Stretching_in_horizontal_direction', 700, 200, "", "") }}
We now realize that the bottom bracket "⎵" and the rightward arrow "→" stretch horizontally to cover the width of the substituted values. Recall that [some vertical operators can stretch](/en-US/docs/Learn/MathML/First_steps/Text_containers#active_learning_stretchy_operators) to cover the height of non-stretchy siblings inside an `<mrow>`. Similarly some horizontal operators can stretch to cover the width of non-stretchy siblings in an `<munder>`, `<mover>` or `<munderover>` element.
> **Note:** Stretching can happen for any child of the `<munder>`, `<mover>` or `<munderover>` element, not just the underscript or overscript.
### Large operator and limits
So far our example has actually been rendered with the [`display="block"`](/en-US/docs/Learn/MathML/First_steps/Getting_started#the_display_attribute) attribute. Let's look at the same example, as rendered without that attribute:
```html hidden
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My page with moved limits and small largeop</title>
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
</head>
<body>
<math>
<mroot>
<mrow>
<munder>
<mrow>
<msub>
<mi>z</mi>
<mn>1</mn>
</msub>
<mo>+</mo>
<msub>
<mi>z</mi>
<mn>2</mn>
</msub>
</mrow>
<mo>⎵</mo>
</munder>
</mrow>
<mn>3</mn>
</mroot>
<mo>+</mo>
<mfrac>
<mrow
><mo>|</mo>
<mover>
<mrow>
<msub>
<mi>v</mi>
<mn>1</mn>
</msub>
<mo>+</mo>
<msub>
<mi>v</mi>
<mn>2</mn>
</msub>
</mrow>
<mo>→</mo>
</mover>
<mo>|</mo>
</mrow>
<msup>
<mi>s</mi>
<mn>3</mn>
</msup>
</mfrac>
<mo>−</mo>
<mrow>
<munderover>
<mo>∑</mo>
<mrow>
<mi>i</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mi>n</mi>
</munderover>
<msqrt>
<mrow>
<msub>
<mi>a</mi>
<mi>i</mi>
</msub>
<mo>−</mo>
<msubsup>
<mi>K</mi>
<mn>0</mn>
<mi>i</mi>
</msubsup>
</mrow>
</msqrt>
</mrow>
</math>
</body>
</html>
```
```css hidden
.highlight {
color: red;
}
math {
font-size: 200%;
}
```
{{ EmbedLiveSample('Large_operator_and_limits', 700, 200, "", "") }}
As expected, the formula is no longer centered and the rendering is modified to minimized the height. Focusing on the summation symbol, one can notice that the sigma is drawn smaller and that the scripts of the `<munderover>` element are now attached as a subscript and a superscript! This is due to two properties of the "∑" operator:
- _largeop_: The operator is drawn with a bigger glyph if the `<math>` tag has a `display="block"` attribute.
- _movablelimits_: The underscripts and overscripts attached to the operator are respectively rendered as subscripts and superscripts if the `<math>` tag does not have the `display="block"` attribute.
> **Note:** The _largeop_ property is actually unrelated to scripts, even though operators having this property are typically scripted. The _movablelimits_ property is taken into account for `<munder>` and `<mover>` elements too.
## Summary
In this article, we've finished reviewing basic layout introducing elements `<msub>`, `<msup>`, `<msubsup>`, `<munder>`, `<mover>`, `<munderover>` for subscripts, superscripts, underscripts and overscripts. Using these elements, we were able to briefly introduce new properties of the `<mo>` element. In the next article, we will continue focus on [tabular layout](/en-US/docs/Learn/MathML/First_steps/Tables).
{{LearnSidebar}}{{PreviousMenuNext("Learn/MathML/First_steps/Fractions_and_roots", "Learn/MathML/First_steps/Tables", "Learn/MathML/First_steps")}}
## See also
- [The `<msub>` element](/en-US/docs/Web/MathML/Element/msub)
- [The `<msup>` element](/en-US/docs/Web/MathML/Element/msup)
- [The `<msubsup>` element](/en-US/docs/Web/MathML/Element/msubsup)
- [The `<munder>` element](/en-US/docs/Web/MathML/Element/munder)
- [The `<mover>` element](/en-US/docs/Web/MathML/Element/mover)
- [The `<munderover>` element](/en-US/docs/Web/MathML/Element/munderover)
| 0 |
data/mdn-content/files/en-us/learn/mathml/first_steps | data/mdn-content/files/en-us/learn/mathml/first_steps/tables/index.md | ---
title: MathML tables
slug: Learn/MathML/First_steps/Tables
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/MathML/First_steps/Scripts", "Learn/MathML/First_steps/Three_famous_mathematical_formulas", "Learn/MathML/First_steps")}}
Once all basic math notations are known, it remains to consider tabular layout which can be used for matrix-like expressions and other advanced math layout.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, and HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>. and <a href="/en-US/docs/Learn/HTML/Tables"
>HTML tables</a
>)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To get familiar with MathML tabular elements and be aware of some
use cases.
</td>
</tr>
</tbody>
</table>
## MathML tabular elements
The MathML tabular elements are similar to the ones for [HTML tables](/en-US/docs/Learn/HTML/Tables): the `<mtable>` element represents a mathematical table, it has `<mtr>` elements as its children (representing rows), each of them having `<mtd>` elements as its children (representing cells). An `<mtable>` element can be inserted anywhere in a MathML formula. The `<mtd>` element can contain any number of MathML children and will lay them out as an `<mrow>` container.
Tables are typically used for matrix-like expressions (including vectors). Here is a basic example taken from the [article about the CSS `matrix()` function](/en-US/docs/Web/CSS/transform-function/matrix):
```html hidden
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
```
```html
<math display="block">
<mrow>
<mo>(</mo>
<mtable>
<mtr>
<mtd>
<mi>a</mi>
</mtd>
<mtd>
<mi>c</mi>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<msub>
<mi>t</mi>
<mi>x</mi>
</msub>
</mtd>
</mtr>
<mtr>
<mtd>
<mi>b</mi>
</mtd>
<mtd>
<mi>d</mi>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<msub>
<mi>t</mi>
<mi>y</mi>
</msub>
</mtd>
</mtr>
<mtr>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mn>1</mn>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
</mtr>
<mtr>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mn>1</mn>
</mtd>
</mtr>
</mtable>
<mo>)</mo>
</mrow>
</math>
```
{{ EmbedLiveSample('MathML_tabular_elements', 700, 200, "", "") }}
## Allowing cells to span multiple rows and columns
This is again similar to [HTML tables](/en-US/docs/Learn/HTML/Tables/Basics#allowing_cells_to_span_multiple_rows_and_columns). The `<mtd>` element accepts the `columnspan` and `rowspan` attributes to indicate that the cell spans multiples rows and columns. Below the inner matrix spans two columns of the outer matrix:
```html hidden
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My matrix with columnspan</title>
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
</head>
<body>
<math display="block">
<mrow>
<mo>(</mo>
<mtable>
<mtr>
<mtd columnspan="2">
<mrow>
<mo>(</mo>
<mtable>
<mtr>
<mtd>
<mi>a</mi>
</mtd>
<mtd>
<mi>c</mi>
</mtd>
</mtr>
<mtr>
<mtd>
<mi>b</mi>
</mtd>
<mtd>
<mi>d</mi>
</mtd>
</mtr>
</mtable>
<mo>)</mo>
</mrow>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mi>T</mi>
</mtd>
</mtr>
<mtr>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mn>1</mn>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
</mtr>
<mtr>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mn>1</mn>
</mtd>
</mtr>
</mtable>
<mo>)</mo>
</mrow>
</math>
</body>
</html>
```
{{ EmbedLiveSample('allowing_cells_to_span_multiple_rows_and_columns', 700, 200, "", "") }}
> **Note:** For historical reason, the MathML attribute for column spanning is called `columnspan` not `colspan`.
## Usage for advanced layout
Besides representing matrix-like objects, MathML tables are sometimes used for advanced layout inside mathematical formulas, for example in [Wikipedia's definition of Legendre symbol](https://en.wikipedia.org/wiki/Legendre_symbol). Here, the different cases are written on three different rows while the values and conditions are placed on two different columns.
```html hidden
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My first matrix</title>
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
</head>
<body>
<math display="block">
<mrow>
<mrow>
<mo>(</mo>
<mfrac>
<mi>a</mi>
<mi>b</mi>
</mfrac>
<mo>)</mo>
</mrow>
<mo>=</mo>
<mrow>
<mo>{</mo>
<mtable>
<mtr>
<mtd>
<mn>1</mn>
</mtd>
<mtd>
<mtext>if </mtext>
<mi>a</mi>
<mtext> is a quadratic residue modulo </mtext>
<mi>p</mi>
<mtext> and </mtext>
<mi>a</mi>
<mtext> is not a multiple of </mtext>
<mi>p</mi>
<mo>;</mo>
</mtd>
</mtr>
<mtr>
<mtd>
<mo>−</mo>
<mn>1</mn>
</mtd>
<mtd>
<mtext>if </mtext>
<mi>a</mi>
<mtext> is a non-quadratic residue modulo </mtext>
<mi>p</mi>
<mo>;</mo>
</mtd>
</mtr>
<mtr>
<mtd>
<mn>0</mn>
</mtd>
<mtd>
<mtext>if </mtext>
<mi>a</mi>
<mtext> is a multiple of </mtext>
<mi>p</mi>
<mo>.</mo>
</mtd>
</mtr>
</mtable>
</mrow>
</mrow>
</math>
</body>
</html>
```
{{ EmbedLiveSample('Usage_for_advanced_layout', 700, 200, "", "") }}
> **Warning:** The [`<mtable>` article](/en-US/docs/Web/MathML/Element/mtable) provides more advanced layout options via special attributes such as alignment or spacing. These originated before CSS equivalents and were originally designed and intended for renderers which were not-CSS aware. However, these attributes may not be implemented in all browsers. In the future, it is likely that usages of `<mtable>` for layout-only purpose (i.e. not actual matrix-like objects) can be replaced with CSS-based alternatives.
## Summary
In this article, we've reviewed the `<mtable>`, `<mtr>` and `<mtd>` elements which are the equivalent of HTML elements for tables. We have seen how to use them for representing matrix-like objects and how it is sometimes used for advanced layout.
You've nearly finished this module — we only have one more thing to do. In the [three famous mathematical formulas assessment](/en-US/docs/Learn/MathML/First_steps/Three_famous_mathematical_formulas) you'll use your new knowledge to rewrite a small mathematical article using HTML and MathML.
{{LearnSidebar}}{{PreviousMenuNext("Learn/MathML/First_steps/Scripts", "Learn/MathML/First_steps/Three_famous_mathematical_formulas", "Learn/MathML/First_steps")}}
## See also
- [Learning about HTML tables](/en-US/docs/Learn/HTML/Tables)
- [The `<mtable>` element](/en-US/docs/Web/MathML/Element/mtable)
- [The `<mtr>` element](/en-US/docs/Web/MathML/Element/mtr)
- [The `<mtd>` element](/en-US/docs/Web/MathML/Element/mtd)
| 0 |
data/mdn-content/files/en-us/learn/mathml/first_steps | data/mdn-content/files/en-us/learn/mathml/first_steps/text_containers/index.md | ---
title: MathML Text Containers
slug: Learn/MathML/First_steps/Text_containers
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/MathML/First_steps/Getting_started", "Learn/MathML/First_steps/Fractions_and_roots", "Learn/MathML/First_steps")}}
Now that you get a better idea of MathML, we move focus on text containers (variables, numbers, operators, ...) which are used as building blocks of MathML formulas.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>) and some CSS notions on text styling (read <a href="/en-US/docs/Learn/CSS/Styling_text/Fundamentals">fundamental text and font styling</a> and
<a href="/en-US/docs/Learn/CSS/Styling_text/Web_fonts">web fonts</a>).
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To get familiar with MathML elements used for writing text and be aware
of special behaviors.
</td>
</tr>
</tbody>
</table>
## Unicode characters for mathematics
Mathematical formulas involve many special characters, for example greek letters (e.g. Δ), fraktur letters (e.g. 𝔄), double-struck letter (e.g. ℂ), binary operators (e.g. ≠), arrows (e.g. ⇒), integral symbols (e.g. ∮), summation symbols (e.g. ∑), logical symbols (e.g. ∀), fences (e.g. ⌊) and many more. Wikipedia's article [Mathematical operators and symbols in Unicode](https://en.wikipedia.org/wiki/Mathematical_operators_and_symbols_in_Unicode) provides a good overview of the characters used.
Since most of these characters are not part of Basic Latin Unicode block, it is recommended to specify your [document's character encoding](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML#specifying_your_documents_character_encoding) and to serve it with appropriate [web fonts](/en-US/docs/Learn/CSS/Styling_text/Web_fonts). Here is a basic template to use UTF-8 encoding and the [Latin Modern Math](/en-US/docs/Web/MathML/Fonts#fonts_with_a_math_table) font:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My page with math characters</title>
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
</head>
<body>
<p style="font-family: Latin Modern Math">∀A∊𝔰𝔩(n,𝔽),TrA=0</p>
</body>
</html>
```
{{ EmbedLiveSample('Unicode_characters_for_mathematics', 700, 100, "", "") }}
## A bit of semantics
We noticed in the [getting started with MathML](/en-US/docs/Learn/MathML/First_steps/Getting_started) article that the text in MathML formulas are wrapped in specific container elements such as the `<mn>` or `<mo>`. More generally, every text in MathML formulas must be included inside such container elements, called _token_ elements. In addition, MathML provides multiple token elements in order to distinguish different meanings of the text content:
- The `<mi>` element, which represents an "identifier" which could be a symbolic name or arbitrary text. Examples: `<mi>x</mi>` (variable), `<mi>cos</mi>` (function name) and `<mi>π</mi>` (symbolic constant).
- The `<mn>` element represents a "numeric literal" or other data that should be rendered as a numeric literal. Examples: `<mn>2</mn>` (integer), `<mn>0.123</mn>` (decimal number) or `<mn>0xFFEF</mn>` (hexadecimal value).
- The `<mo>` element represents an operator or anything that should be rendered as an operator. For example `<mo>+</mo>` (binary operation), `<mo>≤</mo>` (binary relation), `<mo>∑</mo>` (summation symbol) or `<mo>[</mo>` (fence).
- The `<mtext>` element is used to represent arbitrary text. For example short words in formulas such as `<mtext>if<mtext>` or `<mtext>maps to</mtext>`.
### Active learning: recognize token elements
Below is a more complex example, which says that the absolute value of a real number is equal to that number if and only if it is nonnegative. Spot the different token elements and what they are used for. Each time you click the corresponding text, it is highlighted and a confirmation message is displayed.
```html hidden
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My page with math characters</title>
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
</head>
<body>
<math display="block">
<mrow>
<mrow>
<mo>|</mo>
<mi>x</mi>
<mo>|</mo>
</mrow>
<mo>=</mo>
<mi>x</mi>
</mrow>
<mtext> iff </mtext>
<mrow>
<mi>x</mi>
<mo>≥</mo>
<mn>0</mn>
</mrow>
</math>
<input type="button" id="clearOutput" value="Reset" />
<div id="output"></div>
</body>
</html>
```
```css hidden
.highlight {
color: red;
}
math {
font-size: 200%;
}
```
```js hidden
const tokenElements = Array.from(
document.querySelectorAll("mi, mo, mn, mtext"),
);
const outputDiv = document.getElementById("output");
function clearHighlight() {
tokenElements.forEach((token) => {
token.classList.remove("highlight");
});
}
tokenElements.forEach((token) => {
token.addEventListener("click", () => {
clearHighlight();
token.classList.add("highlight");
outputDiv.insertAdjacentHTML(
"beforeend",
`<p><strong>You clicked an <code><${token.tagName}></code> element.</strong></p>`,
);
});
});
document.getElementById("clearOutput").addEventListener("click", () => {
clearHighlight();
outputDiv.innerHTML = "";
});
```
{{ EmbedLiveSample('Active_learning_recognize_token_elements', 700, 400, "", "") }}
Finally, read the MathML source to verify whether that corresponds to your expectation:
```xml
<math display="block">
<mrow>
<mrow>
<mo>|</mo>
<mi>x</mi>
<mo>|</mo>
</mrow>
<mo>=</mo>
<mi>x</mi>
</mrow>
<mtext> iff </mtext>
<mrow>
<mi>x</mi>
<mo>≥</mo>
<mn>0</mn>
</mrow>
</math>
```
> **Note:** It is sometimes difficult to decide the token element to use for a given text content. In practice, choosing the wrong element should not cause major issues because all token elements are generally rendered the same by browser implementations (for visual display and for assistive technologies). However, the `<mi>` and `<mo>` elements have special distinguishing features that one should be aware of. They are explained in the following sections.
## Automatic italicization of \<mi>
One typographic convention in mathematics is to use italic letters for variables. In order to help with that, `<mi>` elements with a single character may be automatically rendered as italic. This is the case for all the letters from the latin and greek alphabets. Compare the rendering of the two `<mi>` elements in the following formula:
```html
<math>
<mi>sin</mi>
<mi>x</mi>
</math>
```
{{ EmbedLiveSample('Automatic italicization of <mi>', 700, 50) }}
> **Note:** [This table from MathML Core](https://w3c.github.io/mathml-core/#italic-mappings) provide the exhaustive list of characters that are subject to italicization, together with the corresponding italic characters.
## Reverting automatic italicization of \<mi>
In order to revert this default italic transformation you can attach a `mathvariant="normal"` attribute on the `<mi>` element.
Compare the rendering of the uppercase gamma letters in the following formula:
```html
<math>
<mi>Γ</mi>
<mi mathvariant="normal">Γ</mi>
</math>
```
{{ EmbedLiveSample('Reverting automatic italicization of <mi>', 700, 50) }}
> **Note:** Although you can apply this transformation, normally you'd just use the desired [Mathematical Alphanumeric Symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols).
## Operator properties of \<mo>
MathML contains an [operator dictionary](https://w3c.github.io/mathml-core/#operator-dictionary-human) that defines default properties of `<mo>` elements depending on their content and the position within its container (prefix, infix or postfix). Let's consider a concrete example:
```html
<table>
<tr>
<td>Prefix plus</td>
<td>
<math>
<mo>+</mo>
<mi>i</mi>
</math>
</td>
</tr>
<tr>
<td>Infix plus</td>
<td>
<math>
<mi>j</mi>
<mo>+</mo>
<mi>i</mi>
</math>
</td>
</tr>
<tr>
<td>Prefix sum</td>
<td>
<math>
<mo>∑</mo>
<mi>i</mi>
</math>
</td>
</tr>
</table>
```
This example should render similarly to the screenshot below. Observe the spacing between the `<mi>i</mi>` elements and its preceding `<mo>`: no spacing for the prefix plus, some spacing for the infix plus and some smaller spacing for the prefix summation symbol.

Operators have many other properties that we will see in more details later. For now, remember to use an `<mo>` container for characters in the operator dictionary and to properly group subexpressions with `<mrow>` elements in order to help MathML renderers.
### Active learning: spot the difference
Now that you are a bit familiar with special features of `<mi>` and `<mo>`, let's rewrite the `<p>` element in the [example at the top of the page](#unicode_characters_for_mathematics) with some actual MathML. Compare the visual rendering in your browser and explain the differences with the text-only version.
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My page with math characters</title>
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
</head>
<body>
<p style="font-family: Latin Modern Math">∀A∊𝔰𝔩(n,𝔽),TrA=0</p>
<p>
<math>
<mo>∀</mo>
<mrow>
<mi>A</mi>
<mo>∊</mo>
<mrow>
<mi>𝔰𝔩</mi>
<mrow>
<mo>(</mo>
<mi>n</mi>
<mo>,</mo>
<mi>𝔽</mi>
<mo>)</mo>
</mrow>
</mrow>
</mrow>
<mo>,</mo>
<mrow>
<mrow>
<mi>Tr</mi>
<mi>A</mi>
</mrow>
<mo>=</mo>
<mn>0</mn>
</mrow>
</math>
</p>
<input id="showSolution" type="button" value="Show solution" />
<div id="solution"></div>
</body>
</html>
```
```css hidden
div {
padding: 0.5em;
}
```
```js hidden
document.getElementById("showSolution").addEventListener(
"click",
() => {
document.getElementById("solution").insertAdjacentHTML(
"beforeEnd",
`<ul>
<li><strong>The <code><mi></code> elements containing the "A" and "n" variables are rendered in italic</strong>. However, the <code><mi></code> elements with multiple characters "𝔰𝔩" or whose character is "𝔽" are still rendered upright.</li>
<li><strong>Spacing is automatically added around the <code><mo></code> elements whose text is "∀", "∊", "=" or a comma</strong>. However, some of them have no spacing added before while the parentheses still have no spacing around them.</li>
</ul>`,
);
},
{ once: true },
);
```
{{ EmbedLiveSample('active_learning_spot_the_difference', 700, 500, "", "") }}
> **Note:** An obvious difference is that the source code became much more verbose with MathML. Recall that this tutorial is about learning the language but in practice MathML content is generally not written manually. See the [Authoring MathML](/en-US/docs/Web/MathML/Authoring) page for more information.
### Active learning: stretchy operators
The operator dictionary defines a default _stretchy_ property as well as corresponding _stretch axis_ for some operators. For example, an operator can stretch vertically by default to cover the maximum height of non-stretchy siblings within its `<mrow>` container. By tweaking a bit the [previous exercise](#active_learning_recognize_token_elements), one can make operators stretch vertically. Can you find them?
```html hidden
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My page with stretchy operators</title>
<link
rel="stylesheet"
href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
</head>
<body>
<math display="block">
<mrow>
<mrow>
<mo>|</mo>
<mfrac>
<mn>1</mn>
<mi>x</mi>
</mfrac>
<mo>|</mo>
</mrow>
<mo>=</mo>
<mfrac>
<mn>1</mn>
<mrow>
<mo>|</mo>
<mi>x</mi>
<mo>|</mo>
</mrow>
</mfrac>
<mo>=</mo>
<mfrac>
<mn>1</mn>
<mi>x</mi>
</mfrac>
</mrow>
<mtext> iff </mtext>
<mrow>
<mi>x</mi>
<mo>≥</mo>
<mn>0</mn>
</mrow>
</math>
<input type="button" id="clearOutput" value="Reset" />
<div id="output"></div>
</body>
</html>
```
```css hidden
.highlight {
color: red;
}
math {
font-size: 200%;
}
```
```js hidden
const tokenElements = Array.from(
document.querySelectorAll("mi, mo, mn, mtext"),
);
const stretchyMoElements = Array.from(
document.getElementsByTagName("mo"),
).slice(0, 2);
const outputDiv = document.getElementById("output");
function clearHighlight() {
tokenElements.forEach((token) => {
token.classList.remove("highlight");
});
}
tokenElements.forEach((token) => {
token.addEventListener("click", () => {
clearHighlight();
token.classList.add("highlight");
let message = "";
let tagName = `<code><${token.tagName}></code>`;
if (token.tagName !== "mo") message = `No, this is an ${tagName} element!`;
else if (!stretchyMoElements.includes(token))
message = `No, this is an ${tagName} element, but it's not vertically stretched.`;
else
message = `Correct, this ${tagName} element is indeed stretched to the height of its <code><mfrac></code> sibling.`;
outputDiv.insertAdjacentHTML(
"beforeend",
`<p><strong>${message}</strong></p>`,
);
});
});
document.getElementById("clearOutput").addEventListener("click", () => {
clearHighlight();
outputDiv.innerHTML = "";
});
```
{{ EmbedLiveSample('Active_learning_stretchy_fences', 700, 400, "", "") }}
As usual, you are invited to read the source code when you are done:
```xml
<math display="block">
<mrow>
<mrow>
<mo>|</mo>
<mfrac>
<mn>1</mn>
<mi>x</mi>
</mfrac>
<mo>|</mo>
</mrow>
<mo>=</mo>
<mfrac>
<mn>1</mn>
<mrow>
<mo>|</mo>
<mi>x</mi>
<mo>|</mo>
</mrow>
</mfrac>
<mo>=</mo>
<mfrac>
<mn>1</mn>
<mi>x</mi>
</mfrac>
</mrow>
<mtext> iff </mtext>
<mrow>
<mi>x</mi>
<mo>≥</mo>
<mn>0</mn>
</mrow>
</math>
```
> **Warning:** Special [math fonts](/en-US/docs/Web/MathML/Fonts) are generally required to make that stretching possible, the previous example relies on [web fonts](/en-US/docs/Learn/CSS/Styling_text/Web_fonts).
## Summary
In this article, we have learnt about a few _token_ elements that are used as text containers as well as their different semantics, namely `<mi>` (identifier), `<mn>` (numbers), `<mo>` (operators), `<mtext>` (generic text). We have seen special Unicode characters that are commonly found in math formulas and given an overview of some observable behaviors of the `<mi>` and `<mo>` elements. In the next article, we will see how to rely on _token_ elements to build much complex expressions such as [fractions and roots](/en-US/docs/Learn/MathML/First_steps/Fractions_and_roots).
{{LearnSidebar}}{{PreviousMenuNext("Learn/MathML/First_steps/Getting_started", "Learn/MathML/First_steps/Fractions_and_roots", "Learn/MathML/First_steps")}}
## See also
- [The `<mi>` element](/en-US/docs/Web/MathML/Element/mi)
- [The `<mn>` element](/en-US/docs/Web/MathML/Element/mn)
- [The `<mo>` element](/en-US/docs/Web/MathML/Element/mo)
- [The `<mtext>` element](/en-US/docs/Web/MathML/Element/mtext)
| 0 |
data/mdn-content/files/en-us/learn/mathml/first_steps | data/mdn-content/files/en-us/learn/mathml/first_steps/getting_started/index.md | ---
title: Getting started with MathML
slug: Learn/MathML/First_steps/Getting_started
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/MathML/First_steps/Text_containers", "Learn/MathML/First_steps")}}
In this article, we will take a simple HTML document and see how to add MathML formulas into it, introducing a few elements along the way.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software"
>Basic software installed</a
>, basic knowledge of
<a
href="/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files"
>working with files</a
>, and HTML basics (study
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the basic syntax of MathML and how to integrate it in
HTML pages.
</td>
</tr>
</tbody>
</table>
## Inserting formulas in HTML via the \<math> element
MathML uses the same syntax as HTML to represent a tree of elements and attributes. In particular, each mathematical formula is represented by an element `<math>` which can be placed inside an HTML page. In the following document, it is inside a paragraph of text:
```html
<!doctype html>
<html lang="en-US">
<head>
<title>My first math page</title>
</head>
<body>
<p>
The fraction
<math>
<mfrac>
<mn>1</mn>
<mn>3</mn>
</mfrac>
</math>
is not a decimal number.
</p>
</body>
</html>
```
The `<mfrac>` element specifies a fraction with a numerator (its first child) and a denominator (its second child). This is how it renders in your browser:
{{ EmbedLiveSample('Inserting_formulas_in_HTML', 700, 100, "", "") }}
> **Warning:** If you just see "1 3" instead of a fraction, then your browser may not support MathML. Check out the [browser compatibility table](/en-US/docs/Web/MathML/Element/math#browser_compatibility) for further details.
### The display attribute
Note that in the previous example, the formula is on the same line as the text of the paragraph. However, it is quite common to instead render large mathematical formulas centered on their own line as shown below. To achieve that, you need to attach a `display="block"` attribute on the `<math>` element.
```html hidden
<!doctype html>
<html lang="en-US">
<head>
<title>My first math page</title>
</head>
<body>
<p>
The fraction
<math display="block">
<mfrac>
<mn>1</mn>
<mn>3</mn>
</mfrac>
</math>
is not a decimal number.
</p>
</body>
</html>
```
{{ EmbedLiveSample('The_display_attribute', 700, 100, "", "") }}
You may also notice some subtle change in the appearance: the text and vertical spacing of the fraction becomes a bit bigger. Without the `display="block"` attribute, the height is minimized to avoid disturbing the flow of the surrounding text. With the `display="block"` attribute, priority is instead put on legibility of the mathematical formula.
> **Note:** This corresponds to the LaTeX's concept of _inline_ formulas (delimited by dollar signs `$...$`) and _display_ formulas (delimited by `\[...\]`).
> **Note:** The appearance change mentioned above is actually controlled by the [`math-style`](/en-US/docs/Web/CSS/math-style) property which is initially `normal` for `<math display="block">` and `compact` otherwise. In some MathML subtrees, this property can then automatically become `compact` but we will ignore this subtlety for this introductory tutorial. Again, this is similar to LaTeX.
## Grouping with the \<mrow> element
The `<math>` element can actually contain an arbitrary number of children and will essentially render them in a row. For instance, the simple formula "1 + 2 + 3" would be encoded like this in MathML:
```html
<math>
<mn>1</mn>
<mo>+</mo>
<mn>2</mn>
<mo>+</mo>
<mn>3</mn>
</math>
```
The `<mrow>` element is a generic container that performs similar layout but can be placed anywhere in the MathML subtree. It is helpful to group several elements together. For instance, the numerator of the following fraction (its first child) is "one plus two".
```html
<math>
<mfrac>
<mrow>
<mn>1</mn>
<mo>+</mo>
<mn>2</mn>
</mrow>
<mn>3</mn>
</mfrac>
</math>
```
### Active learning: nested expressions
As an exercise, figure out how to write the following expressions using only the MathML elements we've seen so far. If you are stuck or want to verify the solution, check the source code of the example.
```html hidden
<ol>
<li>
"one half" plus "two third":
<!-- It's correct but unnecessary to group the children of the math element with an mrow element. -->
<math>
<mfrac>
<mn>1</mn>
<mn>2</mn>
</mfrac>
<mo>+</mo>
<mfrac>
<mn>2</mn>
<mn>3</mn>
</mfrac>
</math>
</li>
<li>
"one plus two plus three" over "four plus five":
<math>
<mfrac>
<mrow>
<mn>1</mn>
<mo>+</mo>
<mn>2</mn>
<mo>+</mo>
<mn>3</mn>
</mrow>
<mrow>
<mn>4</mn>
<mo>+</mo>
<mn>5</mn>
</mrow>
</mfrac>
</math>
</li>
<li>
"one quarter" over "two plus three":
<math>
<mfrac>
<mfrac>
<mn>1</mn>
<mn>4</mn>
</mfrac>
<mrow>
<mn>2</mn>
<mo>+</mo>
<mn>3</mn>
</mrow>
</mfrac>
</math>
</li>
</ol>
```
{{ EmbedLiveSample('Active_learning_nested_expressions', 700, 200, "", "") }}
## Summary
In this article, we have taken a look at how to use the `<math>` element to insert a mathematical formula inside a HTML document. We have learned about rendering differences between `<math>` elements that use `display="block"` or not. In addition, we stumbled upon a couple of other MathML elements: `<mfrac>` for fractions, `<mrow>` for grouping and finally a few text elements. We will analyze these [text containers](/en-US/docs/Learn/MathML/First_steps/Text_containers) further in the next article.
{{LearnSidebar}}{{NextMenu("Learn/MathML/First_steps/Text_containers", "Learn/MathML/First_steps")}}
## See also
- [Using MathML](/en-US/docs/Web/MathML/Authoring#using_mathml)
- [The `<math>` element](/en-US/docs/Web/MathML/Element/math)
- [The `<mfrac>` element](/en-US/docs/Web/MathML/Element/mfrac)
- [The `<mrow>` element](/en-US/docs/Web/MathML/Element/mrow)
- [The `math-style` property](/en-US/docs/Web/CSS/math-style)
- [The `math-depth` property](/en-US/docs/Web/CSS/math-depth)
| 0 |
data/mdn-content/files/en-us/learn | data/mdn-content/files/en-us/learn/forms/index.md | ---
title: Web forms — Working with user data
slug: Learn/Forms
page-type: learn-module
---
{{LearnSidebar}}
This module provides a series of articles that will help you master the essentials of web forms. Web forms are a very powerful tool for interacting with users — most commonly they are used for collecting data from users, or allowing them to control a user interface. However, for historical and technical reasons, it's not always obvious how to use them to their full potential. In the articles listed below, we'll cover all the essential aspects of Web forms including marking up their HTML structure, styling form controls, validating form data, and submitting data to the server.
> **Callout:**
>
> #### Looking to become a front-end web developer?
>
> We have put together a course that includes all the essential information you need to
> work towards your goal.
>
> [**Get started**](/en-US/docs/Learn/Front-end_web_developer)
## Prerequisites
Before starting this module, you should at least work through our [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML). At this point you should find the [Introductory guides](#introductory_guides) easy to understand, and also be able to make use of our [Basic native form controls](/en-US/docs/Learn/Forms/Basic_native_form_controls) guide.
Mastering forms however requires more than just HTML knowledge — you also need to learn some specific techniques to style form controls, and some scripting knowledge is required to handle things like validation and creating custom form controls. Therefore, before you look at the other sections listed below we'd recommend that you go away and learn some [CSS](/en-US/docs/Learn/CSS) and [JavaScript](/en-US/docs/Learn/JavaScript) first.
The above text is a good indicator as to why we've put web forms into its own standalone module, rather than trying to mix bits of it into the HTML, CSS, and JavaScript topic areas — form elements are more complex than most other HTML elements, and they also require a close marriage of related CSS and JavaScript techniques to get the most out of them.
> **Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as [JSBin](https://jsbin.com/) or [Glitch](https://glitch.com/).
## Introductory guides
- [Your first form](/en-US/docs/Learn/Forms/Your_first_form)
- : The first article in our series provides your very first experience of creating a web form, including designing a simple form, implementing it using the right HTML elements, adding some very simple styling via CSS, and how data is sent to a server.
- [How to structure a web form](/en-US/docs/Learn/Forms/How_to_structure_a_web_form)
- : With the basics out of the way, we now look in more detail at the elements used to provide structure and meaning to the different parts of a form.
## The different form controls
- [Basic native form controls](/en-US/docs/Learn/Forms/Basic_native_form_controls)
- : We start off this section by looking at the functionality of the original HTML {{htmlelement("input")}} types in detail, looking at what options are available to collect different types of data.
- [The HTML5 input types](/en-US/docs/Learn/Forms/HTML5_input_types)
- : Here we continue our deep dive into the `<input>` element, looking at the additional input types provided when HTML5 was released, and the various UI controls and data collection enhancements they provide. Additionally, we look at the {{htmlelement('output')}} element.
- [Other form controls](/en-US/docs/Learn/Forms/Other_form_controls)
- : Next we take a look at all the non-`<input>` form controls and associated tools, such as {{htmlelement('select')}}, {{htmlelement('textarea')}}, {{htmlelement('meter')}}, and {{htmlelement('progress')}}.
## Form styling guides
- [Styling web forms](/en-US/docs/Learn/Forms/Styling_web_forms)
- : This article provides an introduction to styling forms with CSS, including all the basics you might need to know for basic styling tasks.
- [Advanced form styling](/en-US/docs/Learn/Forms/Advanced_form_styling)
- : Here we look at some more advanced form styling techniques that need to be used when trying to deal with some of the more difficult-to-style form elements.
- [UI pseudo-classes](/en-US/docs/Learn/Forms/UI_pseudo-classes)
- : An introduction to the UI pseudo-classes enabling HTML form controls to be targeted based on their current state.
## Validating and submitting form data
- [Client-side form validation](/en-US/docs/Learn/Forms/Form_validation)
- : Sending data is not enough — we also need to make sure that the data users enter into forms is in the correct format to process it successfully, and that it won't break our applications. We also want to help our users to fill out our forms correctly and not get frustrated when trying to use our apps. Form validation helps us achieve these goals — this article tells you what you need to know.
- [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data)
- : This article looks at what happens when a user submits a form — where does the data go, and how do we handle it when it gets there? We also look at some of the security concerns associated with sending form data.
## Advanced articles
The following articles aren't essential to the learning pathway, but they'll prove interesting and useful when you've mastered the above techniques and want to know more.
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- : You'll come across some cases where the native form widgets just don't provide what you need, e.g. because of styling or functionality. In such cases, you may need to build your own form widget out of raw HTML. This article explains how you'd do this and the considerations you need to be aware of when doing so, with a practical case study.
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- : This article looks at ways to use a form to assemble an HTTP request and send it via custom JavaScript, rather than standard form submission. It also looks at why you'd want to do this, and the implications of doing so. (See also [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects).)
- [CSS property compatibility table for form controls](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
- : This last article provides a handy reference allowing you to look up what CSS properties are compatible with what form elements.
## See also
- [HTML forms element reference](/en-US/docs/Web/HTML/Element#forms)
- [HTML \<input> types reference](/en-US/docs/Web/HTML/Element/input)
- [HTML attribute reference](/en-US/docs/Web/HTML/Attributes)
- [User input methods and controls](/en-US/docs/Learn/Forms/User_input_methods)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/test_your_skills_colon__advanced_styling/index.md | ---
title: "Test your skills: Advanced styling"
slug: Learn/Forms/Test_your_skills:_Advanced_styling
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Advanced form styling](/en-US/docs/Learn/Forms/Advanced_form_styling) and [UI pseudo-classes](/en-US/docs/Learn/Forms/UI_pseudo-classes) articles.
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Advanced form styling 1
In our first advanced styling tasks, we want you to handle making a search input as consistent as possible across browsers — a trickier task than with standard text inputs, even on modern browsers.
We've already provided you with a basic reset to build upon.
1. First of all, try giving the search box a consistent width, height, padding, and border color across browsers.
2. You'll find that some browsers will not behave in terms of the form element's height. This is due to native OS styling being used in some cases. How can you remove this native styling?
3. Once you've removed the native styling, you'll need to add back one of the features it was providing, to keep the same look and feel we originally had. How do you do this?
4. One thing that is inconsistent across browsers (particularly looking at Safari here) is the position of the standard blue focus outline. How can you remove this?
5. There is a major problem with just getting rid of the blue focus outline. What is it? Can you add some kind of styling back in so that users can tell when the search box is being hovered or focused?
6. Another thing that commonly denotes a search box is a magnifying glass icon. We've made one available in the same directory as our HTML files — see [search-24px.png](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/advanced-styling/search-24px.png) — plus a `<div>` element after the search input to help you attach it, should you need it. Can you figure out a sensible way to attach it, and can you use some CSS to get it to sit to the right of the search box, and be lined up vertically as well?
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/html/forms/tasks/advanced-styling/advanced-styling1.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/advanced-styling/advanced-styling1-download.html) to work in your own editor or in an online editor.
## Advanced form styling 2
In our next task we provide you with a set of three radio buttons. We want you to give them custom styling.
We've already provided you with a basic reset to build upon.
1. First of all, get rid of their default styling.
2. Next, give the radio buttons a reasonable base style — the style they have when the page first loads. This can be anything you like, but you probably want to set a width and height (of somewhere between about 18 and 24 pixels), and a subtle border and/or background color.
3. Now give the radio buttons a different style for when they are selected.
4. Align the radio buttons nicely with the labels.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/html/forms/tasks/advanced-styling/advanced-styling2.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/advanced-styling/advanced-styling2-download.html) to work in your own editor or in an online editor.
## Advanced form styling 3
In our final task for this assessment series, we provide you with a feedback form that is already nicely-styled — you've already seen something similar if you've worked through our [UI pseudo-classes](/en-US/docs/Learn/Forms/UI_pseudo-classes) article, and now we want you to come up with your own solution.
What we'd like you to do is make use of some advanced pseudo-classes to provide some useful indicators of validity.
1. First of all, we want you to provide some specific styling to visually indicate which inputs have to be filled in — they cannot be left empty.
2. Second, we want you to provide a useful visual indicator of whether the data entered inside each input is valid or not.
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/advanced-styling/advanced-styling3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/how_to_structure_a_web_form/index.md | ---
title: How to structure a web form
slug: Learn/Forms/How_to_structure_a_web_form
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Forms/Your_first_form", "Learn/Forms/Basic_native_form_controls", "Learn/Forms")}}
With the basics out of the way, we'll now look in more detail at the elements used to provide structure and meaning to the different parts of a form.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">understanding of HTML</a>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand how to structure HTML forms and give them semantics so they are usable and accessible.
</td>
</tr>
</tbody>
</table>
The flexibility of forms makes them one of the most complex structures in [HTML](/en-US/docs/Learn/HTML); you can build any kind of basic form using dedicated form elements and attributes. Using the correct structure when building an HTML form will help ensure that the form is both usable and [accessible](/en-US/docs/Learn/Accessibility).
## The \<form> element
The {{HTMLElement("form")}} element formally defines a form and attributes that determine the form's behavior. Each time you want to create an HTML form, you must start it by using this element, nesting all the contents inside. Many assistive technologies and browser plugins can discover {{HTMLElement("form")}} elements and implement special hooks to make them easier to use.
We already met this in the previous article.
> **Warning:** It's strictly forbidden to nest a form inside another form. Nesting can cause forms to behave unpredictably, so it is a bad idea.
It's always possible to use a form control outside of a {{HTMLElement("form")}} element. If you do so, by default that control has nothing to do with any form unless you associate it with a form using its [`form`](/en-US/docs/Web/HTML/Element/input#form) attribute. This was introduced to let you explicitly bind a control with a form even if it is not nested inside it.
Let's move forward and cover the structural elements you'll find nested in a form.
## The \<fieldset> and \<legend> elements
The {{HTMLElement("fieldset")}} element is a convenient way to create groups of widgets that share the same purpose, for styling and semantic purposes. You can label a {{HTMLElement("fieldset")}} by including a {{HTMLElement("legend")}} element just below the opening {{HTMLElement("fieldset")}} tag. The text content of the {{HTMLElement("legend")}} formally describes the purpose of the {{HTMLElement("fieldset")}} it is included inside.
Many assistive technologies will use the {{HTMLElement("legend")}} element as if it is a part of the label of each control inside the corresponding {{HTMLElement("fieldset")}} element. For example, some screen readers such as [Jaws](https://www.freedomscientific.com/products/software/jaws/) and [NVDA](https://www.nvaccess.org/) will speak the legend's content before speaking the label of each control.
Here is a little example:
```html
<form>
<fieldset>
<legend>Fruit juice size</legend>
<p>
<input type="radio" name="size" id="size_1" value="small" />
<label for="size_1">Small</label>
</p>
<p>
<input type="radio" name="size" id="size_2" value="medium" />
<label for="size_2">Medium</label>
</p>
<p>
<input type="radio" name="size" id="size_3" value="large" />
<label for="size_3">Large</label>
</p>
</fieldset>
</form>
```
> **Note:** You can find this example in [fieldset-legend.html](https://github.com/mdn/learning-area/blob/main/html/forms/html-form-structure/fieldset-legend.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/html-form-structure/fieldset-legend.html)).
When reading the above form, a screen reader will speak "Fruit juice size small" for the first widget, "Fruit juice size medium" for the second, and "Fruit juice size large" for the third.
The use case in this example is one of the most important. Each time you have a set of radio buttons, you should nest them inside a {{HTMLElement("fieldset")}} element. There are other use cases, and in general the {{HTMLElement("fieldset")}} element can also be used to section a form. Ideally, long forms should be spread across multiple pages, but if a form is getting long and must be on a single page, putting the different related sections inside different fieldsets improves usability.
Because of its influence over assistive technology, the {{HTMLElement("fieldset")}} element is one of the key elements for building accessible forms; however, it is your responsibility not to abuse it. If possible, each time you build a form, try to [listen to how a screen reader](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#screen_readers) interprets it. If it sounds odd, try to improve the form structure.
## The \<label> element
As we saw in the previous article, The {{HTMLElement("label")}} element is the formal way to define a label for an HTML form widget. This is the most important element if you want to build accessible forms — when implemented properly, screen readers will speak a form element's label along with any related instructions, as well as it being useful for sighted users. Take this example, which we saw in the previous article:
```html
<label for="name">Name:</label> <input type="text" id="name" name="user_name" />
```
With the `<label>` associated correctly with the `<input>` via its `for` attribute (which contains the `<input>` element's `id` attribute), a screen reader will read out something like "Name, edit text".
There is another way to associate a form control with a label — nest the form control within the `<label>`, implicitly associating it.
```html
<label for="name">
Name: <input type="text" id="name" name="user_name" />
</label>
```
Even in such cases however, it is considered best practice to set the `for` attribute to ensure all assistive technologies understand the relationship between label and widget.
If there is no label, or if the form control is neither implicitly nor explicitly associated with a label, a screen reader will read out something like "Edit text blank", which isn't very helpful at all.
### Labels are clickable, too!
Another advantage of properly set up labels is that you can click or tap the label to activate the corresponding widget. This is useful for controls like text inputs, where you can click the label as well as the input to focus it, but it is especially useful for radio buttons and checkboxes — the hit area of such a control can be very small, so it is useful to make it as easy to activate as possible.
For example, clicking on the "I like cherry" label text in the example below will toggle the selected state of the _taste_cherry_ checkbox:
```html
<form>
<p>
<input type="checkbox" id="taste_1" name="taste_cherry" value="cherry" />
<label for="taste_1">I like cherry</label>
</p>
<p>
<input type="checkbox" id="taste_2" name="taste_banana" value="banana" />
<label for="taste_2">I like banana</label>
</p>
</form>
```
> **Note:** You can find this example in [checkbox-label.html](https://github.com/mdn/learning-area/blob/main/html/forms/html-form-structure/checkbox-label.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/html-form-structure/checkbox-label.html)).
### Multiple labels
Strictly speaking, you can put multiple labels on a single widget, but this is not a good idea as some assistive technologies can have trouble handling them. In the case of multiple labels, you should nest a widget and its labels inside a single {{htmlelement("label")}} element.
Let's consider this example:
```html
<p>Required fields are followed by <span aria-label="required">*</span>.</p>
<!-- So this: -->
<!--div>
<label for="username">Name:</label>
<input id="username" type="text" name="username" required>
<label for="username"><span aria-label="required">*</label>
</div-->
<!-- would be better done like this: -->
<!--div>
<label for="username">
<span>Name:</span>
<input id="username" type="text" name="username" required>
<span aria-label="required">*</span>
</label>
</div-->
<!-- But this is probably best: -->
<div>
<label for="username">Name: <span aria-label="required">*</span></label>
<input id="username" type="text" name="username" required />
</div>
```
{{EmbedLiveSample("Multiple_labels", 120, 120)}}
The paragraph at the top states a rule for required elements. The rule must be included _before_ it is used so that sighted users and users of assistive technologies such as screen readers can learn what it means before they encounter a required element. While this helps inform users what an asterisk means, it can not be relied upon. A screen reader will speak an asterisk as "_star_" when encountered. When hovered by a sighted mouse user, "_required_" should appear, which is achieved by use of the `title` attribute. Titles being read aloud depends on the screen reader's settings, so it is more reliable to also include the [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute, which is always read by screen readers.
The above variants increase in effectiveness as you go through them:
- In the first example, the label is not read out at all with the input — you just get "edit text blank", plus the actual labels are read out separately. The multiple `<label>` elements confuse the screen reader.
- In the second example, things are a bit clearer — the label read out along with the input is "name star name edit text required", and the labels are still read out separately. Things are still a bit confusing, but it's a bit better this time because the `<input>` has a label associated with it.
- The third example is best — the actual label is read out all together, and the label read out with the input is "name required edit text".
> **Note:** You might get slightly different results, depending on your screen reader. This was tested in VoiceOver (and NVDA behaves similarly). We'd love to hear about your experiences too.
> **Note:** You can find this example on GitHub as [required-labels.html](https://github.com/mdn/learning-area/blob/main/html/forms/html-form-structure/required-labels.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/html-form-structure/required-labels.html)). Don't test the example with 2 or 3 of the versions uncommented — screen readers will definitely get confused if you have multiple labels AND multiple inputs with the same ID!
## Common HTML structures used with forms
Beyond the structures specific to web forms, it's good to remember that form markup is just HTML. This means that you can use all the power of HTML to structure a web form.
As you can see in the examples, it's common practice to wrap a label and its widget with a {{HTMLElement("li")}} element within a {{HTMLElement("ul")}} or {{HTMLElement("ol")}} list. {{HTMLElement("p")}} and {{HTMLElement("div")}} elements are also commonly used. Lists are recommended for structuring multiple checkboxes or radio buttons.
In addition to the {{HTMLElement("fieldset")}} element, it's also common practice to use HTML titles (e.g. {{htmlelement("Heading_Elements", "h1")}}, {{htmlelement("Heading_Elements", "h2")}}) and sectioning (e.g. {{htmlelement("section")}}) to structure complex forms.
Above all, it is up to you to find a comfortable coding style that results in accessible, usable forms. Each separate section of functionality should be contained in a separate {{htmlelement("section")}} element, with {{htmlelement("fieldset")}} elements to contain radio buttons.
### Active learning: building a form structure
Let's put these ideas into practice and build a slightly more involved form — a payment form. This form will contain a number of control types that you may not yet understand. Don't worry about this for now; you'll find out how they work in the next article ([Basic native form controls](/en-US/docs/Learn/Forms/Basic_native_form_controls)). For now, read the descriptions carefully as you follow the below instructions, and start to form an appreciation of which wrapper elements we are using to structure the form, and why.
1. To start with, make a local copy of our [blank template file](https://github.com/mdn/learning-area/blob/main/html/introduction-to-html/getting-started/index.html) in a new directory on your computer.
2. Next, create your form by adding a {{htmlelement("form")}} element:
```html-nolint
<form>
```
3. Inside the `<form>` element, add a heading and paragraph to inform users how required fields are marked:
```html-nolint
<h1>Payment form</h1>
<p>
Required fields are followed by
<strong><span aria-label="required">*</span></strong>.
</p>
```
4. Next, we'll add a larger section of code into the form, below our previous entry. Here you'll see that we are wrapping the contact information fields inside a distinct {{htmlelement("section")}} element. Moreover, we have a set of three radio buttons, each of which we are putting inside its own list ({{htmlelement("li")}}) element. We also have two standard text {{htmlelement("input")}}s and their associated {{htmlelement("label")}} elements, each contained inside a {{htmlelement("p")}}, and a password input for entering a password. Add this code to your form:
```html
<section>
<h2>Contact information</h2>
<fieldset>
<legend>Title</legend>
<ul>
<li>
<label for="title_1">
<input type="radio" id="title_1" name="title" value="A" />
Ace
</label>
</li>
<li>
<label for="title_2">
<input type="radio" id="title_2" name="title" value="K" />
King
</label>
</li>
<li>
<label for="title_3">
<input type="radio" id="title_3" name="title" value="Q" />
Queen
</label>
</li>
</ul>
</fieldset>
<p>
<label for="name">
<span>Name: </span>
<strong><span aria-label="required">*</span></strong>
</label>
<input type="text" id="name" name="username" required />
</p>
<p>
<label for="mail">
<span>Email: </span>
<strong><span aria-label="required">*</span></strong>
</label>
<input type="email" id="mail" name="usermail" required />
</p>
<p>
<label for="pwd">
<span>Password: </span>
<strong><span aria-label="required">*</span></strong>
</label>
<input type="password" id="pwd" name="password" required />
</p>
</section>
```
5. The second `<section>` of our form is the payment information.
We have three distinct controls along with their labels, each contained inside a `<p>`.
The first is a drop-down menu ({{htmlelement("select")}}) for selecting credit card type.
The second is an `<input>` element of type `tel`, for entering a credit card number; while we could have used the `number` type, we don't want the number's spinner UI.
The last one is an `<input>` element of type `text`, for entering the expiration date of the card; this includes a _placeholder_ attribute indicating the correct format, and a _pattern_ that tests that the entered date has the correct format.
These newer input types are reintroduced in [The HTML5 input types](/en-US/docs/Learn/Forms/HTML5_input_types).
Enter the following below the previous section:
```html
<section>
<h2>Payment information</h2>
<p>
<label for="card">
<span>Card type:</span>
</label>
<select id="card" name="usercard">
<option value="visa">Visa</option>
<option value="mc">Mastercard</option>
<option value="amex">American Express</option>
</select>
</p>
<p>
<label for="number">
<span>Card number:</span>
<strong><span aria-label="required">*</span></strong>
</label>
<input type="tel" id="number" name="cardnumber" required />
</p>
<p>
<label for="expiration">
<span>Expiration date:</span>
<strong><span aria-label="required">*</span></strong>
</label>
<input
type="text"
id="expiration"
name="expiration"
required
placeholder="MM/YY"
pattern="^(0[1-9]|1[0-2])\/([0-9]{2})$" />
</p>
</section>
```
6. The last section we'll add is a lot simpler, containing only a {{htmlelement("button")}} of type `submit`, for submitting the form data. Add this to the bottom of your form now:
```html
<section>
<p>
<button type="submit">Validate the payment</button>
</p>
</section>
```
7. Finally, complete your form by adding the outer {{htmlelement("form")}} closing tag:
```html
</form>
```
```css hidden
h1 {
margin-top: 0;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
form {
margin: 0 auto;
width: 400px;
padding: 1em;
border: 1px solid #ccc;
border-radius: 1em;
}
div + div {
margin-top: 1em;
}
label span {
display: inline-block;
text-align: right;
}
input,
textarea {
font: 1em sans-serif;
width: 250px;
box-sizing: border-box;
border: 1px solid #999;
}
input[type="checkbox"],
input[type="radio"] {
width: auto;
border: none;
}
input:focus,
textarea:focus {
border-color: #000;
}
textarea {
vertical-align: top;
height: 5em;
resize: vertical;
}
fieldset {
width: 250px;
box-sizing: border-box;
border: 1px solid #999;
}
button {
margin: 20px 0 0 0;
}
label {
position: relative;
display: inline-block;
}
p label {
width: 100%;
}
label em {
position: absolute;
right: 5px;
top: 20px;
}
```
We applied some extra CSS to the finished form below. If you'd like to make changes to the appearance of your form, you can copy styles from [the example](/en-US/docs/Learn/Forms/How_to_structure_a_web_form/Example) or visit [Styling web forms](/en-US/docs/Learn/Forms/Styling_web_forms).
{{EmbedLiveSample("active_learning_building_a_form_structure","100%",620)}}
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find a further test to verify that you've retained this information before you move on — see [Test your skills: Form structure](/en-US/docs/Learn/Forms/Test_your_skills:_Form_structure).
## Summary
You now have all the knowledge you'll need to properly structure your web forms. We will cover many of the features introduced here in the next few articles, with the next article looking in more detail at using all the different types of form widgets you'll want to use to collect information from your users.
## See also
- [A List Apart: _Sensible Forms: A Form Usability Checklist_](https://alistapart.com/article/sensibleforms/)
{{PreviousMenuNext("Learn/Forms/Your_first_form", "Learn/Forms/Basic_native_form_controls", "Learn/Forms")}}
### Advanced Topics
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms/how_to_structure_a_web_form | data/mdn-content/files/en-us/learn/forms/how_to_structure_a_web_form/example/index.md | ---
title: Example
slug: Learn/Forms/How_to_structure_a_web_form/Example
page-type: learn-module-chapter
---
This the example for a basic payment form for the article [How to structure an HTML form](/en-US/docs/Learn/Forms/How_to_structure_a_web_form).
## A payment form
### HTML
```html-nolint
<form method="post">
<h1>Payment form</h1>
<p>
Required fields are followed by
<strong><span aria-label="required">*</span></strong>.
</p>
<section>
<h2>Contact information</h2>
<fieldset>
<legend>Title</legend>
<ul>
<li>
<label for="title_1">
<input type="radio" id="title_1" name="title" value="A" />
Ace
</label>
</li>
<li>
<label for="title_2">
<input type="radio" id="title_2" name="title" value="K" />
King
</label>
</li>
<li>
<label for="title_3">
<input type="radio" id="title_3" name="title" value="Q" />
Queen
</label>
</li>
</ul>
</fieldset>
<p>
<label for="name">
<span>Name: </span>
<strong><span aria-label="required">*</span></strong>
</label>
<input type="text" id="name" name="username" required />
</p>
<p>
<label for="mail">
<span>Email: </span>
<strong><span aria-label="required">*</span></strong>
</label>
<input type="email" id="mail" name="usermail" required />
</p>
<p>
<label for="pwd">
<span>Password: </span>
<strong><span aria-label="required">*</span></strong>
</label>
<input type="password" id="pwd" name="password" required />
</p>
</section>
<section>
<h2>Payment information</h2>
<p>
<label for="card">
<span>Card type:</span>
</label>
<select id="card" name="usercard">
<option value="visa">Visa</option>
<option value="mc">Mastercard</option>
<option value="amex">American Express</option>
</select>
</p>
<p>
<label for="number">
<span>Card number:</span>
<strong><span aria-label="required">*</span></strong>
</label>
<input type="tel" id="number" name="cardnumber" />
</p>
<p>
<label for="expiration">
<span>Expiration date:</span>
<strong><span aria-label="required">*</span></strong>
</label>
<input
type="text"
id="expiration"
required="true"
placeholder="MM/YY"
pattern="^(0[1-9]|1[0-2])\/([0-9]{2})$" />
</p>
</section>
<section>
<p><button type="submit">Validate the payment</button></p>
</section>
</form>
```
### CSS
```css
h1 {
margin-top: 0;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
form {
margin: 0 auto;
width: 400px;
padding: 1em;
border: 1px solid #ccc;
border-radius: 1em;
}
div + div {
margin-top: 1em;
}
label span {
display: inline-block;
text-align: right;
}
input,
textarea {
font: 1em sans-serif;
width: 250px;
box-sizing: border-box;
border: 1px solid #999;
}
input[type="checkbox"],
input[type="radio"] {
width: auto;
border: none;
}
input:focus,
textarea:focus {
border-color: #000;
}
textarea {
vertical-align: top;
height: 5em;
resize: vertical;
}
fieldset {
width: 250px;
box-sizing: border-box;
border: 1px solid #999;
}
button {
margin: 20px 0 0 0;
}
label {
position: relative;
display: inline-block;
}
p label {
width: 100%;
}
label em {
position: absolute;
right: 5px;
top: 20px;
}
```
### Result
{{ EmbedLiveSample('A_payment_form', '100%', 620) }}
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/advanced_form_styling/index.md | ---
title: Advanced form styling
slug: Learn/Forms/Advanced_form_styling
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Forms/Styling_web_forms", "Learn/Forms/UI_pseudo-classes", "Learn/Forms")}}
In this article, we will see what can be done with CSS to style the types of form control that are more difficult to style — the "bad" and "ugly" categories. As we saw [in the previous article](/en-US/docs/Learn/Forms/Styling_web_forms), text fields and buttons are perfectly easy to style; now we will dig into styling the more problematic bits.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">HTML</a> and
<a href="/en-US/docs/Learn/CSS/First_steps">CSS</a>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand what parts of forms are hard to style, and why; to learn
what can be done to customize them.
</td>
</tr>
</tbody>
</table>
To recap what we said in the previous article, we have:
**The bad**: Some elements are more difficult to style, requiring more complex CSS or some more specific tricks:
- Checkboxes and radio buttons
- [`<input type="search">`](/en-US/docs/Web/HTML/Element/input/search)
**The ugly**: Some elements can't be styled thoroughly using CSS. These include:
- Elements involved in creating dropdown widgets, including {{HTMLElement("select")}}, {{HTMLElement("option")}}, {{HTMLElement("optgroup")}} and {{HTMLElement("datalist")}}.
- [`<input type="color">`](/en-US/docs/Web/HTML/Element/input/color)
- Date-related controls such as [`<input type="datetime-local">`](/en-US/docs/Web/HTML/Element/input/datetime-local)
- [`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range)
- [`<input type="file">`](/en-US/docs/Web/HTML/Element/input/file)
- {{HTMLElement("progress")}} and {{HTMLElement("meter")}}
Let's first talk about the [`appearance`](/en-US/docs/Web/CSS/appearance) property, which is pretty useful for making all of the above more stylable.
## appearance: controlling OS-level styling
In the previous article we said that historically, the styling of web form controls was largely taken from the underlying operating system, which is part of the problem with customizing the look of these controls.
The {{cssxref("appearance")}} property was created as a way to control what OS- or system-level styling was applied to web form controls. By far the most helpful value, and probably the only one you'll use, is `none`. This stops any control you apply it to from using system-level styling, as much as possible, and lets you build up the styles yourself using CSS.
For example, let's take the following controls:
```html
<form>
<p>
<label for="search">search: </label>
<input id="search" name="search" type="search" />
</p>
<p>
<label for="text">text: </label>
<input id="text" name="text" type="text" />
</p>
<p>
<label for="date">date: </label>
<input id="date" name="date" type="datetime-local" />
</p>
<p>
<label for="radio">radio: </label>
<input id="radio" name="radio" type="radio" />
</p>
<p>
<label for="checkbox">checkbox: </label>
<input id="checkbox" name="checkbox" type="checkbox" />
</p>
<p><input type="submit" value="submit" /></p>
<p><input type="button" value="button" /></p>
</form>
```
Applying the following CSS to them removes system-level styling.
```css
input {
appearance: none;
}
```
The following live example shows you what they look like in your system — default on the left, and with the above CSS applied on the right ([find it here also](https://mdn.github.io/learning-area/html/forms/styling-examples/appearance-tester.html) if you want to test it on other systems).
{{EmbedGHLiveSample("learning-area/html/forms/styling-examples/appearance-tester.html", '100%', 400)}}
In most cases, the effect is to remove the stylized border, which makes CSS styling a bit easier, but isn't really essential. In a couple of cases — search and radio buttons/checkboxes, it becomes way more useful. We'll look at those now.
### Taming search boxes
[`<input type="search">`](/en-US/docs/Web/HTML/Element/input/search) is basically just a text input, so why is `appearance: none;` useful here? The answer is that Safari search boxes have some styling restrictions — you can't adjust their `height` or `font-size` freely, for example.
This can be fixed using our friend `appearance: none;`, which disables the default appearance:
```css
input[type="search"] {
appearance: none;
}
```
In the example below, you can see two identical styled search boxes. The right one has `appearance: none;` applied, and the left one doesn't. If you look at it in Safari on macOS you'll see that the left one isn't sized properly.
{{EmbedGHLiveSample("learning-area/html/forms/styling-examples/search-appearance.html", '100%', 200)}}
Interestingly, setting border/background on the search field also fixes this problem. The following styled search doesn't have `appearance: none;` applied, but it doesn't suffer from the same problem in Safari as the previous example.
{{EmbedGHLiveSample("learning-area/html/forms/styling-examples/styled-search.html", '100%', 200)}}
> **Note:** You may have noticed that in the search field, the "x" delete icon, which appears when the value of the search is not null, disappears when the input loses focus in Edge and Chrome, but stays put in Safari. To remove via CSS, you can use `input[type="search"]:not(:focus, :active)::-webkit-search-cancel-button { display: none; }`.
### Styling checkboxes and radio buttons
Styling a checkbox or a radio button is tricky by default. The sizes of checkboxes and radio buttons are not meant to be changed with their default designs, and browsers react very differently when you try.
For example, consider this simple test case:
```html
<label
><span><input type="checkbox" name="q5" value="true" /></span> True</label
>
<label
><span><input type="checkbox" name="q5" value="false" /></span> False</label
>
```
```css
span {
display: inline-block;
background: red;
}
input[type="checkbox"] {
width: 100px;
height: 100px;
}
```
Different browsers handle the checkbox and span differently, often ugly ways:
| Browser | Rendering |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------ |
| Firefox 71 (macOS) |  |
| Firefox 57 (Windows 10) |  |
| Chrome 77 (macOS), Safari 13, Opera |  |
| Chrome 63 (Windows 10) |  |
| Edge 16 (Windows 10) |  |
#### Using appearance: none on radios/checkboxes
As we showed before, you can remove the default appearance of a checkbox or radio button altogether with {{cssxref('appearance')}}`:none;`. Let's take this example HTML:
```html
<form>
<fieldset>
<legend>Fruit preferences</legend>
<p>
<label>
<input type="checkbox" name="fruit" value="cherry" />
I like cherry
</label>
</p>
<p>
<label>
<input type="checkbox" name="fruit" value="banana" disabled />
I can't like banana
</label>
</p>
<p>
<label>
<input type="checkbox" name="fruit" value="strawberry" />
I like strawberry
</label>
</p>
</fieldset>
</form>
```
Now, let's style these with a custom checkbox design. Let's start by unstyling the original check boxes:
```css
input[type="checkbox"] {
appearance: none;
}
```
We can use the {{cssxref(":checked")}} and {{cssxref(":disabled")}} pseudo-classes to change the appearance of our custom checkbox as its state changes:
```css
input[type="checkbox"] {
position: relative;
width: 1em;
height: 1em;
border: 1px solid gray;
/* Adjusts the position of the checkboxes on the text baseline */
vertical-align: -2px;
/* Set here so that Windows' High-Contrast Mode can override */
color: green;
}
input[type="checkbox"]::before {
content: "✔";
position: absolute;
font-size: 1.2em;
right: -1px;
top: -0.3em;
visibility: hidden;
}
input[type="checkbox"]:checked::before {
/* Use `visibility` instead of `display` to avoid recalculating layout */
visibility: visible;
}
input[type="checkbox"]:disabled {
border-color: black;
background: #ddd;
color: gray;
}
```
You'll find out more about such pseudo-classes and more in the [next article](/en-US/docs/Learn/Forms/UI_pseudo-classes); the above ones do the following:
- `:checked` — the checkbox (or radio button) is in a checked state — the user has clicked/activated it.
- `:disabled` — the checkbox (or radio button) is in a disabled state — it cannot be interacted with.
You can see the live result:
{{EmbedGHLiveSample("learning-area/html/forms/styling-examples/checkboxes-styled.html", '100%', 200)}}
We've also created a couple of other examples to give you more ideas:
- [Styled radio buttons](https://mdn.github.io/learning-area/html/forms/styling-examples/radios-styled.html): Custom radio button styling.
- [Toggle switch example](https://mdn.github.io/learning-area/html/forms/toggle-switch-example/): A checkbox styled to look like a toggle switch.
If you view these checkboxes in a browser that doesn't support {{cssxref("appearance")}}, your custom design will be lost, but they will still look like checkboxes and be usable.
## What can be done about the "ugly" elements?
Now let's turn our attention to the "ugly" controls — the ones that are really hard to thoroughly style. In short, these are drop-down boxes, complex control types like [`color`](/en-US/docs/Web/HTML/Element/input/color) and [`datetime-local`](/en-US/docs/Web/HTML/Element/input/datetime-local), and feedback—oriented controls like {{HTMLElement("progress")}} and {{HTMLElement("meter")}}.
The problem is that these elements have very different default looks across browsers, and while you can style them in some ways, some parts of their internals are literally impossible to style.
If you are prepared to live with some differences in look and feel, you can get away with some simple styling to make sizing consistent, uniform styling of things like background-colors, and usage of appearance to get rid of some system-level styling.
Take the following example, which shows a number of the "ugly" form features in action:
{{EmbedGHLiveSample("learning-area/html/forms/styling-examples/ugly-controls.html", '100%', 750)}}
This example has the following CSS applied to it:
```css
body {
font-family: "Josefin Sans", sans-serif;
margin: 20px auto;
max-width: 400px;
}
form > div {
margin-bottom: 20px;
}
select {
appearance: none;
width: 100%;
height: 100%;
}
.select-wrapper {
position: relative;
}
.select-wrapper::after {
content: "▼";
font-size: 1rem;
top: 3px;
right: 10px;
position: absolute;
}
button,
label,
input,
select,
progress,
meter {
display: block;
font-family: inherit;
font-size: 100%;
margin: 0;
box-sizing: border-box;
width: 100%;
padding: 5px;
height: 30px;
}
input[type="text"],
input[type="datetime-local"],
input[type="color"],
select {
box-shadow: inset 1px 1px 3px #ccc;
border-radius: 5px;
}
label {
margin-bottom: 5px;
}
button {
width: 60%;
margin: 0 auto;
}
```
> **Note:** If you want to test these examples across a number of browsers simultaneously, you can [find it live here](https://mdn.github.io/learning-area/html/forms/styling-examples/ugly-controls.html) (also [see here for the source code](https://github.com/mdn/learning-area/blob/main/html/forms/styling-examples/ugly-controls.html)).
>
> Also bear in mind that we've added some JavaScript to the page that lists the files selected by the file picker, below the control itself. This is a simplified version of the example found on the [`<input type="file">`](/en-US/docs/Web/HTML/Element/input/file#examples) reference page.
As you can see, we've done fairly well at getting these to look uniform across modern browsers.
We've applied some global normalizing CSS to all the controls and their labels, to get them to size in the same way, adopt their parent font, etc., as mentioned in the previous article:
```css
button,
label,
input,
select,
progress,
meter {
display: block;
font-family: inherit;
font-size: 100%;
margin: 0;
box-sizing: border-box;
width: 100%;
padding: 5px;
height: 30px;
}
```
We also added some uniform shadow and rounded corners to the controls on which it made sense:
```css
input[type="text"],
input[type="datetime-local"],
input[type="color"],
select {
box-shadow: inset 1px 1px 3px #ccc;
border-radius: 5px;
}
```
On other controls like range types, progress bars, and meters they just add an ugly box around the control area, so it doesn't make sense.
Let's talk about some specifics of each of these types of control, highlighting difficulties along the way.
### Selects and datalists
In modern browsers, selects and datalists are generally not too bad to style provided you don't want to vary the look and feel too much from the defaults.
We've managed to get the basic look of the boxes looking pretty uniform and consistent. The datalist control is `<input type="text">` anyway, so we knew this wouldn't be a problem.
Two things are slightly more problematic. First of all, the select's "arrow" icon that indicates it is a dropdown differs across browsers. It also tends to change if you increase the size of the select box, or resize in an ugly fashion. To fix this in our example we first used our old friend `appearance: none` to get rid of the icon altogether:
```css
select {
appearance: none;
}
```
We then created our own icon using generated content. We put an extra wrapper around the control, because [`::before`](/en-US/docs/Web/CSS/::before)/[`::after`](/en-US/docs/Web/CSS/::after) don't work on `<select>` elements (this is because generated content is placed relative to an element's formatting box, but form inputs work more like replaced elements — their display is generated by the browser and put in place — and therefore don't have one):
```html
<label for="select">Select a fruit</label>
<div class="select-wrapper">
<select id="select" name="select">
<option>Banana</option>
<option>Cherry</option>
<option>Lemon</option>
</select>
</div>
```
We then use generated content to generate a little down arrow, and put it in the right place using positioning:
```css
.select-wrapper {
position: relative;
}
.select-wrapper::after {
content: "▼";
font-size: 1rem;
top: 6px;
right: 10px;
position: absolute;
}
```
The second, slightly more important issue is that you don't have control over the box that appears containing the options when you click on the `<select>` box to open it. You can inherit the font set on the parent, but you won't be able to set things like spacing and colors. The same is true for the autocomplete list that appears with {{HTMLElement("datalist")}}.
If you really need full control over the option styling, you'll have to either use some kind of library to generate a custom control, or build your own custom control, or in the case of select use the `multiple` attribute, which makes all the options appear on the page, sidestepping this particular problem:
```html
<label for="select">Select fruits</label>
<select id="select" name="select" multiple>
…
</select>
```
Of course, this might also not fit in with the design you are going for, but it's worth noting!
### Date input types
The date/time input types ([`datetime-local`](/en-US/docs/Web/HTML/Element/input/datetime-local), [`time`](/en-US/docs/Web/HTML/Element/input/time), [`week`](/en-US/docs/Web/HTML/Element/input/week), [`month`](/en-US/docs/Web/HTML/Element/input/month)) all have the same major associated issue. The actual containing box is as easy to style as any text input, and what we've got in this demo looks fine.
However, the internal parts of the control (e.g. the popup calendar that you use to pick a date, the spinner that you can use to increment/decrement values) are not stylable at all, and you can't get rid of them using `appearance: none;`. If you really need full control over the styling, you'll have to either use some kind of library to generate a custom control, or build your own.
> **Note:** It is worth mentioning [`<input type="number">`](/en-US/docs/Web/HTML/Element/input/number) here too — this also has a spinner that you can use to increment/decrement values, so potentially suffers from the same problem. However, in the case of the `number` type the data being collected is simpler, and it is easy to just use a `tel` input type instead which has the appearance of `text`, but displays the numeric keypad in devices with touch keyboards.
### Range input types
[`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range) is annoying to style. You can use something like the following to remove the default slider track completely and replace it with a custom style (a thin red track, in this case):
```css
input[type="range"] {
appearance: none;
background: red;
height: 2px;
padding: 0;
outline: 1px solid transparent;
}
```
However, it is very difficult to customize the style of the range control's drag handle — to get full control over range styling you'll need to use a whole bunch of complex CSS code, including multiple non-standard, browser-specific pseudo-elements. Check out [Styling Cross-Browser Compatible Range Inputs with CSS](https://css-tricks.com/styling-cross-browser-compatible-range-inputs-css/) on CSS tricks for a detailed write-up of what's needed.
### Color input types
Input controls of type color are not too bad. In supporting browsers, they tend to just give you a block of solid color with a small border.
You can remove the border, just leaving the block of color, using something like this:
```css
input[type="color"] {
border: 0;
padding: 0;
}
```
However, a custom solution is the only way to get anything significantly different.
### File input types
Inputs of type file are generally OK — as you saw in our example, it is fairly easy to create something that fits in OK with the rest of the page — the output line that is part of the control will inherit the parent font if you tell the input to do so, and you can style the custom list of file names and sizes in any way you want; we created it after all.
The only problem with file pickers is that the button provided that you press to open the file picker is completely unstylable — it can't be sized or colored, and it won't even accept a different font.
One way around this is to take advantage of the fact that if you have a label associated with a form control, clicking the label will activate the control. So you could hide the actual form input using something like this:
```css
input[type="file"] {
height: 0;
padding: 0;
opacity: 0;
}
```
And then style the label to act like a button, which when pressed will open the file picker as expected:
```css
label[for="file"] {
box-shadow: 1px 1px 3px #ccc;
background: linear-gradient(to bottom, #eee, #ccc);
border: 1px solid rgb(169, 169, 169);
border-radius: 5px;
text-align: center;
line-height: 1.5;
}
label[for="file"]:hover {
background: linear-gradient(to bottom, #fff, #ddd);
}
label[for="file"]:active {
box-shadow: inset 1px 1px 3px #ccc;
}
```
You can see the result of the above CSS styling in the below live example (see also [styled-file-picker.html](https://mdn.github.io/learning-area/html/forms/styling-examples/styled-file-picker.html) live, and the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/styling-examples/styled-file-picker.html)).
{{EmbedGHLiveSample("learning-area/html/forms/styling-examples/styled-file-picker.html", '100%', 200)}}
### Meters and progress bars
[`<meter>`](/en-US/docs/Web/HTML/Element/meter) and [`<progress>`](/en-US/docs/Web/HTML/Element/progress) are possibly the worst of the lot. As you saw in the earlier example, we can set them to the desired width relatively accurately. But beyond that, they are really difficult to style in any way. They don't handle height settings consistently between each other and between browsers, you can color the background, but not the foreground bar, and setting `appearance: none` on them makes things worse, not better.
It is easier to just create your own custom solution for these features, if you want to be able to control the styling, or use a third-party solution such as [progressbar.js](https://kimmobrunfeldt.github.io/progressbar.js/#examples).
The article [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls) provides an example of how to build a custom designed select with HTML, CSS, and JavaScript.
## Summary
While there are still difficulties using CSS with HTML forms, there are ways to get around many of the problems. There are no clean, universal solutions, but modern browsers offer new possibilities. For now, the best solution is to learn more about the way the different browsers support CSS when applied to HTML form controls.
In the next article of this module, we will explore the different [UI pseudo-classes](/en-US/docs/Learn/Forms/UI_pseudo-classes) available to us in modern browsers for styling forms in different states.
{{PreviousMenuNext("Learn/Forms/Styling_web_forms", "Learn/Forms/UI_pseudo-classes", "Learn/Forms")}}
### Advanced Topics
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/test_your_skills_colon__styling_basics/index.md | ---
title: "Test your skills: Styling basics"
slug: Learn/Forms/Test_your_skills:_Styling_basics
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Styling web forms](/en-US/docs/Learn/Forms/Styling_web_forms) article.
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Styling basics 1
Our basic form styling assessment is fairly free-form, and you have a lot of flexibility over what you end up doing here. But your CSS should aim to fulfill the following requirements:
1. Add some kind of lightweight "reset" to make fonts, padding, margin, and sizing more consistent to begin with.
2. On top of that, add in some nice, consistent styling for the inputs and button.
3. Use some kind of layout technique to make the inputs and labels line up neatly.
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/styling-basics/styling-basics1-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/test_your_skills_colon__form_structure/index.md | ---
title: "Test your skills: Form structure"
slug: Learn/Forms/Test_your_skills:_Form_structure
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [How to structure a web form](/en-US/docs/Learn/Forms/How_to_structure_a_web_form) article.
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Form structure 1
In this task we want you to structure the provided form features:
1. Separate out the first two and second two form fields into two distinct containers, each with a descriptive legend (use "Personal details" for the first two, and "Comment information" for the second two).
2. Mark up each text label with an appropriate element so that it is semantically associated with its respective form field.
3. Add a suitable set of structural elements around the label/field pairs to separate them out.
{{EmbedGHLiveSample("learning-area/html/forms/tasks/form-structure/form-structure1.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/form-structure/form-structure1-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/property_compatibility_table_for_form_controls/index.md | ---
title: CSS property compatibility table for form controls
slug: Learn/Forms/Property_compatibility_table_for_form_controls
page-type: learn-module-chapter
---
{{learnsidebar}}
The following compatibility tables try to summarize the state of CSS support for HTML forms. Due to the complexity of CSS and HTML forms, these tables can't be considered a perfect reference. However, they will give you good insight into what can and can't be done, which will help you learn how to do things.
## How to read the tables
### Values
For each property, there are four possible values:
- ✅ Yes
- : There's reasonably consistent support for the property across browsers. You may still face strange side effects in certain edge cases.
- ⚠️ Partial
- : While the property works, you may frequently face strange side effects or inconsistencies. You should probably avoid these properties unless you master those side effects first.
- ❌ No
- : The property doesn't work or is so inconsistent that it's not reliable.
- n.a.
- : The property has no meaning for this type of widget.
### Rendering
For each property there are two possible renderings:
- N (Normal)
- : Indicates that the property is applied as it is
- T (Tweaked)
- : Indicates that the property is applied with the extra rule below:
```css
* {
/* Turn off the native look and feel */
appearance: none;
}
```
## Compatibility tables
Altering the appearance of form controls with CSS, such as with {{cssxref("border")}}, {{cssxref("background")}}, {{cssxref("border-radius")}}, and {{cssxref("height")}} can partially or fully turn off the native look & feel of widgets on some browsers. Be careful when you use them.
### Text fields
See the `{{htmlelement("input/text", "text")}}`, `{{htmlelement("input/search", "search")}}`, and `{{htmlelement("input/password", "password")}}` input types.
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td
style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
WebKit browsers (mostly on Mac OSX and iOS) use the native look
& feel for the search fields. Therefore, it's required to use
<code>appearance:none</code> to be able to apply this
property to search fields.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
WebKit browsers (mostly on Mac OSX and iOS) use the native look
& feel for the search fields. Therefore, it's required to use
<code>appearance:none</code> to be able to apply this
property to search fields.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
WebKit browsers (mostly on Mac OSX and iOS) use the native look
& feel for the search fields. Therefore, it's required to use
<code>appearance:none</code> to be able to apply this
property to search fields.
</li>
</ol>
</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}<sup>[1]</sup>
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
If the {{cssxref("border-color")}} property is not set,
some WebKit based browsers will apply the
{{cssxref("color")}} property to the border as well as the
font on <code>{{htmlelement("textarea")}}</code>s.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>See the note about {{cssxref("line-height")}}</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td>See the note about Opera</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
IE9 supports this property only on
<code>{{htmlelement("textarea")}}</code>s, whereas Opera
only supports it on single line text fields.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
WebKit browsers (mostly on Mac OSX and iOS) use the native look
& feel for the search fields. Therefore, it's required to use
<code>-webkit-appearance:none</code> to be able to apply this
property to search fields.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
WebKit browsers (mostly on Mac OSX and iOS) use the native look
& feel for the search fields. Therefore, it's required to use
<code>-webkit-appearance:none</code> to be able to apply this
property to search fields.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>IE9 does not support this property.</li>
</ol>
</td>
</tr>
</tbody>
</table>
### Buttons
See the `{{htmlelement("input/button", "button")}}`, `{{htmlelement("input/submit", "submit")}}`, and `{{htmlelement("input/reset", "reset")}}` input types and the `{{htmlelement("button")}}` element.
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
This property is not applied on WebKit based browsers on Mac OSX or
iOS.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
This property is not applied on WebKit based browsers on Mac OSX or
iOS.
</li>
</ol>
</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>See the note about {{cssxref("line-height")}}.</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes<sup>[1]</sup>
</td>
<td>
<ol>
<li>
On Opera the {{cssxref("border-radius")}} property is
applied only if an explicit border is set.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>IE9 does not support this property.</li>
</ol>
</td>
</tr>
</tbody>
</table>
### Number
See the `{{htmlelement("input/number", "number")}}` input type. There is no standard way to change the style of spinners used to change the value of the field, with the spinners on Safari being outside the field.
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
On Opera, the spinners are zoomed in, which can hide the content of
the field.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
On Opera, the spinners are zoomed in, which can hide the content of
the field.
</li>
</ol>
</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>See the note about {{cssxref("line-height")}}.</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td rowspan="3">
<p>
Supported but there is too much inconsistency between browsers to be
reliable.
</p>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
</tr>
</tbody>
</table>
### Check boxes and radio buttons
See the `{{htmlelement("input/checkbox", "checkbox")}}` and `{{htmlelement("input/radio", "radio")}}` input types.
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Some browsers add extra margins and others stretch the widget.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Some browsers add extra margins and others stretch the widget.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td
style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
</tbody>
</table>
### Select boxes (single line)
See the `{{htmlelement("select")}}`, `{{htmlelement("optgroup")}}` and `{{htmlelement("option")}}` elements.
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
This property is okay on the
<code>{{htmlelement("select")}}</code> element, but it cannot
be the case on the <code>{{htmlelement("option")}}</code> or
<code>{{htmlelement("optgroup")}}</code> elements.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[2]</sup>
</td>
<td>
<ol>
<li>
The property is applied, but in an inconsistent way between browsers
on Mac OSX.
</li>
<li>
The property is well applied on the
<code>{{htmlelement("select")}}</code> element, but is
inconsistently handled on
<code>{{htmlelement("option")}}</code> and
<code>{{htmlelement("optgroup")}}</code> elements.
</li>
</ol>
</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
On Mac OSX, WebKit based browsers do not support this property on
native widgets and they, along with Opera, do not support it at all
on <code>{{htmlelement("option")}}</code> and
<code>{{htmlelement("optgroup")}}</code> elements.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
On Mac OSX, WebKit based browsers do not support this property on
native widgets and they, along with Opera, do not support it at all
on <code>{{htmlelement("option")}}</code> and
<code>{{htmlelement("optgroup")}}</code> elements.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
IE9 does not support this property on
<code>{{htmlelement("select")}}</code>,
<code>{{htmlelement("option")}}</code>, and
<code>{{htmlelement("optgroup")}}</code> elements; WebKit
based browsers on Mac OSX do not support this property on
<code>{{htmlelement("option")}}</code> and
<code>{{htmlelement("optgroup")}}</code> elements.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Only Firefox provides full support for this property. Other browsers only support it on
the <code>{{htmlelement("select")}}</code> element.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Most of the browsers only support this property on the
<code>{{htmlelement("select")}}</code> element.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Most of the browsers only support this property on the
<code>{{htmlelement("select")}}</code> element.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Most of the browsers only support this property on the
<code>{{htmlelement("select")}}</code> element.
</li>
</ol>
</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td rowspan="3">
<ol>
<li>
Most of the browsers only support this property on the
<code>{{htmlelement("select")}}</code> element.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
</tr>
</tbody>
</table>
Note Firefox does not provide any way to change the down arrow on the `{{htmlelement("select")}}` element.
### Select boxes (multiline)
See the `{{htmlelement("select")}}`, `{{htmlelement("optgroup")}}` and `{{htmlelement("option")}}` elements and the [`size` attribute](/en-US/docs/Web/HTML/Attributes/size).
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Opera does not support {{cssxref("padding-top")}} and
{{cssxref("padding-bottom")}} on the
<code>{{htmlelement("select")}}</code> element.
</li>
</ol>
</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>See the note about {{cssxref("line-height")}}.</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
IE9 does not support this property on
<code>{{htmlelement("select")}}</code>,
<code>{{htmlelement("option")}}</code>, and
<code>{{htmlelement("optgroup")}}</code> elements; WebKit
based browsers on Mac OSX do not support this property on
<code>{{htmlelement("option")}}</code> and
<code>{{htmlelement("optgroup")}}</code> elements.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td>
<ol>
<li>
WebKit based browser on Mac OSX do not support
this property on this widget.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td>
<ol>
<li>Only supported by Firefox and IE9+.</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Most of the browsers only support this property on the
<code>{{htmlelement("select")}}</code> element.
</li>
</ol>
</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes<sup>[1]</sup>
</td>
<td>
<ol>
<li>
On Opera the {{cssxref("border-radius")}} property is
applied only if an explicit border is set.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>IE9 does not support this property.</li>
</ol>
</td>
</tr>
</tbody>
</table>
### Datalist
See the `{{htmlelement("datalist")}}` and `{{htmlelement("input")}}` elements and the [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute.
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
</tbody>
</table>
### File picker
See the `{{htmlelement("input/file", "file")}}` input type.
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Supported, but there is too much inconsistency between browsers to
be reliable.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>Many browsers apply this property to the select button.</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
It acts more or less like an extra left margin outside the widget.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Supported, but there is too much inconsistency between browsers to
be reliable.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>IE9 does not support this property.</li>
</ol>
</td>
</tr>
</tbody>
</table>
### Date pickers
See the `{{htmlelement("input/date", "date")}}` and `{{htmlelement("input/time", "time")}}` input types. Many properties are supported, but there is too much inconsistency between browsers to be reliable.
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td></td>
</tr>
</tbody>
</table>
### Color pickers
See the `{{htmlelement("input/color", "color")}}` input type:
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
Opera handles this like a select widget with the same restriction.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
Opera handles this like a select widget with the same restriction.
</li>
</ol>
</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td rowspan="3">
<ol>
<li>
Supported, but there is too much inconsistency between browsers to
be reliable.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
</tr>
</tbody>
</table>
### Meters and progress
See the `{{htmlelement("meter")}}` and `{{htmlelement("progress")}}` elements:
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Chrome hides the
<code>{{htmlelement("progress")}}</code> and
<code>{{htmlelement("meter")}}</code> element when the
{{cssxref("padding")}} property is applied on a tweaked
element.
</li>
</ol>
</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td rowspan="3">
<ol>
<li>
Supported, but there is too much inconsistency between browsers to
be reliable.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
</tr>
</tbody>
</table>
### Range
See the `{{htmlelement("input/range", "range")}}` input type. There is no standard way to change the style of the range grip and Opera has no way to tweak the default rendering of the range widget.
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>
Chrome and Opera add some extra space around the widget.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td>
<ol>
<li>
The {{cssxref("padding")}} is applied, but has no visual
effect.
</li>
</ol>
</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td rowspan="3">
<ol>
<li>
Supported, but there is too much inconsistency between browsers to
be reliable.
</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
❌ No<sup>[1]</sup>
</td>
</tr>
</tbody>
</table>
### Image buttons
See the `{{htmlelement("input/image", "image")}}` input type:
<table>
<thead>
<tr>
<th scope="col">Property</th>
<th scope="col" style="text-align: center">N</th>
<th scope="col" style="text-align: center">T</th>
<th scope="col">Note</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4" scope="col"><em>CSS box model</em></th>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("width")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("height")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("border")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("margin")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="vertical-align: top">
{{cssxref("padding")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Text and font</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("color")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("font")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("letter-spacing")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-align")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-decoration")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-indent")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-overflow")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("text-transform")}}
</th>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td style="text-align: center; vertical-align: top">N.A.</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4" scope="col"><em>Border and background</em></th>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("background")}}
</th>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td style="text-align: center; vertical-align: top">
✅ Yes
</td>
<td></td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("border-radius")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>IE9 does not support this property.</li>
</ol>
</td>
</tr>
<tr>
<th scope="row" style="white-space: nowrap; vertical-align: top">
{{cssxref("box-shadow")}}
</th>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td style="text-align: center; vertical-align: top">
⚠️ Partial<sup>[1]</sup>
</td>
<td>
<ol>
<li>IE9 does not support this property.</li>
</ol>
</td>
</tr>
</tbody>
</table>
## See also
### Learning path
- [Your first HTML form](/en-US/docs/Learn/Forms/Your_first_form)
- [How to structure an HTML form](/en-US/docs/Learn/Forms/How_to_structure_a_web_form)
- [The native form widgets](/en-US/docs/Learn/Forms/Basic_native_form_controls)
- [HTML5 input types](/en-US/docs/Learn/Forms/HTML5_input_types)
- [Additional form controls](/en-US/docs/Learn/Forms/Other_form_controls)
- [UI pseudo-classes](/en-US/docs/Learn/Forms/UI_pseudo-classes)
- [Styling HTML forms](/en-US/docs/Learn/Forms/Styling_web_forms)
- [Form data validation](/en-US/docs/Learn/Forms/Form_validation)
- [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data)
### Advanced Topics
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [How to build custom form widgets](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [HTML forms in legacy browsers](/en-US/docs/Learn/Forms/HTML_forms_in_legacy_browsers)
- [Advanced styling for HTML forms](/en-US/docs/Learn/Forms/Advanced_form_styling)
- **Property compatibility table for form widgets**
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls/index.md | ---
title: How to build custom form controls
slug: Learn/Forms/How_to_build_custom_form_controls
page-type: learn-module-chapter
---
{{LearnSidebar}}
There are some cases where the available native HTML form controls may seem like they are not enough. For example, if you need to [perform advanced styling](/en-US/docs/Learn/Forms/Advanced_form_styling) on some controls such as the {{HTMLElement("select")}} element, or if you want to provide custom behaviors, you may consider building your own controls.
In this article, we will discuss how to build a custom control. To that end, we will work with an example: rebuilding the {{HTMLElement("select")}} element. We will also discuss how, when, and whether building your own control makes sense, and what to consider when building a control is a requirement.
> **Note:** We'll focus on building the control, not on how to make the code generic and reusable; that would involve some non-trivial JavaScript code and DOM manipulation in an unknown context, and that is out of the scope of this article.
## Design, structure, and semantics
Before building a custom control, you should start by figuring out exactly what you want. This will save you some precious time. In particular, it's important to clearly define all the states of your control. To do this, it's good to start with an existing control whose states and behavior are well known, so that you can mimic those as much as possible.
In our example, we will rebuild the {{HTMLElement("select")}} element. Here is the result we want to achieve:

This screenshot shows the three main states of our control: the normal state (on the left); the active state (in the middle) and the open state (on the right).
In terms of behavior, we are recreating a native HTML element. Therefore it should have the same behaviors and semantics as the native HTML element. We require our control to be usable with a mouse as well as with a keyboard, and comprehensible to a screen reader, just like any native control. Let's start by defining how the control reaches each state:
**The control is in its normal state when:**
- the page loads.
- the control was active and the user clicks anywhere outside it.
- the control was active and the user moves the focus to another control using the keyboard (e.g. the
<kbd>Tab</kbd>
key).
**The control is in its active state when:**
- the user clicks on it or touches it on a touch screen.
- the user hits the tab key and it gains focus.
- the control was in its open state and the user clicks on it.
**The control is in its open state when:**
- the control is in any other state than open and the user clicks on it.
Once we know how to change states, it is important to define how to change the control's value:
**The value changes when:**
- the user clicks on an option when the control is in the open state.
- the user hits the up or down arrow keys when the control is in its active state.
**The value does not change when:**
- the user hits the up arrow key when the first option is selected.
- the user hits the down arrow key when the last option is selected.
Finally, let's define how the control's options will behave:
- When the control is opened, the selected option is highlighted
- When the mouse is over an option, the option is highlighted and the previously highlighted option is returned to its normal state
For the purposes of our example, we'll stop with that; however, if you're a careful reader, you'll notice that some behaviors are missing. For example, what do you think will happen if the user hits the tab key while the control is in its open state? The answer is _nothing_. OK, the right behavior seems obvious but the fact is, because it's not defined in our specs, it is very easy to overlook this behavior. This is especially true in a team environment when the people who design the control's behavior are different from the ones who implement it.
Another fun example: what will happen if the user hits the up or down arrow keys while the control is in the open state? This one is a little bit trickier. If you consider that the active state and the open state are completely different, the answer is again "nothing will happen" because we did not define any keyboard interactions for the opened state. On the other hand, if you consider that the active state and the open state overlap a bit, the value may change but the option will definitely not be highlighted accordingly, once again because we did not define any keyboard interactions over options when the control is in its opened state (we have only defined what should happen when the control is opened, but nothing after that).
We have to think a little further: what about the escape key? Pressing <kbd>Esc</kbd> key closes an open select. Remember, if you want to provide the same functionality as the existing native {{htmlelement('select')}}, it should behave the exact same way as the select for all users, from keyboard to mouse to touch to screen reader, and any other input device.
In our example, the missing specifications are obvious so we will handle them, but it can be a real problem for exotic new controls. When it comes to standardized elements, of which the {{htmlelement('select')}} is one, the specification authors spent an inordinate amount of time specifying all interactions for every use case for every input device. Creating new controls is not that easy, especially if you are creating something that has not been done before, and therefore
nobody has the slightest idea of what the expected behaviors and interactions are. At least select has been done before, so we know how it should behave!
Designing new interactions is generally only an option for very large industry players who have enough reach that an interaction they create can become a standard. For example, Apple introduced the scroll wheel with the iPod in 2001. They had the market share to successfully introduce a completely new way of interacting with a device, something most device companies can't do.
It is best not to invent new user interactions. For any interaction you do add, it is vital to spend time in the design stage; if you define a behavior poorly, or forget to define one, it will be very hard to redefine it once the users have gotten used to it. If you have doubts, ask for the opinions of others, and if you have the budget for it, do not hesitate to [perform user tests](https://en.wikipedia.org/wiki/Usability_testing). This process is called UX Design. If you want to learn more about this topic, you should check out the following helpful resources:
- [UXMatters.com](https://www.uxmatters.com/)
- [UXDesign.com](https://uxdesign.com/)
- [The UX Design section of SmashingMagazine](https://www.smashingmagazine.com/)
> **Note:** Also, in most systems there is a way to open the {{HTMLElement("select")}} element with the keyboard to look at all the available choices (this is the same as clicking the {{HTMLElement("select")}} element with a mouse). This is achieved with <kbd>Alt</kbd> + <kbd>Down</kbd> on Windows. We didn't implement this in our example, but it would be easy to do so, as the mechanism has already been implemented for the `click` event.
## Defining the HTML structure and (some) semantics
Now that the control's basic functionality has been decided upon, it's time to start building it. The first step is to define its HTML structure and give it some basic semantics. Here is what we need to rebuild a {{HTMLElement("select")}} element:
```html
<!-- This is our main container for our control.
The tabindex attribute is what allows the user to focus on the control.
We'll see later that it's better to set it through JavaScript. -->
<div class="select" tabindex="0">
<!-- This container will be used to display the current value of the control -->
<span class="value">Cherry</span>
<!-- This container will contain all the options available for our control.
Because it's a list, it makes sense to use the ul element. -->
<ul class="optList">
<!-- Each option only contains the value to be displayed, we'll see later
how to handle the real value that will be sent with the form data -->
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
```
Note the use of class names; these identify each relevant part regardless of the actual underlying HTML elements used. This is important to make sure that we don't bind our CSS and JavaScript to a strong HTML structure, so that we can make implementation changes later without breaking code that uses the control. For example, what if you wish to implement the equivalent of the {{HTMLElement("optgroup")}} element later on?
Class names, however, provide no semantic value. In this current state, the screen reader user only "sees" an unordered list. We will add ARIA semantics in a bit.
## Creating the look and feel using CSS
Now that we have a structure, we can start designing our control. The whole point of building this custom control is to be able to style it exactly how we want. To that end, we will split our CSS work into two parts: the first part will be the CSS rules absolutely necessary to make our control behave like a {{HTMLElement("select")}} element, and the second part will consist of the fancy styles used to make it look the way we want.
### Required styles
The required styles are those necessary to handle the three states of our control.
```css
.select {
/* This will create a positioning context for the list of options;
adding this to `.select:focus-within` will be a better option when fully supported
*/
position: relative;
/* This will make our control become part of the text flow and sizable at the same time */
display: inline-block;
}
```
We need an extra class `active` to define the look and feel of our control when it is in its active state. Because our control is focusable, we double this custom style with the {{cssxref(":focus")}} pseudo-class in order to be sure they will behave the same.
```css
.select.active,
.select:focus {
outline-color: transparent;
/* This box-shadow property is not exactly required, however it's imperative to ensure
active state is visible, especially to keyboard users, that we use it as a default value. */
box-shadow: 0 0 3px 1px #227755;
}
```
Now, let's handle the list of options:
```css
/* The .select selector here helps to make sure we only select
element inside our control. */
.select .optList {
/* This will make sure our list of options will be displayed below the value
and out of the HTML flow */
position: absolute;
top: 100%;
left: 0;
}
```
We need an extra class to handle when the list of options is hidden. This is necessary in order to manage the differences between the active state and the open state that do not exactly match.
```css
.select .optList.hidden {
/* This is a simple way to hide the list in an accessible way;
we will talk more about accessibility in the end */
max-height: 0;
visibility: hidden;
}
```
> **Note:** We could also have used `transform: scale(1, 0)` to give the option list no height and full width.
### Beautification
So now that we have the basic functionality in place, the fun can start. The following is just an example of what is possible, and will match the screenshot at the beginning of this article. However, you should feel free to experiment and see what you can come up with.
```css
.select {
/* The computations are made assuming 1em equals 16px which is the default value in most browsers.
If you are lost with px to em conversion, try https://nekocalc.com/px-to-em-converter */
font-size: 0.625em; /* this (10px) is the new font size context for em value in this context */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
/* We need extra room for the down arrow we will add */
padding: 0.1em 2.5em 0.2em 0.5em;
width: 10em; /* 100px */
border: 0.2em solid #000;
border-radius: 0.4em;
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%);
/* The first declaration is for browsers that do not support linear gradients. */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
/* Because the value can be wider than our control, we have to make sure it will not
change the control's width. If the content overflows, we display an ellipsis */
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
```
We don't need an extra element to design the down arrow; instead, we're using the {{cssxref("::after")}} pseudo-element. It could also be implemented using a simple background image on the `select` class.
```css
.select::after {
content: "▼"; /* We use the unicode character U+25BC; make sure to set a charset meta tag */
position: absolute;
z-index: 1; /* This will be important to keep the arrow from overlapping the list of options */
top: 0;
right: 0;
box-sizing: border-box;
height: 100%;
width: 2em;
padding-top: 0.1em;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
text-align: center;
}
```
Next, let's style the list of options:
```css
.select .optList {
z-index: 2; /* We explicitly said the list of options will always be on top of the down arrow */
/* this will reset the default style of the ul element */
list-style: none;
margin: 0;
padding: 0;
box-sizing: border-box;
/* If the values are smaller than the control, the list of options
will be as wide as the control itself */
min-width: 100%;
/* In case the list is too long, its content will overflow vertically
(which will add a vertical scrollbar automatically) but never horizontally
(because we haven't set a width, the list will adjust its width automatically.
If it can't, the content will be truncated) */
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
background: #f0f0f0;
}
```
For the options, we need to add a `highlight` class to be able to identify the value the user will pick (or has picked).
```css
.select .option {
padding: 0.2em 0.3em; /* 2px 3px */
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
So here's the result with our three states ([check out the source code here](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls/Example_1)):
#### Basic state
```html hidden
<div class="select">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
```
```css hidden
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
{{EmbedLiveSample("Basic_state",120,130)}}
#### Active state
```html hidden
<div class="select active">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
```
```css hidden
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
{{EmbedLiveSample("Active_state",120,130)}}
#### Open state
```html hidden
<div class="select active">
<span class="value">Cherry</span>
<ul class="optList">
<li class="option highlight">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
```
```css hidden
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #fff;
}
```
{{EmbedLiveSample("Open_state",120,130)}}
## Bringing your control to life with JavaScript
Now that our design and structure are ready, we can write the JavaScript code to make the control actually work.
> **Warning:** The following is educational code, not production code, and should not be used as-is. It is neither future-proof nor will work on legacy browsers. It also has redundant parts that should be optimized in production code.
### Why isn't it working?
Before starting, it's important to remember **JavaScript in the browser is an unreliable technology**. Custom controls rely on JavaScript to tie everything together. However, there are cases in which JavaScript isn't able to run in the browser:
- The user has turned off JavaScript: This is unusual; very few people turn off JavaScript nowadays.
- The script did not load: This is one of the most common cases, especially in the mobile world where the network is not very reliable.
- The script is buggy: You should always consider this possibility.
- The script conflicts with a third-party script: This can happen with tracking scripts or any bookmarklets the user uses.
- The script conflicts with, or is affected by, a browser extension (such as Firefox's [NoScript](https://addons.mozilla.org/fr/firefox/addon/noscript/) extension or Chrome's [ScriptBlock](https://chrome.google.com/webstore/detail/scriptblock/hcdjknjpbnhdoabbngpmfekaecnpajba) extension).
- The user is using a legacy browser, and one of the features you require is not supported: This will happen frequently when you make use of cutting-edge APIs.
- The user is interacting with the content before the JavaScript has been fully downloaded, parsed, and executed.
Because of these risks, it's really important to seriously consider what will happen if your JavaScript doesn't work. We'll discuss options to consider and cover the basics in our example (a full discussion of solving this issue for all scenarios would require a book). Just remember, it is vital to make your script generic and reusable.
In our example, if our JavaScript code isn't running, we'll fall back to displaying a standard {{HTMLElement("select")}} element. We include our control and the {{HTMLElement("select")}}; which one is displayed depends on the class of the body element, with the class of the body element being updated by the script that makes the control function, when it loads successfully.
To achieve this, we need two things:
First, we need to add a regular {{HTMLElement("select")}} element before each instance of our custom control. There is a benefit to having this "extra" select even if our JavaScript works as hoped: we will use this select to send data from our custom control along with the rest of our form data. We will discuss this in greater depth later.
```html
<body>
<form class="no-widget">
<select name="myFruit">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
</form>
</body>
```
Second, we need two new classes to let us hide the unneeded element: we visually hide the custom control if our script isn't running, or the "real" {{HTMLElement("select")}} element if it is running. Note that, by default, our HTML code hides our custom control.
```css
.widget select,
.no-widget .select {
/* This CSS selector basically says:
- either we have set the body class to "widget" and thus we hide the actual <select> element
- or we have not changed the body class, therefore the body class is still "no-widget",
so the elements whose class is "select" must be hidden */
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
```
This CSS visually hides one of the elements, but it is still available to screen readers.
Now we need a JavaScript switch to determine if the script is running or not. This switch is a couple of lines: if at page load time our script is running, it will remove the `no-widget` class and add the `widget` class, thereby swapping the visibility of the {{HTMLElement("select")}} element and the custom control.
```js
window.addEventListener("load", () => {
document.body.classList.remove("no-widget");
document.body.classList.add("widget");
});
```
#### Without JS
Check out the [full source code](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls/Example_2#no_js).
```html hidden
<form class="no-widget">
<select name="myFruit">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
</form>
```
```css hidden
.widget select,
.no-widget .select {
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
```
{{EmbedLiveSample("Without_JS",120,130)}}
#### With JS
Check out the [full source code](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls/Example_2#js).
```html hidden
<form class="no-widget">
<select name="myFruit">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
</form>
```
```css hidden
.widget select,
.no-widget .select {
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
```js hidden
window.addEventListener("load", () => {
const form = document.querySelector("form");
form.classList.remove("no-widget");
form.classList.add("widget");
});
```
{{EmbedLiveSample("With_JS",120,130)}}
> **Note:** If you really want to make your code generic and reusable, instead of doing a class switch it's far better to just add the widget class to hide the {{HTMLElement("select")}} elements, and to dynamically add the DOM tree representing the custom control after every {{HTMLElement("select")}} element in the page.
### Making the job easier
In the code we are about to build, we will use the standard JavaScript and DOM APIs to do all the work we need. The features we plan to use are the following:
1. {{domxref("element.classList","classList")}}
2. {{domxref("EventTarget.addEventListener","addEventListener()")}}
3. {{domxref("NodeList.forEach()")}}
4. {{domxref("element.querySelector","querySelector()")}} and {{domxref("element.querySelectorAll","querySelectorAll()")}}
### Building event callbacks
The groundwork is done. We can now start to define all the functions that will be used each time the user interacts with our control.
```js
// This function will be used each time we want to deactivate a custom control
// It takes one parameter
// select : the DOM node with the `select` class to deactivate
function deactivateSelect(select) {
// If the control is not active there is nothing to do
if (!select.classList.contains("active")) return;
// We need to get the list of options for the custom control
const optList = select.querySelector(".optList");
// We close the list of option
optList.classList.add("hidden");
// and we deactivate the custom control itself
select.classList.remove("active");
}
// This function will be used each time the user wants to activate the control
// (which, in turn, will deactivate other select controls)
// It takes two parameters:
// select : the DOM node with the `select` class to activate
// selectList : the list of all the DOM nodes with the `select` class
function activeSelect(select, selectList) {
// If the control is already active there is nothing to do
if (select.classList.contains("active")) return;
// We have to turn off the active state on all custom controls
// Because the deactivateSelect function fulfills all the requirements of the
// forEach callback function, we use it directly without using an intermediate
// anonymous function.
selectList.forEach(deactivateSelect);
// And we turn on the active state for this specific control
select.classList.add("active");
}
// This function will be used each time the user wants to open/closed the list of options
// It takes one parameter:
// select : the DOM node with the list to toggle
function toggleOptList(select) {
// The list is kept from the control
const optList = select.querySelector(".optList");
// We change the class of the list to show/hide it
optList.classList.toggle("hidden");
}
// This function will be used each time we need to highlight an option
// It takes two parameters:
// select : the DOM node with the `select` class containing the option to highlight
// option : the DOM node with the `option` class to highlight
function highlightOption(select, option) {
// We get the list of all option available for our custom select element
const optionList = select.querySelectorAll(".option");
// We remove the highlight from all options
optionList.forEach((other) => {
other.classList.remove("highlight");
});
// We highlight the right option
option.classList.add("highlight");
}
```
You need these to handle the various states of custom control.
Next, we bind these functions to the appropriate events:
```js
// We handle the event binding when the document is loaded.
window.addEventListener("load", () => {
const selectList = document.querySelectorAll(".select");
// Each custom control needs to be initialized
selectList.forEach((select) => {
// as well as all its `option` elements
const optionList = select.querySelectorAll(".option");
// Each time a user hovers their mouse over an option, we highlight the given option
optionList.forEach((option) => {
option.addEventListener("mouseover", () => {
// Note: the `select` and `option` variable are closures
// available in the scope of our function call.
highlightOption(select, option);
});
});
// Each times the user clicks on or taps a custom select element
select.addEventListener("click", (event) => {
// Note: the `select` variable is a closure
// available in the scope of our function call.
// We toggle the visibility of the list of options
toggleOptList(select);
});
// In case the control gains focus
// The control gains the focus each time the user clicks on it or each time
// they use the tabulation key to access the control
select.addEventListener("focus", (event) => {
// Note: the `select` and `selectList` variable are closures
// available in the scope of our function call.
// We activate the control
activeSelect(select, selectList);
});
// In case the control loses focus
select.addEventListener("blur", (event) => {
// Note: the `select` variable is a closure
// available in the scope of our function call.
// We deactivate the control
deactivateSelect(select);
});
// Loose focus if the user hits `esc`
select.addEventListener("keyup", (event) => {
// deactivate on keyup of `esc`
if (event.key === "Escape") {
deactivateSelect(select);
}
});
});
});
```
At that point, our control will change state according to our design, but its value doesn't get updated yet. We'll handle that next.
#### Live example
Check out the [full source code](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls/Example_3).
```html hidden
<form class="no-widget">
<select name="myFruit" tabindex="-1">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select" tabindex="0">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
</form>
```
```css hidden
.widget select,
.no-widget .select {
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
```js hidden
function deactivateSelect(select) {
if (!select.classList.contains("active")) return;
const optList = select.querySelector(".optList");
optList.classList.add("hidden");
select.classList.remove("active");
}
function activeSelect(select, selectList) {
if (select.classList.contains("active")) return;
selectList.forEach(deactivateSelect);
select.classList.add("active");
}
function toggleOptList(select, show) {
const optList = select.querySelector(".optList");
optList.classList.toggle("hidden");
}
function highlightOption(select, option) {
const optionList = select.querySelectorAll(".option");
optionList.forEach((other) => {
other.classList.remove("highlight");
});
option.classList.add("highlight");
}
window.addEventListener("load", () => {
const form = document.querySelector("form");
form.classList.remove("no-widget");
form.classList.add("widget");
});
window.addEventListener("load", () => {
const selectList = document.querySelectorAll(".select");
selectList.forEach((select) => {
const optionList = select.querySelectorAll(".option");
optionList.forEach((option) => {
option.addEventListener("mouseover", () => {
highlightOption(select, option);
});
});
select.addEventListener(
"click",
(event) => {
toggleOptList(select);
},
false,
);
select.addEventListener("focus", (event) => {
activeSelect(select, selectList);
});
select.addEventListener("blur", (event) => {
deactivateSelect(select);
});
select.addEventListener("keyup", (event) => {
if (event.key === "Escape") {
deactivateSelect(select);
}
});
});
});
```
{{EmbedLiveSample("Live_example",120,130)}}
### Handling the control's value
Now that our control is working, we have to add code to update its value according to user input and make it possible to send the value along with form data.
The easiest way to do this is to use a native control under the hood. Such a control will keep track of the value with all the built-in controls provided by the browser, and the value will be sent as usual when a form is submitted. There's no point in reinventing the wheel when we can have all this done for us.
As seen previously, we already use a native select control as a fallback for accessibility reasons; we can synchronize its value with that of our custom control:
```js
// This function updates the displayed value and synchronizes it with the native control.
// It takes two parameters:
// select : the DOM node with the class `select` containing the value to update
// index : the index of the value to be selected
function updateValue(select, index) {
// We need to get the native control for the given custom control
// In our example, that native control is a sibling of the custom control
const nativeWidget = select.previousElementSibling;
// We also need to get the value placeholder of our custom control
const value = select.querySelector(".value");
// And we need the whole list of options
const optionList = select.querySelectorAll(".option");
// We set the selected index to the index of our choice
nativeWidget.selectedIndex = index;
// We update the value placeholder accordingly
value.innerHTML = optionList[index].innerHTML;
// And we highlight the corresponding option of our custom control
highlightOption(select, optionList[index]);
}
// This function returns the current selected index in the native control
// It takes one parameter:
// select : the DOM node with the class `select` related to the native control
function getIndex(select) {
// We need to access the native control for the given custom control
// In our example, that native control is a sibling of the custom control
const nativeWidget = select.previousElementSibling;
return nativeWidget.selectedIndex;
}
```
With these two functions, we can bind the native controls to the custom ones:
```js
// We handle event binding when the document is loaded.
window.addEventListener("load", () => {
const selectList = document.querySelectorAll(".select");
// Each custom control needs to be initialized
selectList.forEach((select) => {
const optionList = select.querySelectorAll(".option");
const selectedIndex = getIndex(select);
// We make our custom control focusable
select.tabIndex = 0;
// We make the native control no longer focusable
select.previousElementSibling.tabIndex = -1;
// We make sure that the default selected value is correctly displayed
updateValue(select, selectedIndex);
// Each time a user clicks on an option, we update the value accordingly
optionList.forEach((option, index) => {
option.addEventListener("click", (event) => {
updateValue(select, index);
});
});
// Each time a user uses their keyboard on a focused control, we update the value accordingly
select.addEventListener("keyup", (event) => {
let index = getIndex(select);
// When the user hits the Escape key, deactivate the custom control
if (event.key === "Escape") {
deactivateSelect(select);
}
// When the user hits the down arrow, we jump to the next option
if (event.key === "ArrowDown" && index < optionList.length - 1) {
index++;
}
// When the user hits the up arrow, we jump to the previous option
if (event.key === "ArrowUp" && index > 0) {
index--;
}
updateValue(select, index);
});
});
});
```
In the code above, it's worth noting the use of the [`tabIndex`](/en-US/docs/Web/API/HTMLElement/tabIndex) property. Using this property is necessary to ensure that the native control will never gain focus, and to make sure that our custom control gains focus when the user uses their keyboard or mouse.
With that, we're done!
#### Live example
Check out the [source code here](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls/Example_4).
```html hidden
<form class="no-widget">
<select name="myFruit">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
</form>
```
```css hidden
.widget select,
.no-widget .select {
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
```js hidden
function deactivateSelect(select) {
if (!select.classList.contains("active")) return;
const optList = select.querySelector(".optList");
optList.classList.add("hidden");
select.classList.remove("active");
}
function activeSelect(select, selectList) {
if (select.classList.contains("active")) return;
selectList.forEach(deactivateSelect);
select.classList.add("active");
}
function toggleOptList(select, show) {
const optList = select.querySelector(".optList");
optList.classList.toggle("hidden");
}
function highlightOption(select, option) {
const optionList = select.querySelectorAll(".option");
optionList.forEach((other) => {
other.classList.remove("highlight");
});
option.classList.add("highlight");
}
function updateValue(select, index) {
const nativeWidget = select.previousElementSibling;
const value = select.querySelector(".value");
const optionList = select.querySelectorAll(".option");
nativeWidget.selectedIndex = index;
value.innerHTML = optionList[index].innerHTML;
highlightOption(select, optionList[index]);
}
function getIndex(select) {
const nativeWidget = select.previousElementSibling;
return nativeWidget.selectedIndex;
}
window.addEventListener("load", () => {
const form = document.querySelector("form");
form.classList.remove("no-widget");
form.classList.add("widget");
});
window.addEventListener("load", () => {
const selectList = document.querySelectorAll(".select");
selectList.forEach((select) => {
const optionList = select.querySelectorAll(".option");
optionList.forEach((option) => {
option.addEventListener("mouseover", () => {
highlightOption(select, option);
});
});
select.addEventListener("click", (event) => {
toggleOptList(select);
});
select.addEventListener("focus", (event) => {
activeSelect(select, selectList);
});
select.addEventListener("blur", (event) => {
deactivateSelect(select);
});
});
});
window.addEventListener("load", () => {
const selectList = document.querySelectorAll(".select");
selectList.forEach((select) => {
const optionList = select.querySelectorAll(".option");
const selectedIndex = getIndex(select);
select.tabIndex = 0;
select.previousElementSibling.tabIndex = -1;
updateValue(select, selectedIndex);
optionList.forEach((option, index) => {
option.addEventListener("click", (event) => {
updateValue(select, index);
});
});
select.addEventListener("keyup", (event) => {
let index = getIndex(select);
if (event.key === "Escape") {
deactivateSelect(select);
}
if (event.key === "ArrowDown" && index < optionList.length - 1) {
index++;
}
if (event.key === "ArrowUp" && index > 0) {
index--;
}
updateValue(select, index);
});
});
});
```
{{EmbedLiveSample("live_example_2",120,130)}}
But wait a second, are we really done?
## Making it accessible
We have built something that works and though we're far from a fully-featured select box, it works nicely. But what we've done is nothing more than fiddle with the DOM. It has no real semantics, and even though it looks like a select box, from the browser's point of view it isn't one, so assistive technologies won't be able to understand it's a select box. In short, this pretty new select box isn't accessible!
Fortunately, there is a solution and it's called [ARIA](/en-US/docs/Web/Accessibility/ARIA). ARIA stands for "Accessible Rich Internet Application", and it's [a W3C specification](https://www.w3.org/TR/wai-aria/) specifically designed for what we are doing here: making web applications and custom controls accessible. It's basically a set of attributes that extend HTML so that we can better describe roles, states, and properties as though the element we've just devised was the native element it tries to pass for. Using these attributes can be done by editing the HTML markup. We also update the ARIA attributes via JavaScript as the user updates their selected value.
### The `role` attribute
The key attribute used by [ARIA](/en-US/docs/Web/Accessibility/ARIA) is the [`role`](/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques) attribute. The [`role`](/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques) attribute accepts a value that defines what an element is used for. Each role defines its own requirements and behaviors. In our example, we will use the [`listbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role) role. It's a "composite role", which means elements with that role expect to have children, each with a specific role (in this case, at least one child with the `option` role).
It's also worth noting that ARIA defines roles that are applied by default to standard HTML markup. For example, the {{HTMLElement("table")}} element matches the role `grid`, and the {{HTMLElement("ul")}} element matches the role `list`. Because we use a {{HTMLElement("ul")}} element, we want to make sure the `listbox` role of our control will supersede the `list` role of the {{HTMLElement("ul")}} element. To that end, we will use the role `presentation`. This role is designed to let us indicate that an element has no special meaning, and is used solely to present information. We will apply it to our {{HTMLElement("ul")}} element.
To support the [`listbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role) role, we just have to update our HTML like this:
```html
<!-- We add the role="listbox" attribute to our top element -->
<div class="select" role="listbox">
<span class="value">Cherry</span>
<!-- We also add the role="presentation" to the ul element -->
<ul class="optList" role="presentation">
<!-- And we add the role="option" attribute to all the li elements -->
<li role="option" class="option">Cherry</li>
<li role="option" class="option">Lemon</li>
<li role="option" class="option">Banana</li>
<li role="option" class="option">Strawberry</li>
<li role="option" class="option">Apple</li>
</ul>
</div>
```
> **Note:** Including both the `role` attribute and a `class` attribute is not necessary. Instead of using `.option` use the `[role="option"]` [attribute selectors](/en-US/docs/Web/CSS/Attribute_selectors) in your CSS.
### The `aria-selected` attribute
Using the [`role`](/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques) attribute is not enough. [ARIA](/en-US/docs/Web/Accessibility/ARIA) also provides many states and property attributes. The more and better you use them, the better your control will be understood by assistive technologies. In our case, we will limit our usage to one attribute: `aria-selected`.
The `aria-selected` attribute is used to mark which option is currently selected; this lets assistive technologies inform the user what the current selection is. We will use it dynamically with JavaScript to mark the selected option each time the user chooses one. To that end, we need to revise our `updateValue()` function:
```js
function updateValue(select, index) {
const nativeWidget = select.previousElementSibling;
const value = select.querySelector(".value");
const optionList = select.querySelectorAll('[role="option"]');
// We make sure that all the options are not selected
optionList.forEach((other) => {
other.setAttribute("aria-selected", "false");
});
// We make sure the chosen option is selected
optionList[index].setAttribute("aria-selected", "true");
nativeWidget.selectedIndex = index;
value.innerHTML = optionList[index].innerHTML;
highlightOption(select, optionList[index]);
}
```
It might have seemed simpler to let a screen reader focus on the off-screen select and ignore our stylized one, but this is not an accessible solution. Screen readers are not limited to blind people; people with low vision and even perfect vision use them as well. For this reason, you can not have the screen reader focus on an off-screen element.
Below is the final result of all these changes (you'll get a better feel for this by trying it with an assistive technology such as [NVDA](https://www.nvaccess.org/) or [VoiceOver](https://www.apple.com/accessibility/vision/)).
#### Live example
Check out the [full source code here](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls/Example_5).
```html hidden
<form class="no-widget">
<select name="myFruit">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select" role="listbox">
<span class="value">Cherry</span>
<ul class="optList hidden" role="presentation">
<li class="option" role="option" aria-selected="true">Cherry</li>
<li class="option" role="option">Lemon</li>
<li class="option" role="option">Banana</li>
<li class="option" role="option">Strawberry</li>
<li class="option" role="option">Apple</li>
</ul>
</div>
</form>
```
```css hidden
.widget select,
.no-widget .select {
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
```js hidden
function deactivateSelect(select) {
if (!select.classList.contains("active")) return;
const optList = select.querySelector(".optList");
optList.classList.add("hidden");
select.classList.remove("active");
}
function activeSelect(select, selectList) {
if (select.classList.contains("active")) return;
selectList.forEach(deactivateSelect);
select.classList.add("active");
}
function toggleOptList(select, show) {
const optList = select.querySelector(".optList");
optList.classList.toggle("hidden");
}
function highlightOption(select, option) {
const optionList = select.querySelectorAll(".option");
optionList.forEach((other) => {
other.classList.remove("highlight");
});
option.classList.add("highlight");
}
function updateValue(select, index) {
const nativeWidget = select.previousElementSibling;
const value = select.querySelector(".value");
const optionList = select.querySelectorAll(".option");
optionList.forEach((other) => {
other.setAttribute("aria-selected", "false");
});
optionList[index].setAttribute("aria-selected", "true");
nativeWidget.selectedIndex = index;
value.innerHTML = optionList[index].innerHTML;
highlightOption(select, optionList[index]);
}
function getIndex(select) {
const nativeWidget = select.previousElementSibling;
return nativeWidget.selectedIndex;
}
window.addEventListener("load", () => {
const form = document.querySelector("form");
form.classList.remove("no-widget");
form.classList.add("widget");
});
window.addEventListener("load", () => {
const selectList = document.querySelectorAll(".select");
selectList.forEach((select) => {
const optionList = select.querySelectorAll(".option");
const selectedIndex = getIndex(select);
select.tabIndex = 0;
select.previousElementSibling.tabIndex = -1;
updateValue(select, selectedIndex);
optionList.forEach((option, index) => {
option.addEventListener("mouseover", () => {
highlightOption(select, option);
});
option.addEventListener("click", (event) => {
updateValue(select, index);
});
});
select.addEventListener("click", (event) => {
toggleOptList(select);
});
select.addEventListener("focus", (event) => {
activeSelect(select, selectList);
});
select.addEventListener("blur", (event) => {
deactivateSelect(select);
});
select.addEventListener("keyup", (event) => {
let index = getIndex(select);
if (event.key === "Escape") {
deactivateSelect(select);
}
if (event.key === "ArrowDown" && index < optionList.length - 1) {
index++;
}
if (event.key === "ArrowUp" && index > 0) {
index--;
}
updateValue(select, index);
});
});
});
```
{{EmbedLiveSample("live_example_3",120,130)}}
If you want to move forward, the code in this example needs some improvement before it becomes generic and reusable. This is an exercise you can try to perform. Two hints to help you in this: the first argument for all our functions is the same, which means those functions need the same context. Building an object to share that context would be wise.
## An alternative approach: Using radio buttons
In the above example, we reinvented a {{htmlelement('select')}} element using non-semantic HTML, CSS, and JavaScript. This select was selecting one option from a limited number of options, which is the same functionality of a same-named group of {{htmlelement('input/radio', 'radio')}} buttons.
We could therefore reinvent this using radio buttons instead; let's look at this option.
We can start with a completely semantic, accessible, unordered list of {{htmlelement('input/radio','radio')}} buttons with an associated {{htmlelement('label')}}, labeling the entire group with a semantically appropriate {{htmlelement('fieldset')}} and {{htmlelement('legend')}} pair.
```html
<fieldset>
<legend>Pick a fruit</legend>
<ul class="styledSelect">
<li>
<input
type="radio"
name="fruit"
value="Cherry"
id="fruitCherry"
checked />
<label for="fruitCherry">Cherry</label>
</li>
<li>
<input type="radio" name="fruit" value="Lemon" id="fruitLemon" />
<label for="fruitLemon">Lemon</label>
</li>
<li>
<input type="radio" name="fruit" value="Banana" id="fruitBanana" />
<label for="fruitBanana">Banana</label>
</li>
<li>
<input
type="radio"
name="fruit"
value="Strawberry"
id="fruitStrawberry" />
<label for="fruitStrawberry">Strawberry</label>
</li>
<li>
<input type="radio" name="fruit" value="Apple" id="fruitApple" />
<label for="fruitApple">Apple</label>
</li>
</ul>
</fieldset>
```
We'll do a little styling of the radio button list (not the legend/fieldset) to make it look somewhat like the earlier example, just to show that it can be done:
```css
.styledSelect {
display: inline-block;
padding: 0;
}
.styledSelect li {
list-style-type: none;
padding: 0;
display: flex;
}
.styledSelect [type="radio"] {
position: absolute;
left: -100vw;
top: -100vh;
}
.styledSelect label {
margin: 0;
line-height: 2;
padding: 0 0 0 4px;
}
.styledSelect:not(:focus-within) input:not(:checked) + label {
height: 0;
outline-color: transparent;
overflow: hidden;
}
.styledSelect:not(:focus-within) input:checked + label {
border: 0.2em solid #000;
border-radius: 0.4em;
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%);
}
.styledSelect:not(:focus-within) input:checked + label::after {
content: "▼";
background: black;
float: right;
color: white;
padding: 0 4px;
margin: 0 -4px 0 4px;
}
.styledSelect:focus-within {
border: 0.2em solid #000;
border-radius: 0.4em;
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%);
}
.styledSelect:focus-within input:checked + label {
background-color: #333;
color: #fff;
width: 100%;
}
```
With no JavaScript, and just a little bit of CSS, we can style the list of radio buttons to display only the checked item. When the focus is within the `<ul>` in the `<fieldset>`, the list opens up, and the up and down (and left and right) arrows work to select the previous and next items. Try it out:
{{EmbedLiveSample("An_alternative_approach_Using_radio_buttons",200,240)}}
This works, to some extent, without JavaScript. We've created a similar control to our custom control, that works even if the JavaScript fails. Looks like a great solution, right? Well, not 100%. It does work with the keyboard, but not as expected with a mouse click. It likely makes more sense to use web standards as the basis for custom controls instead of relying on frameworks to create elements with no native semantics. However, our control doesn't have the same functionality that a `<select>` has natively.
On the plus side, this control is fully accessible to a screen reader and fully navigable via the keyboard. However, this control isn't a {{htmlelement('select')}} replacement. There is functionality that differs and/or is missing. For example, all four arrows navigate through the options, but clicking the down arrow when the user is on the last button takes them to the first button; it doesn't stop at the top and bottom of the option list like a `<select>` does.
We'll leave adding this missing functionality as a reader exercise.
## Conclusion
We have seen all the basics of building a custom form control, but as you can see it's not trivial to do. Before creating your own customized control, consider whether HTML provides alternative elements that can be used to adequately support your requirements. If you do need to create a custom control, it is often easier to rely on third-party libraries instead of building your own. But, if you do create your own, modify existing elements, or use a framework to implement a pre-baked control, remember that creating a usable and accessible form control is more complicated than it looks.
Here are a few libraries you should consider before coding your own:
- [jQuery UI](https://jqueryui.com/)
- [AXE accessible custom select dropdowns](https://www.webaxe.org/accessible-custom-select-dropdowns/)
- [msDropDown](https://github.com/marghoobsuleman/ms-Dropdown)
If you do create alternative controls via radio buttons, your own JavaScript, or with a 3rd party library, ensure it is accessible and feature-proof; that is, it needs to be able to work better with a variety of browsers whose compatibility with the Web standards they use vary. Have fun!
## See also
### Learning path
- [Your first HTML form](/en-US/docs/Learn/Forms/Your_first_form)
- [How to structure an HTML form](/en-US/docs/Learn/Forms/How_to_structure_a_web_form)
- [The native form controls](/en-US/docs/Learn/Forms/Basic_native_form_controls)
- [HTML5 input types](/en-US/docs/Learn/Forms/HTML5_input_types)
- [Additional form controls](/en-US/docs/Learn/Forms/Other_form_controls)
- [UI pseudo-classes](/en-US/docs/Learn/Forms/UI_pseudo-classes)
- [Styling HTML forms](/en-US/docs/Learn/Forms/Styling_web_forms)
- [Form data validation](/en-US/docs/Learn/Forms/Form_validation)
- [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data)
### Advanced Topics
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- **How to build custom form controls**
- [HTML forms in legacy browsers](/en-US/docs/Learn/Forms/HTML_forms_in_legacy_browsers)
- [Advanced styling for HTML forms](/en-US/docs/Learn/Forms/Advanced_form_styling)
- [Property compatibility table for form controls](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls | data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls/example_3/index.md | ---
title: Example 3
slug: Learn/Forms/How_to_build_custom_form_controls/Example_3
page-type: learn-module-chapter
---
This is the third example that explain [how to build custom form widgets](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls).
## Change states
### HTML
```html
<form class="no-widget">
<select name="myFruit" tabindex="-1">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select" tabindex="0">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
</form>
```
### CSS
```css
.widget select,
.no-widget .select {
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
/* --------------- */
/* Required Styles */
/* --------------- */
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
/* ------------ */
/* Fancy Styles */
/* ------------ */
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
### JavaScript
```js
// -------------------- //
// Function definitions //
// -------------------- //
function deactivateSelect(select) {
if (!select.classList.contains("active")) return;
const optList = select.querySelector(".optList");
optList.classList.add("hidden");
select.classList.remove("active");
}
function activeSelect(select, selectList) {
if (select.classList.contains("active")) return;
selectList.forEach(deactivateSelect);
select.classList.add("active");
}
function toggleOptList(select, show) {
const optList = select.querySelector(".optList");
optList.classList.toggle("hidden");
}
function highlightOption(select, option) {
const optionList = select.querySelectorAll(".option");
optionList.forEach((other) => {
other.classList.remove("highlight");
});
option.classList.add("highlight");
}
// ------------- //
// Event binding //
// ------------- //
window.addEventListener("load", () => {
const form = document.querySelector("form");
form.classList.remove("no-widget");
form.classList.add("widget");
});
window.addEventListener("load", () => {
const selectList = document.querySelectorAll(".select");
selectList.forEach((select) => {
const optionList = select.querySelectorAll(".option");
optionList.forEach((option) => {
option.addEventListener("mouseover", () => {
highlightOption(select, option);
});
});
select.addEventListener(
"click",
(event) => {
toggleOptList(select);
},
false,
);
select.addEventListener("focus", (event) => {
activeSelect(select, selectList);
});
select.addEventListener("blur", (event) => {
deactivateSelect(select);
});
select.addEventListener("keyup", (event) => {
if (event.key === "Escape") {
deactivateSelect(select);
}
});
});
});
```
### Result
{{ EmbedLiveSample('Change_states') }}
| 0 |
data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls | data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls/example_4/index.md | ---
title: Example 4
slug: Learn/Forms/How_to_build_custom_form_controls/Example_4
page-type: learn-module-chapter
---
This is the fourth example that explain [how to build custom form widgets](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls).
## Change states
### HTML
```html
<form class="no-widget">
<select name="myFruit">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
</form>
```
### CSS
```css
.widget select,
.no-widget .select {
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
/* --------------- */
/* Required Styles */
/* --------------- */
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
/* ------------ */
/* Fancy Styles */
/* ------------ */
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
### JavaScript
```js
// -------------------- //
// Function definitions //
// -------------------- //
function deactivateSelect(select) {
if (!select.classList.contains("active")) return;
const optList = select.querySelector(".optList");
optList.classList.add("hidden");
select.classList.remove("active");
}
function activeSelect(select, selectList) {
if (select.classList.contains("active")) return;
selectList.forEach(deactivateSelect);
select.classList.add("active");
}
function toggleOptList(select, show) {
const optList = select.querySelector(".optList");
optList.classList.toggle("hidden");
}
function highlightOption(select, option) {
const optionList = select.querySelectorAll(".option");
optionList.forEach((other) => {
other.classList.remove("highlight");
});
option.classList.add("highlight");
}
function updateValue(select, index) {
const nativeWidget = select.previousElementSibling;
const value = select.querySelector(".value");
const optionList = select.querySelectorAll(".option");
nativeWidget.selectedIndex = index;
value.innerHTML = optionList[index].innerHTML;
highlightOption(select, optionList[index]);
}
function getIndex(select) {
const nativeWidget = select.previousElementSibling;
return nativeWidget.selectedIndex;
}
// ------------- //
// Event binding //
// ------------- //
window.addEventListener("load", () => {
const form = document.querySelector("form");
form.classList.remove("no-widget");
form.classList.add("widget");
});
window.addEventListener("load", () => {
const selectList = document.querySelectorAll(".select");
selectList.forEach((select) => {
const optionList = select.querySelectorAll(".option");
optionList.forEach((option) => {
option.addEventListener("mouseover", () => {
highlightOption(select, option);
});
});
select.addEventListener("click", (event) => {
toggleOptList(select);
});
select.addEventListener("focus", (event) => {
activeSelect(select, selectList);
});
select.addEventListener("blur", (event) => {
deactivateSelect(select);
});
});
});
window.addEventListener("load", () => {
const selectList = document.querySelectorAll(".select");
selectList.forEach((select) => {
const optionList = select.querySelectorAll(".option");
const selectedIndex = getIndex(select);
select.tabIndex = 0;
select.previousElementSibling.tabIndex = -1;
updateValue(select, selectedIndex);
optionList.forEach((option, index) => {
option.addEventListener("click", (event) => {
updateValue(select, index);
});
});
select.addEventListener("keyup", (event) => {
let index = getIndex(select);
if (event.key === "Escape") {
deactivateSelect(select);
}
if (event.key === "ArrowDown" && index < optionList.length - 1) {
index++;
}
if (event.key === "ArrowUp" && index > 0) {
index--;
}
updateValue(select, index);
});
});
});
```
### Result
{{ EmbedLiveSample('Change_states') }}
| 0 |
data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls | data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls/example_2/index.md | ---
title: Example 2
slug: Learn/Forms/How_to_build_custom_form_controls/Example_2
page-type: learn-module-chapter
---
This is the second example that explain [how to build custom form widgets](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls).
## JS
### HTML
```html
<form class="no-widget">
<select name="myFruit">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
</form>
```
### CSS
```css
.widget select,
.no-widget .select {
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
/* --------------- */
/* Required Styles */
/* --------------- */
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline: none;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
/* ------------ */
/* Fancy Styles */
/* ------------ */
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
### JavaScript
```js
window.addEventListener("load", () => {
const form = document.querySelector("form");
form.classList.remove("no-widget");
form.classList.add("widget");
});
```
### Result
{{ EmbedLiveSample('JS', 120, 130) }}
## No JS
### HTML
```html
<form class="no-widget">
<select name="myFruit">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
</form>
```
### CSS
```css
.widget select,
.no-widget .select {
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
```
### Result
{{ EmbedLiveSample('No_JS', 120, 130) }}
| 0 |
data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls | data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls/example_5/index.md | ---
title: Example 5
slug: Learn/Forms/How_to_build_custom_form_controls/Example_5
page-type: learn-module-chapter
---
This is the last example that explain [how to build custom form widgets](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls).
## Change states
### HTML
```html
<form class="no-widget">
<select name="myFruit">
<option>Cherry</option>
<option>Lemon</option>
<option>Banana</option>
<option>Strawberry</option>
<option>Apple</option>
</select>
<div class="select" role="listbox">
<span class="value">Cherry</span>
<ul class="optList hidden" role="presentation">
<li class="option" role="option" aria-selected="true">Cherry</li>
<li class="option" role="option">Lemon</li>
<li class="option" role="option">Banana</li>
<li class="option" role="option">Strawberry</li>
<li class="option" role="option">Apple</li>
</ul>
</div>
</form>
```
### CSS
```css
.widget select,
.no-widget .select {
position: absolute;
left: -5000em;
height: 0;
overflow: hidden;
}
/* --------------- */
/* Required Styles */
/* --------------- */
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
/* ------------ */
/* Fancy Styles */
/* ------------ */
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
### JavaScript
```js
// -------------------- //
// Function definitions //
// -------------------- //
function deactivateSelect(select) {
if (!select.classList.contains("active")) return;
const optList = select.querySelector(".optList");
optList.classList.add("hidden");
select.classList.remove("active");
}
function activeSelect(select, selectList) {
if (select.classList.contains("active")) return;
selectList.forEach(deactivateSelect);
select.classList.add("active");
}
function toggleOptList(select, show) {
const optList = select.querySelector(".optList");
optList.classList.toggle("hidden");
}
function highlightOption(select, option) {
const optionList = select.querySelectorAll(".option");
optionList.forEach((other) => {
other.classList.remove("highlight");
});
option.classList.add("highlight");
}
function updateValue(select, index) {
const nativeWidget = select.previousElementSibling;
const value = select.querySelector(".value");
const optionList = select.querySelectorAll(".option");
optionList.forEach((other) => {
other.setAttribute("aria-selected", "false");
});
optionList[index].setAttribute("aria-selected", "true");
nativeWidget.selectedIndex = index;
value.innerHTML = optionList[index].innerHTML;
highlightOption(select, optionList[index]);
}
function getIndex(select) {
const nativeWidget = select.previousElementSibling;
return nativeWidget.selectedIndex;
}
// ------------- //
// Event binding //
// ------------- //
window.addEventListener("load", () => {
const form = document.querySelector("form");
form.classList.remove("no-widget");
form.classList.add("widget");
});
window.addEventListener("load", () => {
const selectList = document.querySelectorAll(".select");
selectList.forEach((select) => {
const optionList = select.querySelectorAll(".option");
const selectedIndex = getIndex(select);
select.tabIndex = 0;
select.previousElementSibling.tabIndex = -1;
updateValue(select, selectedIndex);
optionList.forEach((option, index) => {
option.addEventListener("mouseover", () => {
highlightOption(select, option);
});
option.addEventListener("click", (event) => {
updateValue(select, index);
});
});
select.addEventListener("click", (event) => {
toggleOptList(select);
});
select.addEventListener("focus", (event) => {
activeSelect(select, selectList);
});
select.addEventListener("blur", (event) => {
deactivateSelect(select);
});
select.addEventListener("keyup", (event) => {
let index = getIndex(select);
if (event.key === "Escape") {
deactivateSelect(select);
}
if (event.key === "ArrowDown" && index < optionList.length - 1) {
index++;
}
if (event.key === "ArrowUp" && index > 0) {
index--;
}
updateValue(select, index);
});
});
});
```
### Result
{{ EmbedLiveSample('Change_states') }}
| 0 |
data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls | data/mdn-content/files/en-us/learn/forms/how_to_build_custom_form_controls/example_1/index.md | ---
title: Example 1
slug: Learn/Forms/How_to_build_custom_form_controls/Example_1
page-type: learn-module-chapter
---
This is the first example of code that explains [how to build a custom form widget](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls).
## Basic state
### HTML
```html
<div class="select">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
```
### CSS
```css
/* --------------- */
/* Required Styles */
/* --------------- */
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
/* ------------ */
/* Fancy Styles */
/* ------------ */
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
### Result for basic state
{{ EmbedLiveSample('Basic_state', 120, 130) }}
## Active state
### HTML
```html
<div class="select active">
<span class="value">Cherry</span>
<ul class="optList hidden">
<li class="option">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
```
### CSS
```css
/* --------------- */
/* Required Styles */
/* --------------- */
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
/* ------------ */
/* Fancy Styles */
/* ------------ */
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #ffffff;
}
```
### Result for active state
{{ EmbedLiveSample('Active_state', 120, 130) }}
## Open state
### HTML
```html
<div class="select active">
<span class="value">Cherry</span>
<ul class="optList">
<li class="option highlight">Cherry</li>
<li class="option">Lemon</li>
<li class="option">Banana</li>
<li class="option">Strawberry</li>
<li class="option">Apple</li>
</ul>
</div>
```
### CSS
```css
/* --------------- */
/* Required Styles */
/* --------------- */
.select {
position: relative;
display: inline-block;
}
.select.active,
.select:focus {
box-shadow: 0 0 3px 1px #227755;
outline-color: transparent;
}
.select .optList {
position: absolute;
top: 100%;
left: 0;
}
.select .optList.hidden {
max-height: 0;
visibility: hidden;
}
/* ------------ */
/* Fancy Styles */
/* ------------ */
.select {
font-size: 0.625em; /* 10px */
font-family: Verdana, Arial, sans-serif;
box-sizing: border-box;
padding: 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */
width: 10em; /* 100px */
border: 0.2em solid #000; /* 2px */
border-radius: 0.4em; /* 4px */
box-shadow: 0 0.1em 0.2em rgb(0 0 0 / 45%); /* 0 1px 2px */
background: #f0f0f0;
background: linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0);
}
.select .value {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.select::after {
content: "▼";
position: absolute;
z-index: 1;
height: 100%;
width: 2em; /* 20px */
top: 0;
right: 0;
padding-top: 0.1em;
box-sizing: border-box;
text-align: center;
border-left: 0.2em solid #000;
border-radius: 0 0.1em 0.1em 0;
background-color: #000;
color: #fff;
}
.select .optList {
z-index: 2;
list-style: none;
margin: 0;
padding: 0;
background: #f0f0f0;
border: 0.2em solid #000;
border-top-width: 0.1em;
border-radius: 0 0 0.4em 0.4em;
box-shadow: 0 0.2em 0.4em rgb(0 0 0 / 40%);
box-sizing: border-box;
min-width: 100%;
max-height: 10em; /* 100px */
overflow-y: auto;
overflow-x: hidden;
}
.select .option {
padding: 0.2em 0.3em;
}
.select .highlight {
background: #000;
color: #fff;
}
```
### Result for open state
{{ EmbedLiveSample('Open_state', 120, 130) }}
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/test_your_skills_colon__other_controls/index.md | ---
title: "Test your skills: Other controls"
slug: Learn/Forms/Test_your_skills:_Other_controls
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Other form controls](/en-US/docs/Learn/Forms/Other_form_controls) article.
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Other controls 1
In our first "other controls" assessment, we'll get you to create a multi-line text input.
1. Create a basic multi-line text input.
2. Associate it semantically with the provided "Comment" label.
3. Give the input 35 columns, and 10 rows of space in which to add comments.
4. Give the comments a maximum length of 100 characters.
To create the input, update the HTML code in the editor below:
{{EmbedGHLiveSample("learning-area/html/forms/tasks/other-controls/other-controls1.html", '100%', 500)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/other-controls/other-controls1-download.html) to work in your own editor or in an online editor.
## Other controls 2
Now it's time to have a go at implementing a drop-down select menu, to allow a user to pick their favorite food from the choices provided.
1. Create your basic select box structure.
2. Associate it semantically with the provided "food" label.
3. Inside the list, split the choices up into 2 subgroups — "mains" and "snacks".
To create the menu, update the HTML code in the editor below:
{{EmbedGHLiveSample("learning-area/html/forms/tasks/other-controls/other-controls2.html", '100%', 500)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/other-controls/other-controls2-download.html) to work in your own editor or in an online editor.
## Other controls 3
In our final task of this set, we start with much the same list of food choices. However, this time we want to do things differently:
1. Create a basic text input that is semantically associated with the provided label.
2. Put the food choices into a list that can be associated with a form input.
3. Associate the list with your text input, so that when you type characters, any of the list options that match the character sequence are given in a dropdown list as autocomplete suggestions.
To create the input, update the HTML code in the editor below:
{{EmbedGHLiveSample("learning-area/html/forms/tasks/other-controls/other-controls3.html", '100%', 500)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/other-controls/other-controls3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/html5_input_types/index.md | ---
title: The HTML5 input types
slug: Learn/Forms/HTML5_input_types
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Forms/Basic_native_form_controls", "Learn/Forms/Other_form_controls", "Learn/Forms")}}
In the [previous article](/en-US/docs/Learn/Forms/Basic_native_form_controls) we looked at the {{htmlelement("input")}} element, covering the original values of the `type` attribute available since the early days of HTML. Now we'll look at the functionality of newer form controls in detail, including some new input types, which were added in HTML5 to allow the collection of specific types of data.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>understanding of HTML</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the newer input type values available to create native
form controls, and how to implement them using HTML.
</td>
</tr>
</tbody>
</table>
> **Note:** Most of the features discussed in this article have wide support across browsers. We'll note any exceptions. If you want more detail on browser support, you should consult our [HTML forms element reference](/en-US/docs/Web/HTML/Element#forms), and in particular our extensive [\<input> types](/en-US/docs/Web/HTML/Element/input) reference.
Because HTML form control appearance may be quite different from a designer's specifications, web developers sometimes build their own custom form controls. We cover this in an advanced tutorial: [How to build custom form widgets](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls).
## Email address field
This type of field is set using the value `email` for the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute:
```html
<input type="email" id="email" name="email" />
```
When this [`type`](/en-US/docs/Web/HTML/Element/input#type) is used, the user is required to type a valid email address into the field. Any other content causes the browser to display an error when the form is submitted. You can see this in action in the below screenshot.

You can also use the [`multiple`](/en-US/docs/Web/HTML/Attributes/multiple) attribute in combination with the `email` input type to allow several email addresses to be entered in the same input (separated by commas):
```html
<input type="email" id="email" name="email" multiple />
```
On some devices — notably, touch devices with dynamic keyboards like smartphones — a different virtual keypad might be presented that is more suitable for entering email addresses, including the `@` key. See the Firefox for Android keyboard screenshot below for an example:

> **Note:** You can find examples of the basic text input types at [basic input examples](https://mdn.github.io/learning-area/html/forms/basic-input-examples/) (see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/basic-input-examples/index.html) also).
This is another good reason for using these newer input types, improving the user experience for users of these devices.
### Client-side validation
As you can see above, `email` — along with other newer `input` types — provides built-in _client-side_ error validation, performed by the browser before the data gets sent to the server. It _is_ a helpful aid to guide users to fill out a form accurately, and it can save time: it is useful to know that your data is not correct immediately, rather than having to wait for a round trip to the server.
But it _should not be considered_ an exhaustive security measure! Your apps should always perform security checks on any form-submitted data on the _server-side_ as well as the client-side, because client-side validation is too easy to turn off, so malicious users can still easily send bad data through to your server. Read [Website security](/en-US/docs/Learn/Server-side/First_steps/Website_security) for an idea of what _could_ happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind.
Note that `a@b` is a valid email address according to the default provided constraints. This is because the `email` input type allows intranet email addresses by default. To implement different validation behavior, you can use the [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) attribute, and you can also customize the error messages; we'll talk about how to use these features in the [Client-side form validation](/en-US/docs/Learn/Forms/Form_validation) article later on.
> **Note:** If the data entered is not an email address, the {{cssxref(':invalid')}} pseudo-class will match, and the {{domxref('validityState.typeMismatch')}} property will return `true`.
## Search field
Search fields are intended to be used to create search boxes on pages and apps. This type of field is set by using the value `search` for the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute:
```html
<input type="search" id="search" name="search" />
```
The main difference between a `text` field and a `search` field is how the browser styles its appearance. Often, `search` fields are rendered with rounded corners; they also sometimes display an "Ⓧ", which clears the field of any value when clicked. Additionally, on devices with dynamic keyboards, the keyboard's enter key may read "**search**", or display a magnifying glass icon.
The below screenshots show a non-empty search field in Firefox 71, Safari 13, and Chrome 79 on macOS, and Edge 18 and Chrome 79 on Windows 10. Note that the clear icon only appears if the field has a value, and, apart from Safari, it is only displayed when the field is focused.

Another worth-noting feature is that the values of a `search` field can be automatically saved and re-used to offer auto-completion across multiple pages of the same website; this tends to happen automatically in most modern browsers.
## Phone number field
A special field for filling in phone numbers can be created using `tel` as the value of the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute:
```html
<input type="tel" id="tel" name="tel" />
```
When accessed via a touch device with a dynamic keyboard, most devices will display a numeric keypad when `type="tel"` is encountered, meaning this type is useful whenever a numeric keypad is useful, and doesn't just have to be used for telephone numbers.
The following Firefox for Android keyboard screenshot provides an example:

Due to the wide variety of phone number formats around the world, this type of field does not enforce any constraints on the value entered by a user (this means it may include letters, etc.).
As we mentioned earlier, the [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) attribute can be used to enforce constraints, which you'll learn about in [Client-side form validation](/en-US/docs/Learn/Forms/Form_validation).
## URL field
A special type of field for entering URLs can be created using the value `url` for the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute:
```html
<input type="url" id="url" name="url" />
```
It adds special validation constraints to the field. The browser will report an error if no protocol (such as `http:`) is entered, or if the URL is otherwise malformed. On devices with dynamic keyboards, the default keyboard will often display some or all of the colon, period, and forward slash as default keys.
See below for an example (taken on Firefox for Android):

> **Note:** Just because the URL is well-formed doesn't necessarily mean that it refers to a location that actually exists!
## Numeric field
Controls for entering numbers can be created with an {{HTMLElement("input")}} [`type`](/en-US/docs/Web/HTML/Element/input#type) of `number`. This control looks like a text field but allows only floating-point numbers, and usually provides buttons in the form of a spinner to increase and decrease the value of the control. On devices with dynamic keyboards, the numeric keyboard is generally displayed.
The following screenshot (from Firefox for Android) provides an example:

With the `number` input type, you can constrain the minimum and maximum values allowed by setting the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes.
You can also use the `step` attribute to set the increment increase and decrease caused by pressing the spinner buttons. By default, the number input type only validates if the number is an integer. To allow float numbers, specify [`step="any"`](/en-US/docs/Web/HTML/Attributes/step). If omitted, the `step` value defaults to `1`, meaning only whole numbers are valid.
Let's look at some examples. The first one below creates a number control whose value is restricted to any value between `1` and `10`, and whose increase and decrease buttons change its value by `2`.
```html
<input type="number" name="age" id="age" min="1" max="10" step="2" />
```
The second one creates a number control whose value is restricted to any value between `0` and `1` inclusive, and whose increase and decrease buttons change its value by `0.01`.
```html
<input type="number" name="change" id="pennies" min="0" max="1" step="0.01" />
```
The `number` input type makes sense when the range of valid values is limited, for example a person's age or height. If the range is too large for incremental increases to make sense (such as USA ZIP codes, which range from `00001` to `99999`), the `tel` type might be a better option; it provides the numeric keypad while forgoing the number's spinner UI feature.
## Slider controls
Another way to pick a number is to use a **slider**. You see these quite often on sites like house-buying sites where you want to set a maximum property price to filter by. Let's look at a live example to illustrate this:
{{EmbedGHLiveSample("learning-area/html/forms/range-example/index.html", '100%', 200)}}
Usage-wise, sliders are less accurate than text fields. Therefore, they are used to pick a number whose _precise_ value is not necessarily important.
A slider is created using the {{HTMLElement("input")}} with its [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute set to the value `range`. The slider-thumb can be moved via mouse or touch, or with the arrows of the keypad.
It's important to properly configure your slider. To that end, it's highly recommended that you set the [`min`](/en-US/docs/Web/HTML/Attributes/min), [`max`](/en-US/docs/Web/HTML/Attributes/max), and [`step`](/en-US/docs/Web/HTML/Attributes/step) attributes which set the minimum, maximum, and increment values, respectively.
Let's look at the code behind the above example, so you can see how it's done. First of all, the basic HTML:
```html
<label for="price">Choose a maximum house price: </label>
<input
type="range"
name="price"
id="price"
min="50000"
max="500000"
step="100"
value="250000" />
<output class="price-output" for="price"></output>
```
This example creates a slider whose value may range between `50000` and `500000`, which increments/decrements by 100 at a time. We've given it a default value of `250000`, using the `value` attribute.
One problem with sliders is that they don't offer any kind of visual feedback as to what the current value is. This is why we've included an {{htmlelement("output")}} element to contain the current value. You could display an input value or the output of a calculation inside any element, but `<output>` is special — like `<label>` — and it can take a `for` attribute that allows you to associate it with the element or elements that the output value came from.
To actually display the current value, and update it as it changed, you must use JavaScript, but this is relatively easy to do:
```js
const price = document.querySelector("#price");
const output = document.querySelector(".price-output");
output.textContent = price.value;
price.addEventListener("input", () => {
output.textContent = price.value;
});
```
Here we store references to the `range` input and the `output` in two variables. Then we immediately set the `output`'s [`textContent`](/en-US/docs/Web/API/Node/textContent) to the current `value` of the input. Finally, an event listener is set to ensure that whenever the range slider is moved, the `output`'s `textContent` is updated to the new value.
> **Note:** There is a nice tutorial covering this subject on CSS Tricks: [The Output Element](https://css-tricks.com/the-output-element/).
## Date and time pickers
Gathering date and time values has traditionally been a nightmare for web developers. For a good user experience, it is important to provide a calendar selection UI, enabling users to select dates without necessitating context switching to a native calendar application or potentially entering them in differing formats that are hard to parse. The last minute of the previous millennium can be expressed in the following different ways, for example: 1999/12/31, 23:59 or 12/31/99T11:59PM.
HTML date controls are available to handle this specific kind of data, providing calendar widgets and making the data uniform.
A date and time control is created using the {{HTMLElement("input")}} element and an appropriate value for the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute, depending on whether you wish to collect dates, times, or both. Here's a live example that falls back to {{htmlelement("select")}} elements in non-supporting browsers:
{{EmbedGHLiveSample("learning-area/html/forms/datetime-local-picker-fallback/index.html", '100%', 200)}}
Let's look at the different available types in brief. Note that the usage of these types is quite complex, especially considering browser support (see below); to find out the full details, follow the links below to the reference pages for each type, including detailed examples.
### `datetime-local`
[`<input type="datetime-local">`](/en-US/docs/Web/HTML/Element/input/datetime-local) creates a widget to display and pick a date with time with no specific time zone information.
```html
<input type="datetime-local" name="datetime" id="datetime" />
```
### `month`
[`<input type="month">`](/en-US/docs/Web/HTML/Element/input/month) creates a widget to display and pick a month with a year.
```html
<input type="month" name="month" id="month" />
```
### `time`
[`<input type="time">`](/en-US/docs/Web/HTML/Element/input/time) creates a widget to display and pick a time value. While time may _display_ in 12-hour format, the _value returned_ is in 24-hour format.
```html
<input type="time" name="time" id="time" />
```
### `week`
[`<input type="week">`](/en-US/docs/Web/HTML/Element/input/week) creates a widget to display and pick a week number and its year.
Weeks start on Monday and run to Sunday. Additionally, the first week 1 of each year contains the first Thursday of that year — which may not include the first day of the year, or may include the last few days of the previous year.
```html
<input type="week" name="week" id="week" />
```
### Constraining date/time values
All date and time controls can be constrained using the [`min`](/en-US/docs/Web/HTML/Attributes/min) and [`max`](/en-US/docs/Web/HTML/Attributes/max) attributes, with further constraining possible via the [`step`](/en-US/docs/Web/HTML/Attributes/step) attribute (whose value varies according to input type).
```html
<label for="myDate">When are you available this summer?</label>
<input
type="date"
name="myDate"
min="2013-06-01"
max="2013-08-31"
step="7"
id="myDate" />
```
## Color picker control
Colors are always a bit difficult to handle. There are many ways to express them: RGB values (decimal or hexadecimal), HSL values, keywords, and so on.
A `color` control can be created using the {{HTMLElement("input")}} element with its [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute set to the value `color`:
```html
<input type="color" name="color" id="color" />
```
Clicking a color control generally displays the operating system's default color-picking functionality for you to choose.
Here is a live example for you to try out:
{{EmbedGHLiveSample("learning-area/html/forms/color-example/index.html", '100%', 200)}}
The value returned is always a lowercase 6-value hexadecimal color.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: HTML5 controls](/en-US/docs/Learn/Forms/Test_your_skills:_HTML5_controls).
## Summary
That brings us to the end of our tour of the HTML5 form input types. There are a few other control types that cannot be easily grouped together due to their very specific behaviors, but which are still essential to know about. We cover those in the next article.
{{PreviousMenuNext("Learn/Forms/Basic_native_form_controls", "Learn/Forms/Other_form_controls", "Learn/Forms")}}
### Advanced Topics
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/form_validation/index.md | ---
title: Client-side form validation
slug: Learn/Forms/Form_validation
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Forms/UI_pseudo-classes", "Learn/Forms/Sending_and_retrieving_form_data", "Learn/HTML/Forms")}}
Before submitting data to the server, it is important to ensure all required form controls are filled out, in the correct format.
This is called **client-side form validation**, and helps ensure data submitted matches the requirements set forth in the various form controls.
This article leads you through basic concepts and examples of client-side form validation.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Computer literacy, a reasonable understanding of
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand what client-side form validation is, why it's important,
and how to apply various techniques to implement it.
</td>
</tr>
</tbody>
</table>
Client-side validation is an initial check and an important feature of good user experience; by catching invalid data on the client-side, the user can fix it straight away.
If it gets to the server and is then rejected, a noticeable delay is caused by a round trip to the server and then back to the client-side to tell the user to fix their data.
However, client-side validation _should not be considered_ an exhaustive security measure! Your apps should always perform security checks on any form-submitted data on the _server-side_ **as well** as the client-side, because client-side validation is too easy to bypass, so malicious users can still easily send bad data through to your server.
Read [Website security](/en-US/docs/Learn/Server-side/First_steps/Website_security) for an idea of what _could_ happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind.
## What is form validation?
Go to any popular site with a registration form, and you will notice that they provide feedback when you don't enter your data in the format they are expecting.
You'll get messages such as:
- "This field is required" (You can't leave this field blank).
- "Please enter your phone number in the format xxx-xxxx" (A specific data format is required for it to be considered valid).
- "Please enter a valid email address" (the data you entered is not in the right format).
- "Your password needs to be between 8 and 30 characters long and contain one uppercase letter, one symbol, and a number." (A very specific data format is required for your data).
This is called **form validation**.
When you enter data, the browser and/or the web server will check to see that the data is in the correct format and within the constraints set by the application. Validation done in the browser is called **client-side** validation, while validation done on the server is called **server-side** validation.
In this chapter we are focusing on client-side validation.
If the information is correctly formatted, the application allows the data to be submitted to the server and (usually) saved in a database; if the information isn't correctly formatted, it gives the user an error message explaining what needs to be corrected, and lets them try again.
We want to make filling out web forms as easy as possible. So why do we insist on validating our forms?
There are three main reasons:
- **We want to get the right data, in the right format.** Our applications won't work properly if our users' data is stored in the wrong format, is incorrect, or is omitted altogether.
- **We want to protect our users' data**. Forcing our users to enter secure passwords makes it easier to protect their account information.
- **We want to protect ourselves**. There are many ways that malicious users can misuse unprotected forms to damage the application. See [Website security](/en-US/docs/Learn/Server-side/First_steps/Website_security).
> **Warning:** Never trust data passed to your server from the client. Even if your form is validating correctly and preventing malformed input on the client-side, a malicious user can still alter the network request.
## Different types of client-side validation
There are two different types of client-side validation that you'll encounter on the web:
- **Built-in form validation** uses HTML form validation features, which we've discussed in many places throughout this module.
This validation generally doesn't require much JavaScript. Built-in form validation has better performance than JavaScript, but it is not as customizable as JavaScript validation.
- **JavaScript** validation is coded using JavaScript.
This validation is completely customizable, but you need to create it all (or use a library).
## Using built-in form validation
One of the most significant features of [modern form controls](/en-US/docs/Learn/Forms/HTML5_input_types) is the ability to validate most user data without relying on JavaScript.
This is done by using validation attributes on form elements.
We've seen many of these earlier in the course, but to recap:
- [`required`](/en-US/docs/Web/HTML/Attributes/required): Specifies whether a form field needs to be filled in before the form can be submitted.
- [`minlength`](/en-US/docs/Web/HTML/Attributes/minlength) and [`maxlength`](/en-US/docs/Web/HTML/Attributes/maxlength): Specifies the minimum and maximum length of textual data (strings).
- [`min`](/en-US/docs/Web/HTML/Attributes/min) and [`max`](/en-US/docs/Web/HTML/Attributes/max): Specifies the minimum and maximum values of numerical input types.
- [`type`](/en-US/docs/Web/HTML/Element/input#input_types): Specifies whether the data needs to be a number, an email address, or some other specific preset type.
- [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern): Specifies a [regular expression](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) that defines a pattern the entered data needs to follow.
If the data entered in a form field follows all of the rules specified by the above attributes, it is considered valid.
If not, it is considered invalid.
When an element is valid, the following things are true:
- The element matches the {{cssxref(":valid")}} CSS pseudo-class, which lets you apply a specific style to valid elements.
- If the user tries to send the data, the browser will submit the form, provided there is nothing else stopping it from doing so (e.g., JavaScript).
When an element is invalid, the following things are true:
- The element matches the {{cssxref(":invalid")}} CSS pseudo-class, and sometimes other UI pseudo-classes (e.g., {{cssxref(":out-of-range")}}) depending on the error, which lets you apply a specific style to invalid elements.
- If the user tries to send the data, the browser will block the form and display an error message.
> **Note:** There are several errors that will prevent the form from being submitted, including a {{domxref('validityState.badInput', 'badInput')}}, {{domxref('validityState.patternMismatch','patternMismatch')}}, {{domxref('validityState.rangeOverflow','rangeOverflow')}} or {{domxref('validityState.rangeUnderflow','rangeUnderflow')}}, {{domxref('validityState.stepMismatch','stepMismatch')}}, {{domxref('validityState.tooLong','tooLong')}} or {{domxref('validityState.tooShort','tooShort')}}, {{domxref('validityState.typeMismatch','typeMismatch')}}, {{domxref('validityState.valueMissing','valueMissing')}}, or a {{domxref('validityState.customError','customError')}}.
## Built-in form validation examples
In this section, we'll test out some of the attributes that we discussed above.
### Simple start file
Let's start with a simple example: an input that allows you to choose whether you prefer a banana or a cherry.
This example involves a simple text {{HTMLElement("input")}} with an associated {{htmlelement("label")}} and a submit {{htmlelement("button")}}.
Find the source code on GitHub at [fruit-start.html](https://github.com/mdn/learning-area/blob/main/html/forms/form-validation/fruit-start.html) and a live example below.
```html
<form>
<label for="choose">Would you prefer a banana or cherry?</label>
<input id="choose" name="i-like" />
<button>Submit</button>
</form>
```
```css
input:invalid {
border: 2px dashed red;
}
input:valid {
border: 2px solid black;
}
```
{{EmbedLiveSample("Simple_start_file", "100%", 80)}}
To begin, make a copy of `fruit-start.html` in a new directory on your hard drive.
### The required attribute
The simplest HTML validation feature is the [`required`](/en-US/docs/Web/HTML/Attributes/required) attribute.
To make an input mandatory, add this attribute to the element.
When this attribute is set, the element matches the {{cssxref(':required')}} UI pseudo-class and the form won't submit, displaying an error message on submission when the input is empty.
While empty, the input will also be considered invalid, matching the {{cssxref(':invalid')}} UI pseudo-class.
Add a `required` attribute to your input, as shown below.
```html
<form>
<label for="choose">Would you prefer a banana or cherry? (required)</label>
<input id="choose" name="i-like" required />
<button>Submit</button>
</form>
```
Note the CSS that is included in the example file:
```css
input:invalid {
border: 2px dashed red;
}
input:invalid:required {
background-image: linear-gradient(to right, pink, lightgreen);
}
input:valid {
border: 2px solid black;
}
```
This CSS causes the input to have a red dashed border when it is invalid and a more subtle solid black border when valid.
We also added a background gradient when the input is required _and_ invalid. Try out the new behavior in the example below:
{{EmbedLiveSample("The_required_attribute", "100%", 80)}}
> **Note:** You can find this example live on GitHub as [fruit-validation.html](https://mdn.github.io/learning-area/html/forms/form-validation/fruit-required.html). See also the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/form-validation/fruit-required.html).
Try submitting the form without a value.
Note how the invalid input gets focus, a default error message ("Please fill out this field") appears, and the form is prevented from being sent.
The presence of the `required` attribute on any element that supports this attribute means the element matches the {{cssxref(':required')}} pseudo-class whether it has a value or not. If the {{HTMLElement("input")}} has no value, the `input` will match the {{cssxref(':invalid')}} pseudo-class.
> **Note:** For good user experience, indicate to the user when form fields are required.
> It isn't only good user experience, it is required by WCAG [accessibility](/en-US/docs/Learn/Accessibility) guidelines.
> Also, only require users to input data you actually need: For example, why do you really need to know someone's gender or title?
### Validating against a regular expression
Another useful validation feature is the [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) attribute, which expects a [Regular Expression](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) as its value.
A regular expression (regexp) is a pattern that can be used to match character combinations in text strings, so regexps are ideal for form validation and serve a variety of other uses in JavaScript.
Regexps are quite complex, and we don't intend to teach you them exhaustively in this article.
Below are some examples to give you a basic idea of how they work.
- `a` — Matches one character that is `a` (not `b`, not `aa`, and so on).
- `abc` — Matches `a`, followed by `b`, followed by `c`.
- `ab?c` — Matches `a`, optionally followed by a single `b`, followed by `c`. (`ac` or `abc`)
- `ab*c` — Matches `a`, optionally followed by any number of `b`s, followed by `c`. (`ac`, `abc`, `abbbbbc`, and so on).
- `a|b` — Matches one character that is `a` or `b`.
- `abc|xyz` — Matches exactly `abc` or exactly `xyz` (but not `abcxyz` or `a` or `y`, and so on).
There are many more possibilities that we don't cover here.
For a complete list and many examples, consult our [Regular expression](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) documentation.
Let's implement an example.
Update your HTML to add a [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) attribute like this:
```html
<form>
<label for="choose">Would you prefer a banana or a cherry?</label>
<input id="choose" name="i-like" required pattern="[Bb]anana|[Cc]herry" />
<button>Submit</button>
</form>
```
```css hidden
input:invalid {
border: 2px dashed red;
}
input:valid {
border: 2px solid black;
}
```
This gives us the following update — try it out:
{{EmbedLiveSample("Validating_against_a_regular_expression", "100%", 80)}}
> **Note:** You can find this example live on GitHub as [fruit-pattern.html](https://mdn.github.io/learning-area/html/forms/form-validation/fruit-pattern.html) (see also the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/form-validation/fruit-pattern.html).)
In this example, the {{HTMLElement("input")}} element accepts one of four possible values: the strings "banana", "Banana", "cherry", or "Cherry". Regular expressions are case-sensitive, but we've made it support capitalized as well as lower-case versions using an extra "Aa" pattern nested inside square brackets.
At this point, try changing the value inside the [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) attribute to equal some of the examples you saw earlier, and look at how that affects the values you can enter to make the input value valid.
Try writing some of your own, and see how it goes.
Make them fruit-related where possible so that your examples make sense!
If a non-empty value of the {{HTMLElement("input")}} doesn't match the regular expression's pattern, the `input` will match the {{cssxref(':invalid')}} pseudo-class.
> **Note:** Some {{HTMLElement("input")}} element types don't need a [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) attribute to be validated against a regular expression. Specifying the `email` type, for example, validates the inputs value against a well-formed email address pattern or a pattern matching a comma-separated list of email addresses if it has the [`multiple`](/en-US/docs/Web/HTML/Attributes/multiple) attribute.
> **Note:** The {{HTMLElement("textarea")}} element doesn't support the [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) attribute.
### Constraining the length of your entries
You can constrain the character length of all text fields created by {{HTMLElement("input")}} or {{HTMLElement("textarea")}} by using the [`minlength`](/en-US/docs/Web/HTML/Attributes/minlength) and [`maxlength`](/en-US/docs/Web/HTML/Attributes/maxlength) attributes.
A field is invalid if it has a value and that value has fewer characters than the [`minlength`](/en-US/docs/Web/HTML/Attributes/minlength) value or more than the [`maxlength`](/en-US/docs/Web/HTML/Attributes/maxlength) value.
Browsers often don't let the user type a longer value than expected into text fields. A better user experience than just using `maxlength` is to also provide character count feedback in an accessible manner and let them edit their content down to size.
An example of this is the character limit when posting on social media. JavaScript, including [solutions using `maxlength`](https://github.com/mimo84/bootstrap-maxlength), can be used to provide this.
### Constraining the values of your entries
For number fields (i.e. [`<input type="number">`](/en-US/docs/Web/HTML/Element/input/number)), the [`min`](/en-US/docs/Web/HTML/Attributes/min) and [`max`](/en-US/docs/Web/HTML/Attributes/max) attributes can be used to provide a range of valid values.
If the field contains a value outside this range, it will be invalid.
Let's look at another example.
Create a new copy of the [fruit-start.html](https://github.com/mdn/learning-area/blob/main/html/forms/form-validation/fruit-start.html) file.
Now delete the contents of the `<body>` element, and replace it with the following:
```html
<form>
<div>
<label for="choose">Would you prefer a banana or a cherry?</label>
<input
type="text"
id="choose"
name="i-like"
required
minlength="6"
maxlength="6" />
</div>
<div>
<label for="number">How many would you like?</label>
<input type="number" id="number" name="amount" value="1" min="1" max="10" />
</div>
<div>
<button>Submit</button>
</div>
</form>
```
- Here you'll see that we've given the `text` field a `minlength` and `maxlength` of six, which is the same length as banana and cherry.
- We've also given the `number` field a `min` of one and a `max` of ten.
Entered numbers outside this range will show as invalid; users won't be able to use the increment/decrement arrows to move the value outside of this range.
If the user manually enters a number outside of this range, the data is invalid.
The number is not required, so removing the value will still result in a valid value.
```css hidden
input:invalid {
border: 2px dashed red;
}
input:valid {
border: 2px solid black;
}
div {
margin-bottom: 10px;
}
```
Here is the example running live:
{{EmbedLiveSample("Constraining_the_values_of_your_entries", "100%", 100)}}
> **Note:** You can find this example live on GitHub as [fruit-length.html](https://mdn.github.io/learning-area/html/forms/form-validation/fruit-length.html). See also the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/form-validation/fruit-length.html).
> **Note:** `<input type="number">` (and other types, such as `range` and `date`) can also take a [`step`](/en-US/docs/Web/HTML/Attributes/step) attribute, which specifies what increment the value will go up or down by when the input controls are used (such as the up and down number buttons).
> In the above example we've not included a `step` attribute, so the value defaults to `1`. This means that floats, like 3.2, will also show as invalid.
### Full example
Here is a full example to show usage of HTML's built-in validation features.
First, some HTML:
```html
<form>
<fieldset>
<legend>
Do you have a driver's license?<span aria-label="required">*</span>
</legend>
<!-- While only one radio button in a same-named group can be selected at a time,
and therefore only one radio button in a same-named group having the "required"
attribute suffices in making a selection a requirement -->
<input type="radio" required name="driver" id="r1" value="yes" /><label
for="r1"
>Yes</label
>
<input type="radio" required name="driver" id="r2" value="no" /><label
for="r2"
>No</label
>
</fieldset>
<p>
<label for="n1">How old are you?</label>
<!-- The pattern attribute can act as a fallback for browsers which
don't implement the number input type but support the pattern attribute.
Please note that browsers that support the pattern attribute will make it
fail silently when used with a number field.
Its usage here acts only as a fallback -->
<input
type="number"
min="12"
max="120"
step="1"
id="n1"
name="age"
pattern="\d+" />
</p>
<p>
<label for="t1"
>What's your favorite fruit?<span aria-label="required">*</span></label
>
<input
type="text"
id="t1"
name="fruit"
list="l1"
required
pattern="[Bb]anana|[Cc]herry|[Aa]pple|[Ss]trawberry|[Ll]emon|[Oo]range" />
<datalist id="l1">
<option>Banana</option>
<option>Cherry</option>
<option>Apple</option>
<option>Strawberry</option>
<option>Lemon</option>
<option>Orange</option>
</datalist>
</p>
<p>
<label for="t2">What's your email address?</label>
<input type="email" id="t2" name="email" />
</p>
<p>
<label for="t3">Leave a short message</label>
<textarea id="t3" name="msg" maxlength="140" rows="5"></textarea>
</p>
<p>
<button>Submit</button>
</p>
</form>
```
And now some CSS to style the HTML:
```css
form {
font: 1em sans-serif;
max-width: 320px;
}
p > label {
display: block;
}
input[type="text"],
input[type="email"],
input[type="number"],
textarea,
fieldset {
width: 100%;
border: 1px solid #333;
box-sizing: border-box;
}
input:invalid {
box-shadow: 0 0 5px 1px red;
}
input:focus:invalid {
box-shadow: none;
}
```
This renders as follows:
{{EmbedLiveSample("Full_example", "100%", 420)}}
See [Validation-related attributes](/en-US/docs/Web/HTML/Constraint_validation#validation-related_attributes) for a complete list of attributes that can be used to constrain input values and the input types that support them.
> **Note:** You can find this example live on GitHub as [full-example.html](https://mdn.github.io/learning-area/html/forms/form-validation/full-example.html) (see also the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/form-validation/full-example.html).)
## Validating forms using JavaScript
You must use JavaScript if you want to take control over the look and feel of native error messages.
In this section we will look at the different ways to do this.
### The Constraint Validation API
The Constraint Validation API consists of a set of methods and properties available on the following form element DOM interfaces:
- [`HTMLButtonElement`](/en-US/docs/Web/API/HTMLButtonElement) (represents a [`<button>`](/en-US/docs/Web/HTML/Element/button) element)
- [`HTMLFieldSetElement`](/en-US/docs/Web/API/HTMLFieldSetElement) (represents a [`<fieldset>`](/en-US/docs/Web/HTML/Element/fieldset) element)
- [`HTMLInputElement`](/en-US/docs/Web/API/HTMLInputElement) (represents an [`<input>`](/en-US/docs/Web/HTML/Element/input) element)
- [`HTMLOutputElement`](/en-US/docs/Web/API/HTMLOutputElement) (represents an [`<output>`](/en-US/docs/Web/HTML/Element/output) element)
- [`HTMLSelectElement`](/en-US/docs/Web/API/HTMLSelectElement) (represents a [`<select>`](/en-US/docs/Web/HTML/Element/select) element)
- [`HTMLTextAreaElement`](/en-US/docs/Web/API/HTMLTextAreaElement) (represents a [`<textarea>`](/en-US/docs/Web/HTML/Element/textarea) element)
The Constraint Validation API makes the following properties available on the above elements.
- `validationMessage`: Returns a localized message describing the validation constraints that the control doesn't satisfy (if any). If the control is not a candidate for constraint validation (`willValidate` is `false`) or the element's value satisfies its constraints (is valid), this will return an empty string.
- `validity`: Returns a `ValidityState` object that contains several properties describing the validity state of the element. You can find full details of all the available properties in the {{domxref("ValidityState")}} reference page; below is listed a few of the more common ones:
- {{domxref("ValidityState.patternMismatch", "patternMismatch")}}: Returns `true` if the value does not match the specified [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern), and `false` if it does match. If true, the element matches the {{cssxref(":invalid")}} CSS pseudo-class.
- {{domxref("ValidityState.tooLong", "tooLong")}}: Returns `true` if the value is longer than the maximum length specified by the [`maxlength`](/en-US/docs/Web/HTML/Element/input#maxlength) attribute, or `false` if it is shorter than or equal to the maximum. If true, the element matches the {{cssxref(":invalid")}} CSS pseudo-class.
- {{domxref("ValidityState.tooShort", "tooShort")}}: Returns `true` if the value is shorter than the minimum length specified by the [`minlength`](/en-US/docs/Web/HTML/Element/input#minlength) attribute, or `false` if it is greater than or equal to the minimum. If true, the element matches the {{cssxref(":invalid")}} CSS pseudo-class.
- {{domxref("ValidityState.rangeOverflow", "rangeOverflow")}}: Returns `true` if the value is greater than the maximum specified by the [`max`](/en-US/docs/Web/HTML/Element/input#max) attribute, or `false` if it is less than or equal to the maximum. If true, the element matches the {{cssxref(":invalid")}} and {{cssxref(":out-of-range")}} CSS pseudo-classes.
- {{domxref("ValidityState.rangeUnderflow", "rangeUnderflow")}}: Returns `true` if the value is less than the minimum specified by the [`min`](/en-US/docs/Web/HTML/Element/input#min) attribute, or `false` if it is greater than or equal to the minimum. If true, the element matches the {{cssxref(":invalid")}} and {{cssxref(":out-of-range")}} CSS pseudo-classes.
- {{domxref("ValidityState.typeMismatch", "typeMismatch")}}: Returns `true` if the value is not in the required syntax (when [`type`](/en-US/docs/Web/HTML/Element/input#type) is `email` or `url`), or `false` if the syntax is correct. If `true`, the element matches the {{cssxref(":invalid")}} CSS pseudo-class.
- `valid`: Returns `true` if the element meets all its validation constraints, and is therefore considered to be valid, or `false` if it fails any constraint. If true, the element matches the {{cssxref(":valid")}} CSS pseudo-class; the {{cssxref(":invalid")}} CSS pseudo-class otherwise.
- `valueMissing`: Returns `true` if the element has a [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute, but no value, or `false` otherwise. If true, the element matches the {{cssxref(":invalid")}} CSS pseudo-class.
- `willValidate`: Returns `true` if the element will be validated when the form is submitted; `false` otherwise.
The Constraint Validation API also makes the following methods available on the above elements and the [`form`](/en-US/docs/Web/HTML/Element/form) element.
- `checkValidity()`: Returns `true` if the element's value has no validity problems; `false` otherwise. If the element is invalid, this method also fires an [`invalid` event](/en-US/docs/Web/API/HTMLInputElement/invalid_event) on the element.
- `reportValidity()`: Reports invalid field(s) using events. This method is useful in combination with `preventDefault()` in an `onSubmit` event handler.
- `setCustomValidity(message)`: Adds a custom error message to the element; if you set a custom error message, the element is considered to be invalid, and the specified error is displayed. This lets you use JavaScript code to establish a validation failure other than those offered by the standard HTML validation constraints. The message is shown to the user when reporting the problem.
#### Implementing a customized error message
As you saw in the HTML validation constraint examples earlier, each time a user tries to submit an invalid form, the browser displays an error message. The way this message is displayed depends on the browser.
These automated messages have two drawbacks:
- There is no standard way to change their look and feel with CSS.
- They depend on the browser locale, which means that you can have a page in one language but an error message displayed in another language, as seen in the following Firefox screenshot.

Customizing these error messages is one of the most common use cases of the Constraint Validation API.
Let's work through a simple example of how to do this.
We'll start with some simple HTML (feel free to put this in a blank HTML file; use a fresh copy of [fruit-start.html](https://github.com/mdn/learning-area/blob/main/html/forms/form-validation/fruit-start.html) as a basis, if you like):
```html
<form>
<label for="mail">
I would like you to provide me with an email address:
</label>
<input type="email" id="mail" name="mail" />
<button>Submit</button>
</form>
```
And add the following JavaScript to the page:
```js
const email = document.getElementById("mail");
email.addEventListener("input", (event) => {
if (email.validity.typeMismatch) {
email.setCustomValidity("I am expecting an email address!");
} else {
email.setCustomValidity("");
}
});
```
Here we store a reference to the email input, then add an event listener to it that runs the contained code each time the value inside the input is changed.
Inside the contained code, we check whether the email input's `validity.typeMismatch` property returns `true`, meaning that the contained value doesn't match the pattern for a well-formed email address. If so, we call the {{domxref("HTMLInputElement.setCustomValidity()","setCustomValidity()")}} method with a custom message. This renders the input invalid, so that when you try to submit the form, submission fails and the custom error message is displayed.
If the `validity.typeMismatch` property returns `false`, we call the `setCustomValidity()` method with an empty string. This renders the input valid, so the form will submit.
You can try it out below:
{{EmbedGHLiveSample("learning-area/html/forms/form-validation/custom-error-message.html", '100%', 120)}}
> **Note:** You can find this example live on GitHub as [custom-error-message.html](https://mdn.github.io/learning-area/html/forms/form-validation/custom-error-message.html) (see also the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/form-validation/custom-error-message.html).)
#### A more detailed example
Now that we've seen a really simple example, let's see how we can use this API to build some slightly more complex custom validation.
First, the HTML. Again, feel free to build this along with us:
```html
<form novalidate>
<p>
<label for="mail">
<span>Please enter an email address:</span>
<input type="email" id="mail" name="mail" required minlength="8" />
<span class="error" aria-live="polite"></span>
</label>
</p>
<button>Submit</button>
</form>
```
This simple form uses the [`novalidate`](/en-US/docs/Web/HTML/Element/form#novalidate) attribute to turn off the browser's automatic validation; this lets our script take control over validation.
However, this doesn't disable support for the constraint validation API nor the application of CSS pseudo-classes like {{cssxref(":valid")}}, etc.
That means that even though the browser doesn't automatically check the validity of the form before sending its data, you can still do it yourself and style the form accordingly.
Our input to validate is an [`<input type="email">`](/en-US/docs/Web/HTML/Element/input/email), which is `required`, and has a `minlength` of 8 characters. Let's check these using our own code, and show a custom error message for each one.
We are aiming to show the error messages inside a `<span>` element.
The [`aria-live`](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) attribute is set on that `<span>` to make sure that our custom error message will be presented to everyone, including it being read out to screen reader users.
> **Note:** A key point here is that setting the `novalidate` attribute on the form is what stops the form from showing its own error message bubbles, and allows us to instead display the custom error messages in the DOM in some manner of our own choosing.
Now onto some basic CSS to improve the look of the form slightly, and provide some visual feedback when the input data is invalid:
```css
body {
font: 1em sans-serif;
width: 200px;
padding: 0;
margin: 0 auto;
}
p * {
display: block;
}
input[type="email"] {
appearance: none;
width: 100%;
border: 1px solid #333;
margin: 0;
font-family: inherit;
font-size: 90%;
box-sizing: border-box;
}
/* This is our style for the invalid fields */
input:invalid {
border-color: #900;
background-color: #fdd;
}
input:focus:invalid {
outline: none;
}
/* This is the style of our error messages */
.error {
width: 100%;
padding: 0;
font-size: 80%;
color: white;
background-color: #900;
border-radius: 0 0 5px 5px;
box-sizing: border-box;
}
.error.active {
padding: 0.3em;
}
```
Now let's look at the JavaScript that implements the custom error validation.
```js
// There are many ways to pick a DOM node; here we get the form itself and the email
// input box, as well as the span element into which we will place the error message.
const form = document.querySelector("form");
const email = document.getElementById("mail");
const emailError = document.querySelector("#mail + span.error");
email.addEventListener("input", (event) => {
// Each time the user types something, we check if the
// form fields are valid.
if (email.validity.valid) {
// In case there is an error message visible, if the field
// is valid, we remove the error message.
emailError.textContent = ""; // Reset the content of the message
emailError.className = "error"; // Reset the visual state of the message
} else {
// If there is still an error, show the correct error
showError();
}
});
form.addEventListener("submit", (event) => {
// if the email field is valid, we let the form submit
if (!email.validity.valid) {
// If it isn't, we display an appropriate error message
showError();
// Then we prevent the form from being sent by canceling the event
event.preventDefault();
}
});
function showError() {
if (email.validity.valueMissing) {
// If the field is empty,
// display the following error message.
emailError.textContent = "You need to enter an email address.";
} else if (email.validity.typeMismatch) {
// If the field doesn't contain an email address,
// display the following error message.
emailError.textContent = "Entered value needs to be an email address.";
} else if (email.validity.tooShort) {
// If the data is too short,
// display the following error message.
emailError.textContent = `Email should be at least ${email.minLength} characters; you entered ${email.value.length}.`;
}
// Set the styling appropriately
emailError.className = "error active";
}
```
The comments explain things pretty well, but briefly:
- Every time we change the value of the input, we check to see if it contains valid data.
If it has then we remove any error message being shown.
If the data is not valid, we run `showError()` to show the appropriate error.
- Every time we try to submit the form, we again check to see if the data is valid. If so, we let the form submit.
If not, we run `showError()` to show the appropriate error, and stop the form submitting with [`preventDefault()`](/en-US/docs/Web/API/Event/preventDefault).
- The `showError()` function uses various properties of the input's `validity` object to determine what the error is, and then displays an error message as appropriate.
Here is the live result:
{{EmbedGHLiveSample("learning-area/html/forms/form-validation/detailed-custom-validation.html", '100%', 150)}}
> **Note:** You can find this example live on GitHub as [detailed-custom-validation.html](https://mdn.github.io/learning-area/html/forms/form-validation/detailed-custom-validation.html). See also the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/form-validation/detailed-custom-validation.html).
The constraint validation API gives you a powerful tool to handle form validation, letting you have enormous control over the user interface above and beyond what you can do with HTML and CSS alone.
### Validating forms without a built-in API
In some cases, such as [custom controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls), you won't be able to or won't want to use the Constraint Validation API. You're still able to use JavaScript to validate your form, but you'll just have to write your own.
To validate a form, ask yourself a few questions:
- What kind of validation should I perform?
- : You need to determine how to validate your data: string operations, type conversion, regular expressions, and so on. It's up to you.
- What should I do if the form doesn't validate?
- : This is clearly a UI matter. You have to decide how the form will behave. Does the form send the data anyway?
Should you highlight the fields that are in error?
Should you display error messages?
- How can I help the user to correct invalid data?
- : In order to reduce the user's frustration, it's very important to provide as much helpful information as possible in order to guide them in correcting their inputs.
You should offer up-front suggestions so they know what's expected, as well as clear error messages.
If you want to dig into form validation UI requirements, here are some useful articles you should read:
- [Help users enter the right data in forms](https://web.dev/learn/forms/validation/)
- [Validating input](https://www.w3.org/WAI/tutorials/forms/validation/)
- [How to Report Errors in Forms: 10 Design Guidelines](https://www.nngroup.com/articles/errors-forms-design-guidelines/)
#### An example that doesn't use the constraint validation API
In order to illustrate this, the following is a simplified version of the previous example without the Constraint Validation API.
The HTML is almost the same; we just removed the HTML validation features.
```html
<form>
<p>
<label for="mail">
<span>Please enter an email address:</span>
<input type="text" id="mail" name="mail" />
<span class="error" aria-live="polite"></span>
</label>
</p>
<button>Submit</button>
</form>
```
Similarly, the CSS doesn't need to change very much; we've just turned the {{cssxref(":invalid")}} CSS pseudo-class into a real class and avoided using the attribute selector.
```css
body {
font: 1em sans-serif;
width: 200px;
padding: 0;
margin: 0 auto;
}
form {
max-width: 200px;
}
p * {
display: block;
}
input#mail {
appearance: none;
width: 100%;
border: 1px solid #333;
margin: 0;
font-family: inherit;
font-size: 90%;
box-sizing: border-box;
}
/* This is our style for the invalid fields */
input.invalid {
border-color: #900;
background-color: #fdd;
}
input:focus:invalid {
outline: none;
}
/* This is the style of our error messages */
.error {
width: 100%;
padding: 0;
font-size: 80%;
color: white;
background-color: #900;
border-radius: 0 0 5px 5px;
box-sizing: border-box;
}
.error.active {
padding: 0.3em;
}
```
The big changes are in the JavaScript code, which needs to do much more heavy lifting.
```js
const form = document.querySelector("form");
const email = document.getElementById("mail");
const error = email.nextElementSibling;
// As per the HTML Specification
const emailRegExp =
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
// Now we can rebuild our validation constraint
// Because we do not rely on CSS pseudo-class, we have to
// explicitly set the valid/invalid class on our email field
window.addEventListener("load", () => {
// Here, we test if the field is empty (remember, the field is not required)
// If it is not, we check if its content is a well-formed email address.
const isValid = email.value.length === 0 || emailRegExp.test(email.value);
email.className = isValid ? "valid" : "invalid";
});
// This defines what happens when the user types in the field
email.addEventListener("input", () => {
const isValid = email.value.length === 0 || emailRegExp.test(email.value);
if (isValid) {
email.className = "valid";
error.textContent = "";
error.className = "error";
} else {
email.className = "invalid";
}
});
// This defines what happens when the user tries to submit the data
form.addEventListener("submit", (event) => {
event.preventDefault();
const isValid = email.value.length === 0 || emailRegExp.test(email.value);
if (!isValid) {
email.className = "invalid";
error.textContent = "I expect an email, darling!";
error.className = "error active";
} else {
email.className = "valid";
error.textContent = "";
error.className = "error";
}
});
```
The result looks like this:
{{EmbedLiveSample("An_example_that_doesnt_use_the_constraint_validation_API", "100%", 130)}}
As you can see, it's not that hard to build a validation system on your own. The difficult part is to make it generic enough to use both cross-platform and on any form you might create. There are many libraries available to perform form validation, such as [Validate.js](https://rickharrison.github.io/validate.js/).
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Form validation](/en-US/docs/Learn/Forms/Test_your_skills:_Form_validation).
## Summary
Client-side form validation sometimes requires JavaScript if you want to customize styling and error messages, but it _always_ requires you to think carefully about the user.
Always remember to help your users correct the data they provide. To that end, be sure to:
- Display explicit error messages.
- Be permissive about the input format.
- Point out exactly where the error occurs, especially on large forms.
Once you have checked that the form is filled out correctly, the form can be submitted.
We'll cover [sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data) next.
{{PreviousMenuNext("Learn/Forms/UI_pseudo-classes", "Learn/Forms/Sending_and_retrieving_form_data", "Learn/HTML/Forms")}}
### Advanced Topics
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/html_forms_in_legacy_browsers/index.md | ---
title: HTML forms in legacy browsers
slug: Learn/Forms/HTML_forms_in_legacy_browsers
page-type: guide
---
{{LearnSidebar}}
All web developers learn very quickly (and sometimes painfully) that the Web is a very rough place for them. Our worst curse is legacy browsers. Okay, let's admit it, when we said "legacy browser" we all have in mind "Internet Explorer", but they are far from the only ones. In the mobile world, when neither the browser nor the OS can be updated such as on older Android phones or iPhones, the stock browsers that don't update are also legacy browsers.
Dealing with this wilderness is part of the job. Fortunately, there are a few tricks to know that can help you to solve most of the problems caused by legacy browsers. If a browser doesn't support an HTML {{htmlelement('input')}} type, it doesn't fail: it just uses the default value of `type=text`.
## Learn about the issues
To understand common patterns, it helps to read documentation. If you are reading this on [MDN](/), you are at the right place to start. Just check the support of the elements (or DOM interfaces) you want to use. MDN has compatibility tables available for most elements, properties and APIs that can be used in a web page.
Because [HTML forms](/en-US/docs/Learn/Forms) involves complex interaction, there is one important rule: keep it simple, also known as the "[KISS principal](https://en.wikipedia.org/wiki/KISS_principle)". There are so many cases where we want forms that are "nicer" or "with advanced functionality", but building efficient HTML Forms is not a question of design or technology. Rather, it's about simplicity, intuitiveness, and ease of user interaction. The tutorial, [forms usability on UX For The Masses,](https://www.uxforthemasses.com/forms-usability/) explains it well.
### Graceful degradation is web developer's best friend
[Graceful degradation and progressive enhancement](https://www.sitepoint.com/progressive-enhancement-graceful-degradation-choice/) are development patterns that allow you to build great stuff by supporting a wide range of browsers at the same time. When you build something for a modern browser, and you want to be sure it will work, one way or another, on legacy browsers, you are performing graceful degradation.
Let's see some examples related to HTML forms.
#### HTML input types
All HTML input types are useable in all browsers, even ancient ones, because the way they degrade is highly predictable. If a browser does not know the value of the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute of an {{HTMLElement("input")}} element, it will fall back as if the value were `text`.
```html
<label for="myColor">
Pick a color
<input type="color" id="myColor" name="color" />
</label>
```
<table class="no-markdown">
<thead>
<tr>
<th>Supported</th>
<th>Not supported</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<img
alt="Screen shot of the color input on Chrome for Mac OSX"
src="color-fallback-chrome.png"
/>
</td>
<td>
<img
alt="Screen shot of the color input on Firefox for Mac OSX"
src="color-fallback-firefox.png"
/>
</td>
</tr>
</tbody>
</table>
#### Form buttons
There are two ways to define buttons within HTML forms:
- The {{HTMLElement("input")}} element with its attribute [`type`](/en-US/docs/Web/HTML/Element/input#type) set to the values `button`, `submit`, `reset` or `image`
- The {{HTMLElement("button")}} element
##### {{HTMLElement("input")}}
The {{HTMLElement("input")}} element can make things a little difficult if you want to apply some CSS by using the element selector:
```html
<input type="button" value="click me" />
```
If we remove the border on all inputs, can we restore the default appearance on input buttons only?
```css
input {
/* This rule turns off the default rendering for the input types that have a border,
including buttons defined with an input element */
border: 1px solid #ccc;
}
input[type="button"] {
/* This does NOT restore the default rendering */
border: none;
}
input[type="button"] {
/* These don't either! Actually there is no standard way to do it in any browser */
border: auto;
border: initial;
}
input[type="button"] {
/* This will come the closest to restoring default rendering. */
border: revert;
}
```
See the global CSS {{cssxref('revert')}} value for more information.
##### {{HTMLElement("button")}}
The {{HTMLElement("button")}} element suffered from two issues that are now resolved:
- A bug in old versions of Internet Explorer sent the HTML content available between the starting and ending tag of the {{HTMLElement("button")}} element instead of the content of the [`value`](/en-US/docs/Web/HTML/Element/button#value) attribute when clicked. This was only an issue if that value needed to be sent, such as when data processing depends on which button a user clicked.
- Some very old browsers did not use `submit` as the default value for the [`type`](/en-US/docs/Web/HTML/Element/button#type) attribute. While resolved in all modern browsers, it is still recommended to always set the [`type`](/en-US/docs/Web/HTML/Element/button#type) attribute on {{HTMLElement("button")}} elements.
```html
<!-- Clicking this button sent "<em>Do A</em>" instead of "A" in some cases -->
<button type="submit" name="IWantTo" value="A">
<em>Do A</em>
</button>
```
Choosing one solution or the other is up to you based on your project's constraints.
### Let go of CSS
One of the big issues with HTML Forms is styling form widgets with CSS. Form controls appearance is browser and operating system specific. For example, the input of color type looks different in Safari, Chrome and Firefox browser, but the color picker widget is the same in all browsers on a device as it opens up the operating system's native color picker.
It's generally a good idea to not alter the default appearance of form control because altering one CSS property value may alter some input types but not others. For example, if you declare `input { font-size: 2rem; }`, it will impact `number`, `date`, and `text`, but not `color` or `range`. If you alter a property, that may impact the appearance of the widget in unexpected ways. For example, `[value] { background-color: #ccc; }` may have been used to target every {{HTMLElement("input")}} with a `value` attribute, but changing the background-color or border radius on a {{HTMLElement("meter")}} will lead to likely unexpected results that differ across browsers. You can declare {{cssxref('appearance', 'appearance: none;')}} to remove the browser styles, but that generally defeats the purpose: as you lose all styling, removing the default look and feel your visitors are used to.
To summarize, when it comes to styling form control widgets, the side effects of styling them with CSS can be unpredictable. So don't. As you can see from the complexity of the [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) article, it's very difficult. Even if it's still possible to do a few adjustments on text elements (such as sizing or font color), there are always side effects. The best approach remains to not style HTML Form widgets at all. But you can still apply styles to all the surrounding items. And, if you must alter the default styles of your form widgets, define a style guide to ensure consistency among all your form controls so user experience is not destroyed. You can also investigate some hard techniques such as [rebuilding widgets with JavaScript](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls). But in that case, do not hesitate to [charge your client for such foolishness](https://www.smashingmagazine.com/2011/11/but-the-client-wants-ie-6-support/).
## Feature detection and polyfills
CSS and JavaScript are awesome technologies, but it's important to ensure you don't break legacy browsers. Before using features that aren't fully supported in the browsers your targeting, you should feature detect:
### CSS feature detection
Before styling a replaced form control widget, you can check to see if the browser supports the features you plan on using {{cssxref('@supports')}}:
```css
@supports (appearance: none) {
input[type="search"] {
appearance: none;
/* restyle the search input */
}
}
```
The {{cssxref('appearance')}} property can be used to display an element using platform-native styling, or, as is done with the value of `none`, remove default platform-native based styling.
### Unobtrusive JavaScript
One of the biggest problems is the availability of APIs. For that reason, it's considered best practice to work with "unobtrusive" JavaScript. It's a development pattern that defines two requirements:
- A strict separation between structure and behaviors.
- If the code breaks, the content and the basic functionalities must remain accessible and usable.
[The principles of unobtrusive JavaScript](https://www.w3.org/wiki/The_principles_of_unobtrusive_JavaScript) (originally written by Peter-Paul Koch for Dev.Opera.com) describes these ideas very well.
### Pay attention to performance
Even though some polyfills are very aware of performance, loading additional scripts can affect the performance of your application. This is especially critical with legacy browsers; many of them have a very slow JavaScript engine that can make the execution of all your polyfills painful for the user. Performance is a subject on its own, but legacy browsers are very sensitive to it: basically, they are slow and the more polyfills they need, the more JavaScript they have to process. So they are doubly burdened compared to modern browsers. Test your code with legacy browsers to see how they actually perform. Sometimes, dropping some functionality leads to a better user experience than having exactly the same functionality in all browsers. As a last reminder, just always think about the end users.
## Conclusion
As you can see, considering browser and operating system default form control appearance is important. There are many techniques to handle these issue; however mastering all of them is beyond the scope of this article. The basic premise is to consider whether altering the default implementation is worth the work before embarking on the challenge.
If you read all the articles of this [HTML Forms guide](/en-US/docs/Learn/Forms), you should now be at ease with using forms. If you discover new techniques or hints, please help improve the guide.
## See also
### Learning path
- [Your first HTML form](/en-US/docs/Learn/Forms/Your_first_form)
- [How to structure an HTML form](/en-US/docs/Learn/Forms/How_to_structure_a_web_form)
- [The native form widgets](/en-US/docs/Learn/Forms/Basic_native_form_controls)
- [HTML5 input types](/en-US/docs/Learn/Forms/HTML5_input_types)
- [Additional form controls](/en-US/docs/Learn/Forms/Other_form_controls)
- [UI pseudo-classes](/en-US/docs/Learn/Forms/UI_pseudo-classes)
- [Styling HTML forms](/en-US/docs/Learn/Forms/Styling_web_forms)
- [Form data validation](/en-US/docs/Learn/Forms/Form_validation)
- [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data)
### Advanced Topics
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [How to build custom form widgets](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- **HTML forms in legacy browsers**
- [Advanced styling for HTML forms](/en-US/docs/Learn/Forms/Advanced_form_styling)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/test_your_skills_colon__html5_controls/index.md | ---
title: "Test your skills: HTML5 controls"
slug: Learn/Forms/Test_your_skills:_HTML5_controls
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [The HTML5 input types](/en-US/docs/Learn/Forms/HTML5_input_types) article.
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## HTML controls 1
First, let's explore some input types. Create appropriate inputs for a user to update their details for:
1. Email
2. Website
3. Phone number
4. Favorite color
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/html/forms/tasks/html5-controls/html5-controls1.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/html5-controls/html5-controls1-download.html) to work in your own editor or in an online editor.
## HTML controls 2
Next, we want you to implement a slider control to allow the user to choose a maximum number of people to invite to their party.
1. Implement a basic slider control to go along with the provided label.
2. Give it a minimum value of 1, maximum value of 30, initial value of 10 and element `id` of `max-invite`.
3. Create a corresponding output element to put the current value of the slider into. Give it a class of `invite-output`, and semantically associate it with the input. If you do this correctly, the JavaScript included on the page will automatically update the output value when the slider is moved.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/html/forms/tasks/html5-controls/html5-controls2.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/html5-controls/html5-controls2-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/basic_native_form_controls/index.md | ---
title: Basic native form controls
slug: Learn/Forms/Basic_native_form_controls
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms/HTML5_input_types", "Learn/Forms")}}
In the [previous article](/en-US/docs/Learn/Forms/How_to_structure_a_web_form), we marked up a functional web form example, introducing some form controls and common structural elements, and focusing on accessibility best practices. Next, we will look at the functionality of the different form controls, or widgets, in detail — studying all the different options available to collect different types of data. In this particular article, we will look at the original set of form controls, available in all browsers since the early days of the web.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>understanding of HTML</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand in detail the original set of native form widgets
available in browsers for collecting data, and how to implement them
using HTML.
</td>
</tr>
</tbody>
</table>
You've already met some form elements, including {{HTMLelement('form')}}, {{HTMLelement('fieldset')}}, {{HTMLelement('legend')}}, {{HTMLelement('textarea')}}, {{HTMLelement('label')}}, {{HTMLelement('button')}}, and {{HTMLelement('input')}}. This article covers:
- The common input types {{HTMLelement('input/button', 'button')}}, {{HTMLelement('input/checkbox', 'checkbox')}}, {{HTMLelement('input/file', 'file')}}, {{HTMLelement('input/hidden', 'hidden')}}, {{HTMLelement('input/image', 'image')}}, {{HTMLelement('input/password', 'password')}}, {{HTMLelement('input/radio', 'radio')}}, {{HTMLelement('input/reset', 'reset')}}, {{HTMLelement('input/submit', 'submit')}}, and {{HTMLelement('input/text', 'text')}}.
- Some of the attributes that are common to all form controls.
> **Note:** We cover additional, more powerful form controls in the next two articles. If you want a more advanced reference, you should consult our [HTML forms element reference](/en-US/docs/Web/HTML/Element#forms), and in particular our extensive [`<input>` types](/en-US/docs/Web/HTML/Element/input) reference.
## Text input fields
Text {{htmlelement("input")}} fields are the most basic form widgets. They are a very convenient way to let the user enter any kind of data, and we've already seen a few simple examples.
> **Note:** HTML form text fields are simple plain text input controls. This means that you cannot use them to perform rich text editing (bold, italic, etc.). All rich text editors you'll encounter are custom widgets created with HTML, CSS, and JavaScript.
All basic text controls share some common behaviors:
- They can be marked as [`readonly`](/en-US/docs/Web/HTML/Element/input#readonly) (the user cannot modify the input value but it is still sent with the rest of the form data) or [`disabled`](/en-US/docs/Web/HTML/Element/input#disabled) (the input value can't be modified and is never sent with the rest of the form data).
- They can have a [`placeholder`](/en-US/docs/Web/HTML/Element/input#placeholder); this is the text that appears inside the text input box that should be used to briefly describe the purpose of the box.
- They can be constrained in [`size`](/en-US/docs/Web/HTML/Attributes/size) (the physical size of the box) and [`maxlength`](/en-US/docs/Web/HTML/Attributes/maxlength) (the maximum number of characters that can be entered into the box).
- They can benefit from spell checking (using the [`spellcheck`](/en-US/docs/Web/HTML/Global_attributes/spellcheck) attribute), if the browser supports it.
> **Note:** The {{htmlelement("input")}} element is unique amongst HTML elements because it can take many forms depending on its [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute value. It is used for creating most types of form widgets including single line text fields, time and date controls, controls without text input like checkboxes, radio buttons, and color pickers, and buttons.
### Single line text fields
A single line text field is created using an {{HTMLElement("input")}} element whose [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute value is set to `text`, or by omitting the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute altogether (`text` is the default value). The value `text` for this attribute is also the fallback value if the value you specify for the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute is unknown by the browser (for example if you specify `type="color"` and the browser doesn't support native color pickers).
> **Note:** You can find examples of all the single line text field types on GitHub at [single-line-text-fields.html](https://github.com/mdn/learning-area/blob/main/html/forms/native-form-widgets/single-line-text-fields.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/native-form-widgets/single-line-text-fields.html)).
Here is a basic single line text field example:
```html
<input type="text" id="comment" name="comment" value="I'm a text field" />
```
Single line text fields have only one true constraint: if you type text with line breaks, the browser removes those line breaks before sending the data to the server.
The screenshot below shows a text input in default, focused, and disabled states. Most browsers indicate the focused state using a focus ring around the control and the disabled state using grey text or a faded/semi-opaque control.

The screenshots used in this document were taken in the Chrome browser on macOS. There may be minor variations in these fields/buttons across different browsers, but the basic highlighting technique remains similar.
> **Note:** We discuss values for the [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute that enforce specific validation constraints including color, email, and url input types, in the next article, [The HTML5 input types](/en-US/docs/Learn/Forms/HTML5_input_types).
#### Password field
One of the original input types was the `password` text field type:
```html
<input type="password" id="pwd" name="pwd" />
```
The following screenshot shows Password input field in which each input character is shown as a dot.

The `password` value doesn't add any special constraints to the entered text, but it does obscure the value entered into the field (e.g. with dots or asterisks) so it can't be easily read by others.
Keep in mind this is just a user interface feature; unless you submit your form securely, it will get sent in plain text, which is bad for security — a malicious party could intercept your data and steal passwords, credit card details, or whatever else you've submitted. The best way to protect users from this is to host any pages involving forms over a secure connection (i.e. located at an `https://` address), so the data is encrypted before it is sent.
Browsers recognize the security implications of sending form data over an insecure connection, and have warnings to deter users from using insecure forms. For more information on what Firefox implements, see [Insecure passwords](/en-US/docs/Web/Security/Insecure_passwords).
### Hidden content
Another original text control is the `hidden` input type. This is used to create a form control that is invisible to the user, but is still sent to the server along with the rest of the form data once submitted — for example you might want to submit a timestamp to the server stating when an order was placed. Because it is hidden, the user can not see nor intentionally edit the value, it will never receive focus, and a screen reader will not notice it either.
```html
<input type="hidden" id="timestamp" name="timestamp" value="1286705410" />
```
If you create such an element, it's required to set its `name` and `value` attributes. The value can be dynamically set via JavaScript. The `hidden` input type should not have an associated label.
Other text input types, like {{HTMLElement("input/search", "search")}}, {{HTMLElement("input/url", "url")}}, and {{HTMLElement("input/tel", "tel")}}, will be covered in the next tutorial, [HTML5 input types](/en-US/docs/Learn/Forms/HTML5_input_types).
## Checkable items: checkboxes and radio buttons
Checkable items are controls whose state you can change by clicking on them or their associated labels. There are two kinds of checkable items: the checkbox and the radio button. Both use the [`checked`](/en-US/docs/Web/HTML/Element/input/checkbox#checked) attribute to indicate whether the widget is checked by default or not.
It's worth noting that these widgets do not behave exactly like other form widgets. For most form widgets, once the form is submitted all widgets that have a [`name`](/en-US/docs/Web/HTML/Element/input#name) attribute are sent, even if no value has been filled out. In the case of checkable items, their values are sent only if they are checked. If they are not checked, nothing is sent, not even their name. If they are checked but have no value, the name is sent with a value of _on._
> **Note:** You can find the examples from this section on GitHub as [checkable-items.html](https://github.com/mdn/learning-area/blob/main/html/forms/native-form-widgets/checkable-items.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/native-form-widgets/checkable-items.html)).
For maximum usability/accessibility, you are advised to surround each list of related items in a {{htmlelement("fieldset")}}, with a {{htmlelement("legend")}} providing an overall description of the list. Each individual pair of {{htmlelement("label")}}/{{htmlelement("input")}} elements should be contained in its own list item (or similar). The associated {{htmlelement('label')}} is generally placed immediately before or after the radio button or checkbox, with the instructions for the group of radio button or checkboxes generally being the content of the {{htmlelement("legend")}}. See the examples linked above for structural examples.
### Checkbox
A checkbox is created using the {{HTMLElement("input")}} element with a [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute set to the value {{HTMLElement("input/checkbox", "checkbox")}}.
```html
<input type="checkbox" id="questionOne" name="subscribe" value="yes" checked />
```
Related checkbox items should use the same [`name`](/en-US/docs/Web/HTML/Element/input#name) attribute. Including the [`checked`](/en-US/docs/Web/HTML/Element/input/checkbox#checked) attribute makes the checkbox checked automatically when the page loads. Clicking the checkbox or its associated label toggles the checkbox on and off.
```html
<fieldset>
<legend>Choose all the vegetables you like to eat</legend>
<ul>
<li>
<label for="carrots">Carrots</label>
<input
type="checkbox"
id="carrots"
name="vegetable"
value="carrots"
checked />
</li>
<li>
<label for="peas">Peas</label>
<input type="checkbox" id="peas" name="vegetable" value="peas" />
</li>
<li>
<label for="cabbage">Cabbage</label>
<input type="checkbox" id="cabbage" name="vegetable" value="cabbage" />
</li>
</ul>
</fieldset>
```
The following screenshot shows checkboxes in the default, focused, and disabled states. Checkboxes in the default and disabled states appear checked, whereas in the focused state, the checkbox is unchecked, with focus ring around it.

> **Note:** Any checkboxes and radio buttons with the [`checked`](/en-US/docs/Web/HTML/Element/input/checkbox#checked) attribute on load match the {{cssxref(':default')}} pseudo-class, even if they are no longer checked. Any that are currently checked match the {{cssxref(':checked')}} pseudo-class.
Due to the on-off nature of checkboxes, the checkbox is considered a toggle button, with many developers and designers expanding on the default checkbox styling to create buttons that look like toggle switches. You can [see an example in action here](https://mdn.github.io/learning-area/html/forms/toggle-switch-example/) (also see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/toggle-switch-example/index.html)).
### Radio button
A radio button is created using the {{HTMLElement("input")}} element with its [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute set to the value `radio`:
```html
<input type="radio" id="soup" name="meal" value="soup" checked />
```
Several radio buttons can be tied together. If they share the same value for their [`name`](/en-US/docs/Web/HTML/Element/input#name) attribute, they will be considered to be in the same group of buttons. Only one button in a given group may be checked at a time; this means that when one of them is checked all the others automatically get unchecked. When the form is sent, only the value of the checked radio button is sent. If none of them are checked, the whole pool of radio buttons is considered to be in an unknown state and no value is sent with the form. Once one of the radio buttons in a same-named group of buttons is checked, it is not possible for the user to uncheck all the buttons without resetting the form.
```html
<fieldset>
<legend>What is your favorite meal?</legend>
<ul>
<li>
<label for="soup">Soup</label>
<input type="radio" id="soup" name="meal" value="soup" checked />
</li>
<li>
<label for="curry">Curry</label>
<input type="radio" id="curry" name="meal" value="curry" />
</li>
<li>
<label for="pizza">Pizza</label>
<input type="radio" id="pizza" name="meal" value="pizza" />
</li>
</ul>
</fieldset>
```
The following screenshot shows default and disabled radio buttons in the checked state, along with focused a radio button in the unchecked state.

## Actual buttons
The radio button isn't actually a button, despite its name; let's move on and look at actual buttons! There are three input types that produce buttons:
- `submit`
- : Sends the form data to the server. For {{HTMLElement("button")}} elements, omitting the `type` attribute (or an invalid value of `type`) results in a submit button.
- `reset`
- : Resets all form widgets to their default values.
- `button`
- : Buttons that have no automatic effect but can be customized using JavaScript code.
Then we also have the {{htmlelement("button")}} element itself. This can take a `type` attribute of value `submit`, `reset`, or `button` to mimic the behavior of the three `<input>` types mentioned above. The main difference between the two is that actual `<button>` elements are much easier to style.
```html
<input type="submit" value="Submit this form" />
<input type="reset" value="Reset this form" />
<input type="button" value="Do Nothing without JavaScript" />
<button type="submit">Submit this form</button>
<button type="reset">Reset this form</button>
<button type="button">Do Nothing without JavaScript</button>
```
```html hidden
<div class="buttondemo">
<p>Using <input></p>
<p>
<input type="submit" value="Submit this form" />
<input type="reset" value="Reset this form" />
<input type="button" value="Do Nothing without JavaScript" />
</p>
<p>Using <button></p>
<p>
<button type="submit">Submit this form</button>
<button type="reset">Reset this form</button>
<button type="button">Do Nothing without JavaScript</button>
</p>
</div>
```
```css hidden
button,
input {
display: none;
}
.buttondemo button,
.buttondemo input {
all: revert;
}
```
{{ EmbedLiveSample('Actual_buttons', '500', '250') }}
> **Note:** The `image` input type also renders as a button. We'll cover that later too.
> **Note:** You can find the examples from this section on GitHub as [button-examples.html](https://github.com/mdn/learning-area/blob/main/html/forms/native-form-widgets/button-examples.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/native-form-widgets/button-examples.html)).
Below you can find examples of each button `<input>` type, along with the equivalent `<button>` type.
### submit
```html
<button type="submit">This is a <strong>submit button</strong></button>
<input type="submit" value="This is a submit button" />
```
### reset
```html
<button type="reset">This is a <strong>reset button</strong></button>
<input type="reset" value="This is a reset button" />
```
### anonymous
```html
<button type="button">This is an <strong>anonymous button</strong></button>
<input type="button" value="This is an anonymous button" />
```
Buttons always behave the same whether you use a {{HTMLElement("button")}} element or an {{HTMLElement("input")}} element. As you can see from the examples, however, {{HTMLElement("button")}} elements let you use HTML in their content, which is inserted between the opening and closing `<button>` tags. {{HTMLElement("input")}} elements on the other hand are {{glossary("void element", "void elements")}}; their displayed content is inserted inside the `value` attribute, and therefore only accepts plain text as content.
The following screenshot shows a button in the default, focused, and disabled states. In the focused state, there is a focus ring around the button, and in the disabled state, the button is greyed out.

### Image button
The **image button** control is rendered exactly like an {{HTMLElement("img")}} element, except that when the user clicks on it, it behaves like a submit button.
An image button is created using an {{HTMLElement("input")}} element with its [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute set to the value `image`. This element supports exactly the same set of attributes as the {{HTMLElement("img")}} element, plus all the attributes supported by other form buttons.
```html
<input type="image" alt="Click me!" src="my-img.png" width="80" height="30" />
```
If the image button is used to submit the form, this control doesn't submit its value — instead, the X and Y coordinates of the click on the image are submitted (the coordinates are relative to the image, meaning that the upper-left corner of the image represents the coordinate (0, 0)). The coordinates are sent as two key/value pairs:
- The X value key is the value of the [`name`](/en-US/docs/Web/HTML/Element/input#name) attribute followed by the string "_.x_".
- The Y value key is the value of the [`name`](/en-US/docs/Web/HTML/Element/input#name) attribute followed by the string "_.y_".
So for example when you click on the image at coordinate (123, 456) and it submits via the `get` method, you'll see the values appended to the URL as follows:
```url
http://foo.com?pos.x=123&pos.y=456
```
This is a very convenient way to build a "hot map". How these values are sent and retrieved is detailed in the [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data) article.
## File picker
There is one last `<input>` type that came to us in early HTML: the file input type. Forms are able to send files to a server (this specific action is also detailed in the [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data) article). The file picker widget can be used to choose one or more files to send.
To create a [file picker widget](/en-US/docs/Web/HTML/Element/input/file), you use the {{HTMLElement("input")}} element with its [`type`](/en-US/docs/Web/HTML/Element/input#type) attribute set to `file`. The types of files that are accepted can be constrained using the [`accept`](/en-US/docs/Web/HTML/Element/input#accept) attribute. In addition, if you want to let the user pick more than one file, you can do so by adding the [`multiple`](/en-US/docs/Web/HTML/Element/input#multiple) attribute.
### Example
In this example, a file picker is created that requests graphic image files. The user is allowed to select multiple files in this case.
```html
<input type="file" name="file" id="file" accept="image/*" multiple />
```
On some mobile devices, the file picker can access photos, videos, and audio captured directly by the device's camera and microphone by adding capture information to the `accept` attribute like so:
```html
<input type="file" accept="image/*;capture=camera" />
<input type="file" accept="video/*;capture=camcorder" />
<input type="file" accept="audio/*;capture=microphone" />
```
The following screenshot shows the file picker widget in the default, focus, and disabled states when no file is selected.

## Common attributes
Many of the elements used to define form controls have some of their own specific attributes. However, there is a set of attributes common to all form elements. You've met some of these already, but below is a list of those common attributes, for your reference:
<table class="no-markdown">
<thead>
<tr>
<th scope="col">Attribute name</th>
<th scope="col">Default value</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code
><a href="/en-US/docs/Web/HTML/Global_attributes/autofocus"
>autofocus</a
></code
>
</td>
<td>false</td>
<td>
This Boolean attribute lets you specify that the element should
automatically have input focus when the page loads. Only one
form-associated element in a document can have this attribute specified.
</td>
</tr>
<tr>
<td>
<code
><a href="/en-US/docs/Web/HTML/Attributes/disabled">disabled</a></code
>
</td>
<td>false</td>
<td>
This Boolean attribute indicates that the user cannot interact with the
element. If this attribute is not specified, the element inherits its
setting from the containing element, for example,
{{HTMLElement("fieldset")}}; if there is no containing element
with the <code>disabled</code> attribute set, then the element is
enabled.
</td>
</tr>
<tr>
<td>
<code><a href="/en-US/docs/Web/HTML/Element/form">form</a></code>
</td>
<td></td>
<td>
The <code><form></code> element that the widget is associated with,
used if it is not nested within that form. The value of the attribute
must be the <code>id</code> attribute of a
{{HTMLElement("form")}} element in the same document. This lets
you associate a form control with a form it is outside of, even if it is
inside a different form element.
</td>
</tr>
<tr>
<td>
<code><a href="/en-US/docs/Web/HTML/Element/input#name">name</a></code>
</td>
<td></td>
<td>The name of the element; this is submitted with the form data.</td>
</tr>
<tr>
<td>
<code><a href="/en-US/docs/Web/HTML/Element/input#value">value</a></code>
</td>
<td></td>
<td>The element's initial value.</td>
</tr>
</tbody>
</table>
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Basic controls](/en-US/docs/Learn/Forms/Test_your_skills:_Basic_controls).
## Summary
This article has covered the older input types — the original set introduced in the early days of HTML that is well-supported in all browsers. In the next section, we'll take a look at the more modern values of the `type` attribute.
{{PreviousMenuNext("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms/HTML5_input_types", "Learn/Forms")}}
### Advanced Topics
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/sending_and_retrieving_form_data/index.md | ---
title: Sending form data
slug: Learn/Forms/Sending_and_retrieving_form_data
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenu("Learn/Forms/Form_validation", "Learn/Forms")}}
Once the form data has been validated on the client-side, it is okay to submit the form. And, since we covered validation in the previous article, we're ready to submit! This article looks at what happens when a user submits a form — where does the data go, and how do we handle it when it gets there? We also look at some of the security concerns associated with sending form data.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
An
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>understanding of HTML</a
>, and basic knowledge of
<a href="/en-US/docs/Web/HTTP/Basics_of_HTTP">HTTP</a> and
<a href="/en-US/docs/Learn/Server-side/First_steps"
>server-side programming</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand what happens when form data is submitted, including
getting a basic idea of how data is processed on the server.
</td>
</tr>
</tbody>
</table>
First, we'll discuss what happens to the data when a form is submitted.
## Client/server architecture
At its most basic, the web uses a client/server architecture that can be summarized as follows: a client (usually a web browser) sends a request to a server (most of the time a web server like [Apache](https://httpd.apache.org/), [Nginx](https://nginx.org/), [IIS](https://www.iis.net/), [Tomcat](https://tomcat.apache.org/), etc.), using the [HTTP protocol](/en-US/docs/Web/HTTP). The server answers the request using the same protocol.

An HTML form on a web page is nothing more than a convenient user-friendly way to configure an HTTP request to send data to a server. This enables the user to provide information to be delivered in the HTTP request.
> **Note:** To get a better idea of how client-server architectures work, read our [Server-side website programming first steps](/en-US/docs/Learn/Server-side/First_steps) module.
## On the client side: defining how to send the data
The {{HTMLElement("form")}} element defines how the data will be sent. All of its attributes are designed to let you configure the request to be sent when a user hits a {{Glossary("submit button")}}. The two most important attributes are [`action`](/en-US/docs/Web/HTML/Element/form#action) and [`method`](/en-US/docs/Web/HTML/Element/form#method).
### The action attribute
The [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute defines where the data gets sent. Its value must be a valid relative or absolute [URL](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL). If this attribute isn't provided, the data will be sent to the URL of the page containing the form — the current page.
In this example, the data is sent to an absolute URL — `https://example.com`:
```html
<form action="https://example.com">…</form>
```
Here, we use a relative URL — the data is sent to a different URL on the same origin:
```html
<form action="/somewhere_else">…</form>
```
When specified with no attributes, as below, the {{HTMLElement("form")}} data is sent to the same page that the form is present on:
```html
<form>…</form>
```
> **Note:** It's possible to specify a URL that uses the HTTPS (secure HTTP) protocol. When you do this, the data is encrypted along with the rest of the request, even if the form itself is hosted on an insecure page accessed using HTTP. On the other hand, if the form is hosted on a secure page but you specify an insecure HTTP URL with the [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute, all browsers display a security warning to the user each time they try to send data because the data will not be encrypted.
The names and values of the non-file form controls are sent to the server as `name=value` pairs joined with ampersands. The `action` value should be a file on the server that can handle the incoming data, including ensuring server-side validation. The server then responds, generally handling the data and loading the URL defined by the `action` attribute, causing a new page load (or a refresh of the existing page, if the `action` points to the same page).
How the data is sent depends on the `method` attribute.
### The method attribute
The [`method`](/en-US/docs/Web/HTML/Element/form#method) attribute defines how data is sent. The [HTTP protocol](/en-US/docs/Web/HTTP) provides several ways to perform a request; HTML form data can be transmitted via a number of different methods, the most common being the `GET` method and the `POST` method
To understand the difference between those two methods, let's step back and examine [how HTTP works](/en-US/docs/Web/HTTP/Overview). Each time you want to reach a resource on the Web, the browser sends a request to a URL. An HTTP request consists of two parts: a [header](/en-US/docs/Web/HTTP/Headers) that contains a set of global metadata about the browser's capabilities, and a body that can contain information necessary for the server to process the specific request.
#### The GET method
The [`GET` method](/en-US/docs/Web/HTTP/Methods/GET) is the method used by the browser to ask the server to send back a given resource: "Hey server, I want to get this resource." In this case, the browser sends an empty body. Because the body is empty, if a form is sent using this method the data sent to the server is appended to the URL.
Consider the following form:
```html
<form action="http://www.foo.com" method="GET">
<div>
<label for="say">What greeting do you want to say?</label>
<input name="say" id="say" value="Hi" />
</div>
<div>
<label for="to">Who do you want to say it to?</label>
<input name="to" id="to" value="Mom" />
</div>
<div>
<button>Send my greetings</button>
</div>
</form>
```
Since the `GET` method has been used, you'll see the URL `www.foo.com/?say=Hi&to=Mom` appear in the browser address bar when you submit the form.

The data is appended to the URL as a series of name/value pairs. After the URL web address has ended, we include a question mark (`?`) followed by the name/value pairs, each one separated by an ampersand (`&`). In this case, we are passing two pieces of data to the server:
- `say`, which has a value of `Hi`
- `to`, which has a value of `Mom`
The HTTP request looks like this:
```http
GET /?say=Hi&to=Mom HTTP/2.0
Host: foo.com
```
> **Note:** You can find this example on GitHub — see [get-method.html](https://github.com/mdn/learning-area/blob/main/html/forms/sending-form-data/get-method.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/sending-form-data/get-method.html)).
#### The POST method
The [`POST` method](/en-US/docs/Web/HTTP/Methods/POST) is a little different. It's the method the browser uses to talk to the server when asking for a response that takes into account the data provided in the body of the HTTP request: "Hey server, take a look at this data and send me back an appropriate result." If a form is sent using this method, the data is appended to the body of the HTTP request.
Let's look at an example — this is the same form we looked at in the `GET` section above, but with the [`method`](/en-US/docs/Web/HTML/Element/form#method) attribute set to `POST`.
```html
<form action="http://www.foo.com" method="POST">
<div>
<label for="say">What greeting do you want to say?</label>
<input name="say" id="say" value="Hi" />
</div>
<div>
<label for="to">Who do you want to say it to?</label>
<input name="to" id="to" value="Mom" />
</div>
<div>
<button>Send my greetings</button>
</div>
</form>
```
When the form is submitted using the `POST` method, you get no data appended to the URL, and the HTTP request looks like so, with the data included in the request body instead:
```http
POST / HTTP/2.0
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
say=Hi&to=Mom
```
The `Content-Length` header indicates the size of the body, and the `Content-Type` header indicates the type of resource sent to the server. We'll discuss these headers later on.
> **Note:** You can find this example on GitHub — see [post-method.html](https://github.com/mdn/learning-area/blob/main/html/forms/sending-form-data/post-method.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/sending-form-data/post-method.html)).
### Viewing HTTP requests
HTTP requests are never displayed to the user (if you want to see them, you need to use tools such as the [Firefox Network Monitor](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/index.html) or the [Chrome Developer Tools](https://developer.chrome.com/docs/devtools/)). As an example, your form data will be shown as follows in the Chrome Network tab. After submitting the form:
1. Open the developer tools.
2. Select "Network"
3. Select "All"
4. Select "foo.com" in the "Name" tab
5. Select "Headers"
You can then get the form data, as shown in the image below.

The only thing displayed to the user is the URL called. As we mentioned above, with a `GET` request the user will see the data in their URL bar, but with a `POST` request they won't. This can be very important for two reasons:
1. If you need to send a password (or any other sensitive piece of data), never use the `GET` method or you risk displaying it in the URL bar, which would be very insecure.
2. If you need to send a large amount of data, the `POST` method is preferred because some browsers limit the sizes of URLs. In addition, many servers limit the length of URLs they accept.
## On the server side: retrieving the data
Whichever HTTP method you choose, the server receives a string that will be parsed in order to get the data as a list of key/value pairs. The way you access this list depends on the development platform you use and on any specific frameworks you may be using with it.
### Example: Raw PHP
[PHP](https://www.php.net/) offers some global objects to access the data. Assuming you've used the `POST` method, the following example just takes the data and displays it to the user. Of course, what you do with the data is up to you. You might display it, store it in a database, send it by email, or process it in some other way.
```php
<?php
// The global $_POST variable allows you to access the data sent with the POST method by name
// To access the data sent with the GET method, you can use $_GET
$say = htmlspecialchars($_POST['say']);
$to = htmlspecialchars($_POST['to']);
echo $say, ' ', $to;
?>
```
This example displays a page with the data we sent. You can see this in action in our example [php-example.html](https://github.com/mdn/learning-area/blob/main/html/forms/sending-form-data/php-example.html) file — which contains the same example form as we saw before, with a `method` of `POST` and an `action` of `php-example.php`. When it is submitted, it sends the form data to [php-example.php](https://github.com/mdn/learning-area/blob/main/html/forms/sending-form-data/php-example.php), which contains the PHP code seen in the above block. When this code is executed, the output in the browser is `Hi Mom`.

> **Note:** This example won't work when you load it into a browser locally — browsers cannot interpret PHP code, so when the form is submitted the browser will just offer to download the PHP file for you. To get it to work, you need to run the example through a PHP server of some kind. Good options for local PHP testing are [MAMP](https://www.mamp.info/en/downloads/) (Mac and Windows) and [AMPPS](https://ampps.com/downloads/) (Mac, Windows, Linux).
>
> Note also that if you are using MAMP but don't have MAMP Pro installed (or if the MAMP Pro demo time trial has expired), you might have trouble getting it working. To get it working again, we have found that you can load up the MAMP app, then choose the menu options _MAMP_ > _Preferences_ > _PHP_, and set "Standard Version:" to "7.2.x" (x will differ depending on what version you have installed).
### Example: Python
This example shows how you would use Python to do the same thing — display the submitted data on a web page. This uses the [Flask framework](https://flask.palletsprojects.com/) for rendering the templates, handling the form data submission, etc. (see [python-example.py](https://github.com/mdn/learning-area/blob/main/html/forms/sending-form-data/python-example.py)).
```python
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def form():
return render_template('form.html')
@app.route('/hello', methods=['GET', 'POST'])
def hello():
return render_template('greeting.html', say=request.form['say'], to=request.form['to'])
if __name__ == "__main__":
app.run()
```
The two templates referenced in the above code are as follows (these need to be in a subdirectory called `templates` in the same directory as the `python-example.py` file, if you try to run the example yourself):
- [form.html](https://github.com/mdn/learning-area/blob/main/html/forms/sending-form-data/templates/form.html): The same form as we saw above in [The POST method](#the_post_method) section but with the `action` set to `\{{ url_for('hello') }}`. This is a [Jinja](https://jinja.palletsprojects.com) template, which is basically HTML but can contain calls to the Python code that is running the web server contained in curly braces. `url_for('hello')` is basically saying "redirect to `/hello` when the form is submitted".
- [greeting.html](https://github.com/mdn/learning-area/blob/main/html/forms/sending-form-data/templates/greeting.html): This template just contains a line that renders the two bits of data passed to it when it is rendered. This is done via the `hello()` function seen above, which runs when the `/hello` URL is navigated to.
> **Note:** Again, this code won't work if you just try to load it into a browser directly. Python works a bit differently from PHP — to run this code locally you'll need to [install Python/PIP](/en-US/docs/Learn/Server-side/Django/development_environment#installing_python_3), then install Flask using `pip3 install flask`. At this point, you should be able to run the example using `python3 python-example.py`, then navigate to `localhost:5042` in your browser.
### Other languages and frameworks
There are many other server-side technologies you can use for form handling, including Perl, Java, .Net, Ruby, etc. Just pick the one you like best. That said, it's worth noting that it's very uncommon to use these technologies directly because this can be tricky. It's more common to use one of the many high quality frameworks that make handling forms easier, such as:
- Python
- [Django](/en-US/docs/Learn/Server-side/Django)
- [Flask](https://flask.palletsprojects.com/)
- [web2py](https://github.com/web2py/web2py) (easiest to get started with)
- [py4web](https://py4web.com/) (written by the same develops as web2py, has a more Django-like setup)
- Node.js
- [Express](/en-US/docs/Learn/Server-side/Express_Nodejs)
- [Next.js](https://nextjs.org/) (for React apps)
- [Nuxt](https://nuxt.com/) (for Vue apps)
- [Remix](https://remix.run/)
- PHP
- [Laravel](https://laravel.com/)
- [Laminas](https://getlaminas.org/) (formerly Zend Framework)
- [Symfony](https://symfony.com/)
- Ruby
- [Ruby On Rails](https://rubyonrails.org/)
- Java
- [Spring Boot](https://spring.io/guides/gs/handling-form-submission/)
It's worth noting that even using these frameworks, working with forms isn't necessarily _easy_. But it's much easier than trying to write all the functionality yourself from scratch, and will save you a lot of time.
> **Note:** It is beyond the scope of this article to teach you any server-side languages or frameworks. The links above will give you some help, should you wish to learn them.
## A special case: sending files
Sending files with HTML forms is a special case. Files are binary data — or considered as such — whereas all other data is text data. Because HTTP is a text protocol, there are special requirements for handling binary data.
### The enctype attribute
This attribute lets you specify the value of the `Content-Type` HTTP header included in the request generated when the form is submitted. This header is very important because it tells the server what kind of data is being sent. By default, its value is `application/x-www-form-urlencoded`. In human terms, this means: "This is form data that has been encoded into URL parameters."
If you want to send files, you need to take three extra steps:
- Set the [`method`](/en-US/docs/Web/HTML/Element/form#method) attribute to `POST` because file content can't be put inside URL parameters.
- Set the value of [`enctype`](/en-US/docs/Web/HTML/Element/form#enctype) to `multipart/form-data` because the data will be split into multiple parts, one for each file plus one for the text data included in the form body (if the text is also entered into the form).
- Include one or more [`<input type="file">`](/en-US/docs/Web/HTML/Element/input/file) controls to allow your users to select the file(s) that will be uploaded.
For example:
```html
<form method="post" action="https://www.foo.com" enctype="multipart/form-data">
<div>
<label for="file">Choose a file</label>
<input type="file" id="file" name="myFile" />
</div>
<div>
<button>Send the file</button>
</div>
</form>
```
> **Note:** Servers can be configured with a size limit for files and HTTP requests in order to prevent abuse.
## Security issues
Each time you send data to a server, you need to consider security. HTML forms are by far the most common server attack vectors (places where attacks can occur). The problems never come from the HTML forms themselves — they come from how the server handles data.
The [Website security](/en-US/docs/Learn/Server-side/First_steps/Website_security) article of our [server-side](/en-US/docs/Learn/Server-side) learning topic discusses several common attacks and potential defenses against them in detail. You should go and check that article out, to get an idea of what's possible.
### Be paranoid: Never trust your users
So, how do you fight these threats? This is a topic far beyond this guide, but there are a few rules to keep in mind. The most important rule is: never ever trust your users, including yourself; even a trusted user could have been hijacked.
All data that comes to your server must be checked and sanitized. Always. No exception.
- **Escape potentially dangerous characters**. The specific characters you should be cautious with vary depending on the context in which the data is used and the server platform you employ, but all server-side languages have functions for this. Things to watch out for are character sequences that look like executable code (such as [JavaScript](/en-US/docs/Learn/JavaScript) or [SQL](https://en.wikipedia.org/wiki/SQL) commands).
- **Limit the incoming amount of data to allow only what's necessary**.
- **Sandbox uploaded files**. Store them on a different server and allow access to the file only through a different subdomain or even better through a completely different domain.
You should be able to avoid many/most problems if you follow these three rules, but it's always a good idea to get a security review performed by a competent third party. Don't assume that you've seen all the possible problems.
## Summary
As we'd alluded to above, sending form data is easy, but securing an application can be tricky. Just remember that a front-end developer is not the one who should define the security model of the data. It's possible to perform [client-side form validation](/en-US/docs/Learn/Forms/Form_validation), but the server can't trust this validation because it has no way to truly know what has really happened on the client-side.
If you've worked your way through these tutorials in order, you now know how to markup and style a form, do client-side validation, and have some idea about submitting a form.
## See also
If you want to learn more about securing a web application, you can dig into these resources:
- [Server-side website programming first steps](/en-US/docs/Learn/Server-side/First_steps)
- [The Open Web Application Security Project (OWASP)](https://owasp.org/)
- [Web Security by Mozilla](https://infosec.mozilla.org/guidelines/web_security)
{{PreviousMenu("Learn/Forms/Form_validation", "Learn/Forms")}}
### Advanced Topics
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/sending_forms_through_javascript/index.md | ---
title: Sending forms through JavaScript
slug: Learn/Forms/Sending_forms_through_JavaScript
page-type: learn-module-chapter
---
{{LearnSidebar}}
When a user submits an HTML form, for example by clicking the {{glossary("Submit_button", "submit button")}}, the browser makes an [HTTP](/en-US/docs/Web/HTTP) request to send the data in the form. But instead of this declarative approach, web apps sometimes use JavaScript APIs such as {{domxref("fetch()")}} to send data programmatically to an endpoint that expects a form submission. This article explains why this is an important use case and how to do it.
## Why use JavaScript to submit form data?
Standard HTML form submission, as described in our article on [sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data), loads the URL where the data was sent, which means the browser window navigates with a full page load.
However, many web apps, especially {{glossary("progressive web apps")}} and {{glossary("SPA", "single-page apps")}}, use JavaScript APIs to request data from the server and update the relevant parts of the page, avoiding the overhead of a full page load.
For this reason, when these web apps want to submit form data, they use HTML forms only to collect input from the user, but not for data submission. When the user tries to send the data, the application takes control and sends the data using a JavaScript API such as {{domxref("fetch()")}}.
## The problem with JavaScript form submission
If the server endpoint to which the web app sends the form data is under the web app developer's control, then they can send the form data in any way they choose: for example, as a JSON object.
However, if the server endpoint is expecting a form submission, the web app must encode the data in a particular way. For example, if the data is just textual, it is made of URL-encoded lists of key/value pairs and sent with a {{httpheader("Content-Type")}} of `application/x-www-form-urlencoded`. If the form includes binary data, it must be sent using the `multipart/form-data` content type.
The {{domxref("FormData")}} interface takes care of the process of encoding data in this way, and in the rest of this article we'll provide a quick introduction to `FormData`. For more details, see our guide to [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects).
## Building a `FormData` object manually
You can populate a `FormData` object by calling the object's {{domxref("FormData.append()", "append()")}} method for each field you want to add, passing in the field's name and value. The value can be a string, for text fields, or a {{domxref("Blob")}}, for binary fields, including {{domxref("File")}} objects.
In the following example we send data as a form submission when the user clicks a button:
```js
async function sendData(data) {
// Construct a FormData instance
const formData = new FormData();
// Add a text field
formData.append("name", "Pomegranate");
// Add a file
const selection = await window.showOpenFilePicker();
if (selection.length > 0) {
const file = await selection[0].getFile();
formData.append("file", file);
}
try {
const response = await fetch("https://example.org/post", {
method: "POST",
// Set the FormData instance as the request body
body: formData,
});
console.log(await response.json());
} catch (e) {
console.error(e);
}
}
const send = document.querySelector("#send");
send.addEventListener("click", sendData);
```
1. We first construct a new, empty, `FormData` object.
2. Next, we call `append()` twice, to add two items to the `FormData` object: a text field and a file.
3. Finally, we make a {{httpmethod("POST")}} request using the `fetch()` API, setting the `FormData` object as the request body.
Note that we don't have to set the {{httpheader("Content-Type")}} header: the correct header is automatically set when we pass a `FormData` object into `fetch()`.
## Associating a `FormData` object and a `<form>`
If the data you're submitting is really coming from a {{htmlelement("form")}}, you can populate the `FormData` instance by passing the form into the `FormData` constructor.
Suppose our HTML declares a `<form>` element:
```html
<form id="userinfo">
<div>
<label for="username">Enter your name:</label>
<input type="text" id="username" name="username" value="Dominic" />
</div>
<div>
<label for="avatar">Select an avatar</label>
<input type="file" id="avatar" name="avatar" required />
</div>
<input type="submit" value="Submit" />
</form>
```
The form includes a text input, a file input, and a submit button.
The JavaScript is as follows:
```js
const form = document.querySelector("#userinfo");
async function sendData() {
// Associate the FormData object with the form element
const formData = new FormData(form);
try {
const response = await fetch("https://example.org/post", {
method: "POST",
// Set the FormData instance as the request body
body: formData,
});
console.log(await response.json());
} catch (e) {
console.error(e);
}
}
// Take over form submission
form.addEventListener("submit", (event) => {
event.preventDefault();
sendData();
});
```
We add a submit event handler for the form element. This first calls {{domxref("Event.preventDefault()", "preventDefault()")}} to prevent the browser's built-in form submission, so we can take over. Then we call `sendData()`, which retrieves the form element and passes it into the `FormData` constructor.
After that, we send the `FormData` instance as an HTTP `POST` request, using `fetch()`.
## See also
### Learning path
- [Your first HTML form](/en-US/docs/Learn/Forms/Your_first_form)
- [How to structure an HTML form](/en-US/docs/Learn/Forms/How_to_structure_a_web_form)
- [The native form widgets](/en-US/docs/Learn/Forms/Basic_native_form_controls)
- [HTML5 input types](/en-US/docs/Learn/Forms/HTML5_input_types)
- [Additional form controls](/en-US/docs/Learn/Forms/Other_form_controls)
- [UI pseudo-classes](/en-US/docs/Learn/Forms/UI_pseudo-classes)
- [Styling HTML forms](/en-US/docs/Learn/Forms/Styling_web_forms)
- [Form data validation](/en-US/docs/Learn/Forms/Form_validation)
- [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data)
### Advanced Topics
- **Sending forms through JavaScript**
- [How to build custom form widgets](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [HTML forms in legacy browsers](/en-US/docs/Learn/Forms/HTML_forms_in_legacy_browsers)
- [Advanced styling for HTML forms](/en-US/docs/Learn/Forms/Advanced_form_styling)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/other_form_controls/index.md | ---
title: Other form controls
slug: Learn/Forms/Other_form_controls
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Forms/HTML5_input_types","Learn/Forms/Styling_web_forms", "Learn/Forms")}}
We now look at the functionality of non-`<input>` form elements in detail, from other control types such as drop-down lists and multi-line text fields, to other useful form features such as the {{htmlelement('output')}} element (which we saw in action in the previous article), and progress bars.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>understanding of HTML</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the non-<code><input></code> form features, and how
to implement them using HTML.
</td>
</tr>
</tbody>
</table>
## Multi-line text fields
A multi-line text field is specified using a {{HTMLElement("textarea")}} element, rather than using the {{HTMLElement("input")}} element.
```html
<textarea cols="30" rows="8"></textarea>
```
This renders like so:
{{EmbedLiveSample("Multi-line_text_fields", 120, 160)}}
The main difference between a `<textarea>` and a regular single-line text field is that users are allowed to include hard line breaks (i.e. pressing return) that will be included when the data is submitted.
`<textarea>` also takes a closing tag; any default text you want it to contain should be put between the opening and closing tags. In contrast, the {{HTMLElement("input")}} is a {{glossary("void element")}} with no closing tag — any default value is put inside the [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute.
Note that even though you can put anything inside a `<textarea>` element (including other HTML elements, CSS, and JavaScript), because of its nature, it is all rendered as if it was plain text content. (Using [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) on non-form controls provides an API for capturing HTML/"rich" content instead of plain text).
Visually, the text entered wraps and the form control is by default resizable. Modern browsers provide a drag handle that you can drag to increase/decrease the size of the text area.
The following screenshots show default, focused, and disabled `<textarea>` elements in Firefox 71 and Safari 13 on macOS and in Edge 18, Yandex 14, Firefox 71, and Chrome 79 on Windows 10.

> **Note:** You can find a slightly more interesting example of text area usage in the [example](https://mdn.github.io/learning-area/html/forms/your-first-HTML-form/first-form-styled.html) we put together in the first article of the series ([see the source code also](https://github.com/mdn/learning-area/blob/main/html/forms/your-first-HTML-form/first-form-styled.html)).
### Controlling multi-line rendering
{{htmlelement("textarea")}} accepts three attributes to control its rendering across several lines:
- [`cols`](/en-US/docs/Web/HTML/Element/textarea#cols)
- : Specifies the visible width (columns) of the text control, measured in average character widths. This is effectively the starting width, as it can be changed by resizing the `<textarea>`, and overridden using CSS. The default value if none is specified is 20.
- [`rows`](/en-US/docs/Web/HTML/Element/textarea#rows)
- : Specifies the number of visible text rows for the control. This is effectively the starting height, as it can be changed by resizing the `<textarea>`, and overridden using CSS. The default value if none is specified is 2.
- [`wrap`](/en-US/docs/Web/HTML/Element/textarea#wrap)
- : Specifies how the control wraps text. The values are `soft` (the default value), which means the text submitted is not wrapped but the text rendered by the browser is wrapped; `hard` (the `cols` attribute must be specified when using this value), which means both the submitted and rendered texts are wrapped, and `off`, which stops wrapping.
### Controlling textarea resizability
The ability to resize a `<textarea>` is controlled with the CSS `resize` property. Its possible values are:
- `both`: The default — allows resizing horizontally and vertically.
- `horizontal`: Allows resizing only horizontally.
- `vertical`: Allows resizing only vertically.
- `none`: Allows no resizing.
- `block` and `inline`: Experimental values that allow resizing in the `block` or `inline` direction only (this varies depending on the directionality of your text; read [Handling different text directions](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions) if you want to find out more.)
Play with the interactive example at the top of the {{cssxref("resize")}} reference page for a demonstration of how these work.
## Drop-down controls
Drop-down controls are a simple way to let users select from many options without taking up much space in the user interface. HTML has two types of drop-down controls: the **select box** and the **autocomplete box**. The interaction is the same in both the types of drop-down controls — after the control is activated, the browser displays a list of values the user can select from.
> **Note:** You can find examples of all the drop-down box types on GitHub at [drop-down-content.html](https://github.com/mdn/learning-area/blob/main/html/forms/native-form-widgets/drop-down-content.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/native-form-widgets/drop-down-content.html)).
### Select box
A simple select box is created with a {{HTMLElement("select")}} element with one or more {{HTMLElement("option")}} elements as its children, each of which specifies one of its possible values.
#### Basic example
```html
<select id="simple" name="simple">
<option>Banana</option>
<option selected>Cherry</option>
<option>Lemon</option>
</select>
```
{{EmbedLiveSample("Basic_example", 120, 120)}}
If required, the default value for the select box can be set using the [`selected`](/en-US/docs/Web/HTML/Element/option#selected) attribute on the desired {{HTMLElement("option")}} element — this option is then preselected when the page loads.
#### Using optgroup
The {{HTMLElement("option")}} elements can be nested inside {{HTMLElement("optgroup")}} elements to create visually associated groups of values:
```html
<select id="groups" name="groups">
<optgroup label="fruits">
<option>Banana</option>
<option selected>Cherry</option>
<option>Lemon</option>
</optgroup>
<optgroup label="vegetables">
<option>Carrot</option>
<option>Eggplant</option>
<option>Potato</option>
</optgroup>
</select>
```
{{EmbedLiveSample("Using_optgroup", 120, 120)}}
On the {{HTMLElement("optgroup")}} element, the value of the [`label`](/en-US/docs/Web/HTML/Element/optgroup#label) attribute is displayed before the values of the nested options. The browser usually sets them visually apart from the options (i.e. by being bolded and at a different nesting level) so they are less likely to be confused for actual options.
#### Using the value attribute
If an {{HTMLElement("option")}} element has an explicit `value` attribute set on it, that value is sent when the form is submitted with that option selected. If the `value` attribute is omitted, as with the examples above, the content of the {{HTMLElement("option")}} element is used as the value. So `value` attributes are not needed, but you might find a reason to want to send a shortened or different value to the server than what is visually shown in the select box.
For example:
```html
<select id="simple" name="simple">
<option value="banana">Big, beautiful yellow banana</option>
<option value="cherry">Succulent, juicy cherry</option>
<option value="lemon">Sharp, powerful lemon</option>
</select>
```
By default, the height of the select box is enough to display a single value. The optional [`size`](/en-US/docs/Web/HTML/Attributes/size) attribute provides control over how many options are visible when the select does not have focus.
### Multiple choice select box
By default, a select box lets a user select only one value. By adding the [`multiple`](/en-US/docs/Web/HTML/Element/select#multiple) attribute to the {{HTMLElement("select")}} element, you can allow users to select several values. Users can select multiple values by using the default mechanism provided by the operating system (e.g., on the desktop, multiple values can be clicked while holding down <kbd>Cmd</kbd>/<kbd>Ctrl</kbd> keys).
```html
<select id="multi" name="multi" multiple size="2">
<optgroup label="fruits">
<option>Banana</option>
<option selected>Cherry</option>
<option>Lemon</option>
</optgroup>
<optgroup label="vegetables">
<option>Carrot</option>
<option>Eggplant</option>
<option>Potato</option>
</optgroup>
</select>
```
{{EmbedLiveSample("Multiple_choice_select_box", 120, 120)}}
> **Note:** In the case of multiple choice select boxes, you'll notice that the select box no longer displays the values as drop-down content — instead, all values are displayed at once in a list, with the optional [`size`](/en-US/docs/Web/HTML/Attributes/size) attribute determining the height of the widget.
> **Note:** All browsers that support the {{HTMLElement("select")}} element also support the [`multiple`](/en-US/docs/Web/HTML/Element/select#multiple) attribute.
### Autocomplete box
You can provide suggested, automatically-completed values for form widgets using the {{HTMLElement("datalist")}} element with child {{HTMLElement("option")}} elements to specify the values to display. The `<datalist>` needs to be given an `id`.
The data list is then bound to an {{htmlelement("input")}} element (e.g. a `text` or `email` input type) using the [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute, the value of which is the `id` of the data list to bind.
Once a data list is affiliated with a form widget, its options are used to auto-complete text entered by the user; typically, this is presented to the user as a drop-down box listing possible matches for what they've typed into the input.
#### Basic example
Let's look at an example.
```html
<label for="myFruit">What's your favorite fruit?</label>
<input type="text" name="myFruit" id="myFruit" list="mySuggestion" />
<datalist id="mySuggestion">
<option>Apple</option>
<option>Banana</option>
<option>Blackberry</option>
<option>Blueberry</option>
<option>Lemon</option>
<option>Lychee</option>
<option>Peach</option>
<option>Pear</option>
</datalist>
```
{{EmbedLiveSample("Basic_example_2", 120, 120)}}
#### Datalist support and fallbacks
Almost all browsers support datalist, but if you are still supporting older browsers such as IE versions below 10, there is a trick to provide a fallback:
```html
<label for="myFruit">What is your favorite fruit? (With fallback)</label>
<input type="text" id="myFruit" name="fruit" list="fruitList" />
<datalist id="fruitList">
<label for="suggestion">or pick a fruit</label>
<select id="suggestion" name="altFruit">
<option>Apple</option>
<option>Banana</option>
<option>Blackberry</option>
<option>Blueberry</option>
<option>Lemon</option>
<option>Lychee</option>
<option>Peach</option>
<option>Pear</option>
</select>
</datalist>
```
{{EmbedLiveSample("Datalist_support_and_fallbacks", 120, 120)}}
Browsers that support the {{HTMLElement("datalist")}} element will ignore all the elements that are not {{HTMLElement("option")}} elements, with the datalist working as expected. Old browsers that don't support the {{HTMLElement("datalist")}} element will display the label and the select box.
The following screenshot shows the datalist fallback as rendered in Safari 6:

If you use this fallback, ensure the data for both the `<input>` and the `<select>` are collected server-side.
#### Less obvious datalist uses
According to [the HTML specification](https://html.spec.whatwg.org/multipage/input.html#attr-input-list), the [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute and the {{HTMLElement("datalist")}} element can be used with any kind of widget requiring a user input. This leads to some uses of it that might seem a little non-obvious.
For example, in browsers that support `{{htmlelement("datalist")}}` on `range` input types, a small tick mark will be displayed above the range for each datalist `{{htmlelement("option")}}` value. You can see an implementation [example of this on the `<input type="range">` reference page](/en-US/docs/Web/HTML/Element/input/range#adding_tick_marks).
And browsers that support {{htmlelement('datalist')}}s and [`<input type="color">`](/en-US/docs/Web/HTML/Element/input/color) should display a customized palette of colors as the default, while still making the full color palette available.
In this case, different browsers behave differently from case to case, so consider such uses as progressive enhancement, and ensure they degrade gracefully.
## Other form features
There are a few other form features that are not as obvious as the ones we have already mentioned, but still useful in some situations, so we thought it would be worth giving them a brief mention.
> **Note:** You can find the examples from this section on GitHub as [other-examples.html](https://github.com/mdn/learning-area/blob/main/html/forms/native-form-widgets/other-examples.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/native-form-widgets/other-examples.html)).
### Meters and progress bars
Meters and progress bars are visual representations of numeric values. Support for {{HTMLElement("progress")}} and {{HTMLElement("meter")}} is available in all modern browsers.
#### Meter
A meter bar represents a fixed value in a range delimited by [`max`](/en-US/docs/Web/HTML/Element/meter#max) and [`min`](/en-US/docs/Web/HTML/Element/meter#min) values. This value is visually rendered as a bar, and to know how this bar looks, we compare the value to some other set values:
- The [`low`](/en-US/docs/Web/HTML/Element/meter#low) and [`high`](/en-US/docs/Web/HTML/Element/meter#high) values divide the range into the following three parts:
- The lower part of the range is between the [`min`](/en-US/docs/Web/HTML/Element/meter#min) and [`low`](/en-US/docs/Web/HTML/Element/meter#low) values, inclusive.
- The medium part of the range is between the [`low`](/en-US/docs/Web/HTML/Element/meter#low) and [`high`](/en-US/docs/Web/HTML/Element/meter#high) values, exclusive.
- The higher part of the range is between the [`high`](/en-US/docs/Web/HTML/Element/meter#high) and [`max`](/en-US/docs/Web/HTML/Element/meter#max) values, inclusive.
- The [`optimum`](/en-US/docs/Web/HTML/Element/meter#optimum) value defines the optimum value for the {{HTMLElement("meter")}} element. In conjunction with the [`low`](/en-US/docs/Web/HTML/Element/meter#low) and [`high`](/en-US/docs/Web/HTML/Element/meter#high) value, it defines which part of the range is preferred:
- If the [`optimum`](/en-US/docs/Web/HTML/Element/meter#optimum) value is in the lower part of the range, the lower range is considered to be the preferred part, the medium range is considered to be the average part, and the higher range is considered to be the worst part.
- If the [`optimum`](/en-US/docs/Web/HTML/Element/meter#optimum) value is in the medium part of the range, the lower range is considered to be an average part, the medium range is considered to be the preferred part, and the higher range is considered to be average as well.
- If the [`optimum`](/en-US/docs/Web/HTML/Element/meter#optimum) value is in the higher part of the range, the lower range is considered to be the worst part, the medium range is considered to be the average part and the higher range is considered to be the preferred part.
All browsers that implement the {{HTMLElement("meter")}} element use those values to change the color of the meter bar:
- If the current value is in the preferred part of the range, the bar is green.
- If the current value is in the average part of the range, the bar is yellow.
- If the current value is in the worst part of the range, the bar is red.
Such a bar is created by using the {{HTMLElement("meter")}} element. This is for implementing any kind of meter; for example, a bar showing the total space used on a disk, which turns red when it starts to get full.
```html
<meter min="0" max="100" value="75" low="33" high="66" optimum="0">75</meter>
```
{{EmbedLiveSample("Meter", 120, 120)}}
The content inside the {{HTMLElement("meter")}} element is a fallback for browsers that don't support the element and for assistive technologies to vocalize it.
#### Progress
A progress bar represents a value that changes over time up to a maximum value specified by the [`max`](/en-US/docs/Web/HTML/Element/progress#max) attribute. Such a bar is created using a {{ HTMLElement("progress")}} element.
```html
<progress max="100" value="75">75/100</progress>
```
{{EmbedLiveSample("Progress", 120, 120)}}
This is for implementing anything requiring progress reporting, such as the percentage of total files downloaded, or the number of questions filled in on a questionnaire.
The content inside the {{HTMLElement("progress")}} element is a fallback for browsers that don't support the element and for screen readers to vocalize it.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Other controls](/en-US/docs/Learn/Forms/Test_your_skills:_Other_controls).
## Summary
As you'll have seen in the last few articles, there are many types of form control. You don't need to remember all of these details at once, and can return to these articles as often as you like to check up on details.
Now that you have a grasp of the HTML behind the different available form controls, we'll take a look at [Styling them](/en-US/docs/Learn/Forms/Styling_web_forms).
{{PreviousMenuNext("Learn/Forms/HTML5_input_types","Learn/Forms/Styling_web_forms", "Learn/Forms")}}
### Advanced Topics
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/ui_pseudo-classes/index.md | ---
title: UI pseudo-classes
slug: Learn/Forms/UI_pseudo-classes
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Forms/Advanced_form_styling", "Learn/Forms/Form_validation", "Learn/Forms")}}
In the previous articles, we covered the styling of various form controls in a general manner. This included some usage of pseudo-classes, for example, using `:checked` to target a checkbox only when it is selected. In this article, we explore the different UI pseudo-classes available for styling forms in different states.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">HTML</a> and
<a href="/en-US/docs/Learn/CSS/First_steps">CSS</a>, including general
knowledge of
<a
href="/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements"
>pseudo-classes and pseudo-elements</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand what parts of forms are hard to style, and why; to learn
what can be done to customize them.
</td>
</tr>
</tbody>
</table>
## What pseudo-classes do we have available?
The original pseudo-classes (from [CSS 2.1](https://www.w3.org/TR/CSS21/selector.html#dynamic-pseudo-classes)) that are relevant to forms are:
- {{cssxref(":hover")}}: Selects an element only when it is being hovered over by a mouse pointer.
- {{cssxref(":focus")}}: Selects an element only when it is focused (i.e. by being tabbed to via the keyboard).
- {{cssxref(":active")}}: selects an element only when it is being activated (i.e. while it is being clicked on, or when the
<kbd>Return</kbd>
/
<kbd>Enter</kbd>
key is being pressed down in the case of a keyboard activation).
These basic pseudo-classes should be familiar to you now. [CSS selectors](/en-US/docs/Web/CSS/CSS_selectors) provide several other pseudo-classes related to HTML forms. These provide several useful targeting conditions that you can take advantage of. We'll discuss these in more detail in the sections below, but briefly, the main ones we'll be looking at are:
- {{cssxref(':required')}} and {{cssxref(':optional')}}: Target elements that can be required (e.g. elements that support the [`required`](/en-US/docs/Web/HTML/Attributes/required) HTML attribute)), based on whether they are required or optional.
- {{cssxref(":valid")}} and {{cssxref(":invalid")}}, and {{cssxref(":in-range")}} and {{cssxref(":out-of-range")}}: Target form controls that are valid/invalid according to form validation constraints set on them, or in-range/out-of-range.
- {{cssxref(":enabled")}} and {{cssxref(":disabled")}}, and {{cssxref(":read-only")}} and {{cssxref(":read-write")}}: Target elements that can be disabled (e.g. elements that support the [`disabled`](/en-US/docs/Web/HTML/Attributes/disabled) HTML attribute), based on whether they are currently enabled or disabled, and read-write or read-only form controls (e.g. elements with the [`readonly`](/en-US/docs/Web/HTML/Attributes/readonly) HTML attribute set).
- {{cssxref(":checked")}}, {{cssxref(":indeterminate")}}, and {{cssxref(":default")}}: Respectively target checkboxes and radio buttons that are checked, in an indeterminate state (neither checked or not checked), and the default selected option when the page loads (e.g. an [`<input type="checkbox">`](/en-US/docs/Web/HTML/Element/input/checkbox) with the [`checked`](/en-US/docs/Web/HTML/Element/input#checked) attribute set, or an [`<option>`](/en-US/docs/Web/HTML/Element/option) element with the [`selected`](/en-US/docs/Web/HTML/Element/option#selected) attribute set).
There are many others, but the ones listed above are the most obviously useful. Some of them are aimed at solving very specific niche problems. The UI pseudo-classes listed above have excellent browser support, but of course, you should test your form implementations carefully to ensure they work for your target audience.
> **Note:** A number of the pseudo-classes discussed here are concerned with styling form controls based on their validation state (is their data valid, or not?) You'll learn much more about setting and controlling validation constraints in our next article — [Client-side form validation](/en-US/docs/Learn/Forms/Form_validation) — but for now we'll keep things simple regarding the form validation, so it doesn't confuse things.
## Styling inputs based on whether they are required or not
One of the most basic concepts regarding client-side form validation is whether a form input is required (it has to be filled in before the form can be submitted) or optional.
{{htmlelement('input')}}, {{htmlelement('select')}}, and {{htmlelement('textarea')}} elements have a `required` attribute available which, when set, means that you have to fill in that control before the form will successfully submit. For example:
```html
<form>
<fieldset>
<legend>Feedback form</legend>
<div>
<label for="fname">First name: </label>
<input id="fname" name="fname" type="text" required />
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" name="lname" type="text" required />
</div>
<div>
<label for="email">
Email address (include if you want a response):
</label>
<input id="email" name="email" type="email" />
</div>
<div><button>Submit</button></div>
</fieldset>
</form>
```
Here, the first name and last name are required, but the email address is optional.
You can match these two states using the {{cssxref(':required')}} and {{cssxref(':optional')}} pseudo-classes. For example, if we apply the following CSS to the above HTML:
```css
input:required {
border: 1px solid black;
}
input:optional {
border: 1px solid silver;
}
```
The required controls would have a black border, and the optional control will have a silver border, like so:
{{EmbedGHLiveSample("learning-area/html/forms/pseudo-classes/basic-required-optional.html", '100%', 400)}}
You can also try submitting the form without filling it in, to see the client-side validation error messages browsers give you by default.
The above form isn't bad, but it isn't great either. For a start, we are signaling required versus optional status using color alone, which isn't great for colorblind people. Second, the standard convention on the web for required status is an asterisk (`*`), or the word "required" being associated with the controls in question.
In the next section, we'll look at a better example of indicating required fields using `:required`, which also digs into using generated content.
> **Note:** You'll probably not find yourself using the `:optional` pseudo-class very often. Form controls are optional by default, so you could just do your optional styling by default, and add styles on top for required controls.
> **Note:** If one radio button in a same-named group of radio buttons has the `required` attribute set, all the radio buttons will be invalid until one is selected, but only the one with the attribute assigned will actually match {{cssxref(':required')}}.
## Using generated content with pseudo-classes
In previous articles, we've seen the usage of [generated content](/en-US/docs/Web/CSS/CSS_generated_content), but we thought now would be a good time to talk about it in a bit more detail.
The idea is that we can use the [`::before`](/en-US/docs/Web/CSS/::before) and [`::after`](/en-US/docs/Web/CSS/::after) pseudo-elements along with the [`content`](/en-US/docs/Web/CSS/content) property to make a chunk of content appear before or after the affected element. The chunk of content is not added to the DOM, so it may be invisible to some screen readers. Because it is a pseudo-element, it can be targeted with styles in the same way that any actual DOM node can.
This is really useful when you want to add a visual indicator to an element, such as a label or icon, when alternative indicators are also available to ensure accessibility for all users. For example, in our [custom radio buttons example](https://mdn.github.io/learning-area/html/forms/styling-examples/radios-styled.html), we use generated content to handle the placement and animation of the a custom radio button's inner circle when a radio button is selected:
```css
input[type="radio"]::before {
display: block;
content: " ";
width: 10px;
height: 10px;
border-radius: 6px;
background-color: red;
font-size: 1.2em;
transform: translate(3px, 3px) scale(0);
transform-origin: center;
transition: all 0.3s ease-in;
}
input[type="radio"]:checked::before {
transform: translate(3px, 3px) scale(1);
transition: all 0.3s cubic-bezier(0.25, 0.25, 0.56, 2);
}
```
This is really useful — screen readers already let their users know when a radio button or checkbox they encounter is checked/selected, so you don't want them to read out another DOM element that indicates selection — that could be confusing. Having a purely visual indicator solves this problem.
Back to our required/optional example from before, this time we'll not alter the appearance of the input itself — we'll use generated content to add an indicating label ([see it live here](https://mdn.github.io/learning-area/html/forms/pseudo-classes/required-optional-generated.html), and see the [source code here](https://github.com/mdn/learning-area/blob/main/html/forms/pseudo-classes/required-optional-generated.html)).
First of all, we'll add a paragraph to the top of the form to say what you are looking for:
```html
<p>Required fields are labeled with "required".</p>
```
Screen reader users will get "required" read out as an extra bit of information when they get to each required input, while sighted users will get our label.
Since form inputs don't directly support having generated content put on them (this is because generated content is placed relative to an element's formatting box, but form inputs work more like replaced elements and therefore don't have one), we will add an empty [`<span>`](/en-US/docs/Web/HTML/Element/span) to hang the generated content on:
```html
<div>
<label for="fname">First name: </label>
<input id="fname" name="fname" type="text" required />
<span></span>
</div>
```
The immediate problem with this was that the span was dropping onto a new line below the input because the input and label are both set with `width: 100%`. To fix this we style the parent `<div>` to become a flex container, but also tell it to wrap its contents onto new lines if the content becomes too long:
```css
fieldset > div {
margin-bottom: 20px;
display: flex;
flex-flow: row wrap;
}
```
The effect this has is that the label and input sit on separate lines because they are both `width: 100%`, but the `<span>` has a width of `0` so it can sit on the same line as the input.
Now onto the generated content. We create it using this CSS:
```css
input + span {
position: relative;
}
input:required + span::after {
font-size: 0.7rem;
position: absolute;
content: "required";
color: white;
background-color: black;
padding: 5px 10px;
top: -26px;
left: -70px;
}
```
We set the `<span>` to `position: relative` so that we can set the generated content to `position: absolute` and position it relative to the `<span>` rather than the `<body>` (The generated content acts as though it is a child node of the element it is generated on, for the purposes of positioning).
Then we give the generated content the content "required", which is what we wanted our label to say, and style and position it as we want. The result is seen below.
{{EmbedGHLiveSample("learning-area/html/forms/pseudo-classes/required-optional-generated.html", '100%', 430)}}
## Styling controls based on whether their data is valid
The other really important, fundamental concept in form validation is whether a form control's data is valid or not (in the case of numerical data, we can also talk about in-range and out-of-range data). Form controls with [constraint limitations](/en-US/docs/Web/HTML/Constraint_validation) can be targeted based on these states.
### :valid and :invalid
You can target form controls using the {{cssxref(":valid")}} and {{cssxref(":invalid")}} pseudo-classes. Some points worth bearing in mind:
- Controls with no constraint validation will always be valid, and therefore matched with `:valid`.
- Controls with `required` set on them that have no value are counted as invalid — they will be matched with `:invalid` and `:required`.
- Controls with built-in validation, such as `<input type="email">` or `<input type="url">` are (matched with) `:invalid` when the data entered into them does not match the pattern they are looking for (but they are valid when empty).
- Controls whose current value is outside the range limits specified by the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes are (matched with) `:invalid`, but also matched by {{cssxref(":out-of-range")}}, as you'll see later on.
- There are some other ways to make an element matched by `:valid`/`:invalid`, as you'll see in the [Client-side form validation](/en-US/docs/Learn/Forms/Form_validation) article. But we'll keep things simple for now.
Let's go in and look at a simple example of `:valid`/`:invalid` (see [valid-invalid.html](https://mdn.github.io/learning-area/html/forms/pseudo-classes/valid-invalid.html) for the live version, and also check out the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/pseudo-classes/valid-invalid.html)).
As in the previous example, we've got extra `<span>`s to generate content on, which we'll use to provide indicators of valid/invalid data:
```html
<div>
<label for="fname">First name: </label>
<input id="fname" name="fname" type="text" required />
<span></span>
</div>
```
To provide these indicators, we use the following CSS:
```css
input + span {
position: relative;
}
input + span::before {
position: absolute;
right: -20px;
top: 5px;
}
input:invalid {
border: 2px solid red;
}
input:invalid + span::before {
content: "✖";
color: red;
}
input:valid + span::before {
content: "✓";
color: green;
}
```
As before, we set the `<span>`s to `position: relative` so that we can position the generated content relative to them. We then absolutely position different generated content depending on whether the form's data is valid or invalid — a green check or a red cross, respectively. To add a bit of extra urgency to the invalid data, we've also given the inputs a thick red border when invalid.
> **Note:** We've used `::before` to add these labels, as we were already using `::after` for the "required" labels.
You can try it below:
{{EmbedGHLiveSample("learning-area/html/forms/pseudo-classes/valid-invalid.html", '100%', 430)}}
Notice how the required text inputs are invalid when empty, but valid when they have something filled in. The email input on the other hand is valid when empty, as it is not required, but invalid when it contains something that is not a proper email address.
### In-range and out-of-range data
As we hinted at above, there are two other related pseudo-classes to consider — {{cssxref(":in-range")}} and {{cssxref(":out-of-range")}}. These match numeric inputs where range limits are specified by the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max), when their data is inside or outside the specified range, respectively.
> **Note:** Numeric input types are `date`, `month`, `week`, `time`, `datetime-local`, `number`, and `range`.
It is worth noting that inputs whose data is in-range will also be matched by the `:valid` pseudo-class and inputs whose data is out-of-range will also be matched by the `:invalid` pseudo-class. So why have both? The issue is really one of semantics — out-of-range is a more specific type of invalid communication, so you might want to provide a different message for out-of-range inputs, which will be more helpful to users than just saying "invalid". You might even want to provide both.
Let's look at an example that does exactly this. Our [out-of-range.html](https://mdn.github.io/learning-area/html/forms/pseudo-classes/out-of-range.html) demo (see also the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/pseudo-classes/out-of-range.html)) builds on top of the previous example to provide out-of-range messages for the numeric inputs, as well as saying whether they are required.
The numeric input looks like this:
```html
<div>
<label for="age">Age (must be 12+): </label>
<input id="age" name="age" type="number" min="12" max="120" required />
<span></span>
</div>
```
And the CSS looks like this:
```css
input + span {
position: relative;
}
input + span::after {
font-size: 0.7rem;
position: absolute;
padding: 5px 10px;
top: -26px;
}
input:required + span::after {
color: white;
background-color: black;
content: "Required";
left: -70px;
}
input:out-of-range + span::after {
color: white;
background-color: red;
width: 155px;
content: "Outside allowable value range";
left: -182px;
}
```
This is a similar story to what we had before in the `:required` example, except that here we've split out the declarations that apply to any `::after` content into a separate rule, and given the separate `::after` content for `:required` and `:out-of-range` states their own content and styling. You can try it here:
{{EmbedGHLiveSample("learning-area/html/forms/pseudo-classes/out-of-range.html", '100%', 430)}}
It is possible for the number input to be both required and out-of-range at the same time, so what happens then? Because the `:out-of-range` rule appears later in the source code than the `:required` rule, the [cascade rules](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#understanding_the_cascade) come into play, and the out of range message is shown.
This works quite nicely — when the page first loads, "Required" is shown, along with a red cross and border. When you've typed in a valid age (i.e. in the range of 12-120), the input turns valid. If however, you then change the age entry to one that is out of range, the "Outside allowable value range" message then pops up in place of "Required".
> **Note:** To enter an invalid/out-of-range value, you'll have to actually focus the form and type it in using the keyboard. The spinner buttons won't let you increment/decrement the value outside the allowable range.
## Styling enabled and disabled inputs, and read-only and read-write
An enabled element is an element that can be activated; it can be selected, clicked on, typed into, etc. A disabled element on the other hand cannot be interacted with in any way, and its data isn't even sent to the server.
These two states can be targeted using {{cssxref(":enabled")}} and {{cssxref(":disabled")}}. Why are disabled inputs useful? Well, sometimes if some data does not apply to a certain user, you might not even want to submit that data when they submit the form. A classic example is a shipping form — commonly you'll get asked if you want to use the same address for billing and shipping; if so, you can just send a single address to the server, and might as well just disable the billing address fields.
Let's have a look at an example that does just this. First of all, the HTML is a simple form containing text inputs, plus a checkbox to toggle disabling the billing address on and off. The billing address fields are disabled by default.
```html
<form>
<fieldset id="shipping">
<legend>Shipping address</legend>
<div>
<label for="name1">Name: </label>
<input id="name1" name="name1" type="text" required />
</div>
<div>
<label for="address1">Address: </label>
<input id="address1" name="address1" type="text" required />
</div>
<div>
<label for="pcode1">Zip/postal code: </label>
<input id="pcode1" name="pcode1" type="text" required />
</div>
</fieldset>
<fieldset id="billing">
<legend>Billing address</legend>
<div>
<label for="billing-checkbox">Same as shipping address:</label>
<input type="checkbox" id="billing-checkbox" checked />
</div>
<div>
<label for="name" class="billing-label disabled-label">Name: </label>
<input id="name" name="name" type="text" disabled required />
</div>
<div>
<label for="address2" class="billing-label disabled-label">
Address:
</label>
<input id="address2" name="address2" type="text" disabled required />
</div>
<div>
<label for="pcode2" class="billing-label disabled-label">
Zip/postal code:
</label>
<input id="pcode2" name="pcode2" type="text" disabled required />
</div>
</fieldset>
<div><button>Submit</button></div>
</form>
```
Now onto the CSS. The most relevant parts of this example are as follows:
```css
input[type="text"]:disabled {
background: #eee;
border: 1px solid #ccc;
}
.disabled-label {
color: #aaa;
}
```
We've directly selected the inputs we want to disable using `input[type="text"]:disabled`, but we also wanted to gray out the corresponding text labels. These weren't quite as easy to select, so we've used a class to provide them with that styling.
Now finally, we've used some JavaScript to toggle the disabling of the billing address fields:
```js
// Wait for the page to finish loading
document.addEventListener(
"DOMContentLoaded",
() => {
// Attach `change` event listener to checkbox
document
.getElementById("billing-checkbox")
.addEventListener("change", toggleBilling);
},
false,
);
function toggleBilling() {
// Select the billing text fields
const billingItems = document.querySelectorAll('#billing input[type="text"]');
// Select the billing text labels
const billingLabels = document.querySelectorAll(".billing-label");
// Toggle the billing text fields and labels
for (let i = 0; i < billingItems.length; i++) {
billingItems[i].disabled = !billingItems[i].disabled;
if (
billingLabels[i].getAttribute("class") === "billing-label disabled-label"
) {
billingLabels[i].setAttribute("class", "billing-label");
} else {
billingLabels[i].setAttribute("class", "billing-label disabled-label");
}
}
}
```
It uses the [`change` event](/en-US/docs/Web/API/HTMLElement/change_event) to let the user enable/disable the billing fields, and toggle the styling of the associated labels.
You can see the example in action below (also [see it live here](https://mdn.github.io/learning-area/html/forms/pseudo-classes/enabled-disabled-shipping.html), and see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/pseudo-classes/enabled-disabled-shipping.html)):
{{EmbedGHLiveSample("learning-area/html/forms/pseudo-classes/enabled-disabled-shipping.html", '100%', 600)}}
### Read-only and read-write
In a similar manner to `:disabled` and `:enabled`, the `:read-only` and `:read-write` pseudo-classes target two states that form inputs toggle between. Read-only inputs have their values submitted to the server, but the user can't edit them, whereas read-write means they can be edited — their default state.
An input is set to read-only using the `readonly` attribute. As an example, imagine a confirmation page where the developer has sent the details filled in on previous pages over to this page, with the aim of getting the user to check them all in one place, add any final data that is needed, and then confirm the order by submitting. At this point, all the final form data can be sent to the server in one go.
Let's look at what a form might look like (see [readonly-confirmation.html](https://mdn.github.io/learning-area/html/forms/pseudo-classes/readonly-confirmation.html) for the live example; also [see the source code](https://github.com/mdn/learning-area/blob/main/html/forms/pseudo-classes/readonly-confirmation.html)).
A fragment of the HTML is as follows — note the readonly attribute:
```html
<div>
<label for="name">Name: </label>
<input id="name" name="name" type="text" value="Mr Soft" readonly />
</div>
```
If you try the live example, you'll see that the top set of form elements are not focusable, however, the values are submitted when the form is submitted. We've styled the form controls using the `:read-only` and `:read-write` pseudo-classes, like so:
```css
input:read-only,
textarea:read-only {
border: 0;
box-shadow: none;
background-color: white;
}
textarea:read-write {
box-shadow: inset 1px 1px 3px #ccc;
border-radius: 5px;
}
```
The full example looks like this:
{{EmbedGHLiveSample("learning-area/html/forms/pseudo-classes/readonly-confirmation.html", '100%', 660)}}
> **Note:** `:enabled` and `:read-write` are two more pseudo-classes that you'll probably rarely use, given that they describe the default states of input elements.
## Radio and checkbox states — checked, default, indeterminate
As we've seen in earlier articles in the module, {{HTMLElement("input/radio", "radio buttons")}} and {{HTMLElement("input/checkbox", "checkboxes")}} can be checked or unchecked. But there are a couple of other states to consider too:
- {{cssxref(":default")}}: Matches radios/checkboxes that are checked by default, on page load (i.e. by setting the `checked` attribute on them). These match the {{cssxref(":default")}} pseudo-class, even if the user unchecks them.
- {{cssxref(":indeterminate")}}: When radios/checkboxes are neither checked nor unchecked, they are considered _indeterminate_ and will match the {{cssxref(":indeterminate")}} pseudo-class. More on what this means below.
### :checked
When checked, they will be matched by the {{cssxref(":checked")}} pseudo-class.
The most common use of this is to add a different style onto the checkbox or radio button when it is checked, in cases where you've removed the system default styling with [`appearance: none;`](/en-US/docs/Web/CSS/appearance) and want to build the styles back up yourself. We saw examples of this in the previous article when we talked about [Using `appearance: none` on radios/checkboxes](/en-US/docs/Learn/Forms/Advanced_form_styling#using_appearance_none_on_radioscheckboxes).
As a recap, the `:checked` code from our [Styled radio buttons](https://mdn.github.io/learning-area/html/forms/styling-examples/radios-styled.html) example looks like so:
```css
input[type="radio"]::before {
display: block;
content: " ";
width: 10px;
height: 10px;
border-radius: 6px;
background-color: red;
font-size: 1.2em;
transform: translate(3px, 3px) scale(0);
transform-origin: center;
transition: all 0.3s ease-in;
}
input[type="radio"]:checked::before {
transform: translate(3px, 3px) scale(1);
transition: all 0.3s cubic-bezier(0.25, 0.25, 0.56, 2);
}
```
You can try it out here:
{{EmbedGHLiveSample("learning-area/html/forms/styling-examples/radios-styled.html", '100%', 200)}}
Basically, we build the styling for a radio button's "inner circle" using the `::before` pseudo-element, but set a `scale(0)` [`transform`](/en-US/docs/Web/CSS/transform) on it. We then use a [`transition`](/en-US/docs/Web/CSS/transition) to make the generated content on the label nicely animate into view when the radio is selected/checked. The advantage of using a transform rather than transitioning [`width`](/en-US/docs/Web/CSS/width)/[`height`](/en-US/docs/Web/CSS/height) is that you can use [`transform-origin`](/en-US/docs/Web/CSS/transform-origin) to make it grow from the center of the circle, rather than having it appear to grow from the circle's corner, and there is no jumping behavior as no box model property values are updated.
### :default and :indeterminate
As mentioned above, the {{cssxref(":default")}} pseudo-class matches radios/checkboxes that are checked by default, on page load, even when unchecked. This could be useful for adding an indicator to a list of options to remind the user what the defaults (or starting options) were, in case they want to reset their choices.
Also, the radios/checkboxes mentioned above will be matched by the {{cssxref(":indeterminate")}} pseudo-class when they are in a state where they are neither checked nor unchecked. But what does this mean? Elements that are indeterminate include:
- {{HTMLElement("input/radio")}} inputs, when all radio buttons in a same-named group are unchecked
- {{HTMLElement("input/checkbox")}} inputs whose `indeterminate` property is set to `true` via JavaScript
- {{HTMLElement("progress")}} elements that have no value.
This isn't something you'll likely use very often. One use case could be an indicator to tell users that they really need to select a radio button before they move on.
Let's look at a couple of modified versions of the previous example that remind the user what the default option was, and style the labels of radio buttons when indeterminate. Both of these have the following HTML structure for the inputs:
```html
<p>
<input type="radio" name="fruit" value="cherry" id="cherry" />
<label for="cherry">Cherry</label>
<span></span>
</p>
```
For the `:default` example, we've added the `checked` attribute to the middle radio button input, so it will be selected by default when loaded. We then style this with the following CSS:
```css
input ~ span {
position: relative;
}
input:default ~ span::after {
font-size: 0.7rem;
position: absolute;
content: "Default";
color: white;
background-color: black;
padding: 5px 10px;
right: -65px;
top: -3px;
}
```
This provides a little "Default" label on the item that was originally selected when the page loaded. Note here we are using the subsequent-sibling combinator (`~`) rather than the Next-sibling combinator (`+`) — we need to do this because the `<span>` does not come right after the `<input>` in the source order.
See the live result below:
{{EmbedGHLiveSample("learning-area/html/forms/pseudo-classes/radios-checked-default.html", '100%', 200)}}
> **Note:** You can also find the example live on GitHub at [radios-checked-default.html](https://mdn.github.io/learning-area/html/forms/pseudo-classes/radios-checked-default.html) (also see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/pseudo-classes/radios-checked-default.html).)
For the `:indeterminate` example, we've got no default selected radio button — this is important — if there was, then there would be no indeterminate state to style. We style the indeterminate radio buttons with the following CSS:
```css
input[type="radio"]:indeterminate {
outline: 2px solid red;
animation: 0.4s linear infinite alternate outline-pulse;
}
@keyframes outline-pulse {
from {
outline: 2px solid red;
}
to {
outline: 6px solid red;
}
}
```
This creates a fun little animated outline on the radio buttons, which hopefully indicates that you need to select one of them!
See the live result below:
{{EmbedGHLiveSample("learning-area/html/forms/pseudo-classes/radios-checked-indeterminate.html", '100%', 200)}}
> **Note:** You can also find the example live on GitHub at [radios-checked-indeterminate.html](https://mdn.github.io/learning-area/html/forms/pseudo-classes/radios-checked-indeterminate.html) (also see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/pseudo-classes/radios-checked-indeterminate.html).)
> **Note:** You can find an [interesting example involving `indeterminate` states](/en-US/docs/Web/HTML/Element/input/checkbox#indeterminate_state_checkboxes) on the [`<input type="checkbox">`](/en-US/docs/Web/HTML/Element/input/checkbox) reference page.
## More pseudo-classes
There are a number of other pseudo-classes of interest, and we don't have space to write about them all in detail here. Let's talk about a few more that you should take the time to investigate.
- The {{cssxref(":focus-within")}} pseudo-class matches an element that has received focus or _contains_ an element that has received focus. This is useful if you want a whole form to highlight in some way when an input inside it is focused.
- The {{cssxref(":focus-visible")}} pseudo-class matches focused elements that received focus via keyboard interaction (rather than touch or mouse) — useful if you want to show a different style for keyboard focus compared to mouse (or other) focus.
- The {{cssxref(":placeholder-shown")}} pseudo-class matches {{htmlelement('input')}} and {{htmlelement('textarea')}} elements that have their placeholder showing (i.e. the contents of the [`placeholder`](/en-US/docs/Web/HTML/Element/input#placeholder) attribute) because the value of the element is empty.
The following are also interesting, but as yet not well-supported in browsers:
- The {{cssxref(":blank")}} pseudo-class selects empty form controls. {{cssxref(":empty")}} also matches elements that have no children, like {{HTMLElement("input")}}, but it is more general — it also matches other {{glossary("void element", "void elements")}} like {{HTMLElement("br")}} and {{HTMLElement("hr")}}. `:empty` has reasonable browser support; the `:blank` pseudo-class's specification is not yet finished, so it is not yet supported in any browser.
- The [`:user-invalid`](/en-US/docs/Web/CSS/:user-invalid) pseudo-class, when supported, will be similar to {{cssxref(":invalid")}}, but with better user experience. If the value is valid when the input receives focus, the element may match `:invalid` as the user enters data if the value is temporarily invalid, but will only match `:user-invalid` when the element loses focus. If the value was originally invalid, it will match both `:invalid` and `:user-invalid` for the whole duration of the focus. In a similar manner to `:invalid`, it will stop matching `:user-invalid` if the value does become valid.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Advanced styling](/en-US/docs/Learn/Forms/Test_your_skills:_Advanced_styling).
## Summary
This completes our look at UI pseudo-classes that relate to form inputs. Keep playing with them, and create some fun form styles! Next up, we'll move on to something different — [client-side form validation](/en-US/docs/Learn/Forms/Form_validation).
{{PreviousMenuNext("Learn/Forms/Advanced_form_styling", "Learn/Forms/Form_validation", "Learn/Forms")}}
### Advanced Topics
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/your_first_form/index.md | ---
title: Your first form
slug: Learn/Forms/Your_first_form
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}
The first article in our series provides you with your very first experience of creating a web form, including designing a simple form, implementing it using the right HTML form controls and other HTML elements, adding some very simple styling via CSS, and describing how data is sent to a server.
We'll expand on each of these subtopics in more detail later on in the module.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>understanding of HTML</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To gain familiarity with what web forms are, what they are used for, how
to think about designing them, and the basic HTML elements you'll need
for simple cases.
</td>
</tr>
</tbody>
</table>
## What are web forms?
**Web forms** are one of the main points of interaction between a user and a website or application.
Forms allow users to enter data, which is generally sent to a web server for processing and storage (see [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data) later in the module), or used on the client-side to immediately update the interface in some way (for example, add another item to a list, or show or hide a UI feature).
A web form's HTML is made up of one or more **form controls** (sometimes called **widgets**), plus some additional elements to help structure the overall form — they are often referred to as **HTML forms**.
The controls can be single or multi-line text fields, dropdown boxes, buttons, checkboxes, or radio buttons, and are mostly created using the {{htmlelement("input")}} element, although there are some other elements to learn about too.
Form controls can also be programmed to enforce specific formats or values to be entered (**form validation**), and paired with text labels that describe their purpose to both sighted and visually impaired users.
## Designing your form
Before starting to code, it's always better to step back and take the time to think about your form. Designing a quick mockup will help you to define the right set of data you want to ask your user to enter. From a user experience (UX) point of view, it's important to remember that the bigger your form, the more you risk frustrating people and losing users. Keep it simple and stay focused: ask only for the data you absolutely need.
Designing forms is an important step when you are building a site or application.
It's beyond the scope of this article to cover the user experience of forms, but if you want to dig into that topic you should read the following articles:
- Smashing Magazine has some [good articles about forms UX](https://www.smashingmagazine.com/2018/08/ux-html5-mobile-form-part-1/), including an older but still relevant [Extensive Guide To Web Form Usability](https://www.smashingmagazine.com/2011/11/extensive-guide-web-form-usability/) article.
- UXMatters is also a very thoughtful resource with good advice from [basic best practices](https://www.uxmatters.com/mt/archives/2012/05/7-basic-best-practices-for-buttons.php) to complex concerns such as [multipage forms](https://www.uxmatters.com/mt/archives/2010/03/pagination-in-web-forms-evaluating-the-effectiveness-of-web-forms.php).
In this article, we'll build a simple contact form. Let's make a rough sketch.

Our form will contain three text fields and one button. We are asking the user for their name, their email and the message they want to send. Hitting the button will send their data to a web server.
## Active learning: Implementing our form HTML
Ok, let's have a go at creating the HTML for our form. We will use the following HTML elements: {{HTMLelement("form")}}, {{HTMLelement("label")}}, {{HTMLelement("input")}}, {{HTMLelement("textarea")}}, and {{HTMLelement("button")}}.
Before you go any further, make a local copy of our [simple HTML template](https://github.com/mdn/learning-area/blob/main/html/introduction-to-html/getting-started/index.html) — you'll enter your form HTML into here.
### The `<form>` element
All forms start with a {{HTMLelement("form")}} element, like this:
```html
<form action="/my-handling-form-page" method="post">…</form>
```
This element formally defines a form. It's a container element like a {{HTMLelement("section")}} or {{HTMLelement("footer")}} element, but specifically for containing forms; it also supports some specific attributes to configure the way the form behaves. All of its attributes are optional, but it's standard practice to always set at least the [`action`](/en-US/docs/Web/HTML/Element/form#action) and [`method`](/en-US/docs/Web/HTML/Element/form#method) attributes:
- The `action` attribute defines the location (URL) where the form's collected data should be sent when it is submitted.
- The `method` attribute defines which HTTP method to send the data with (usually `get` or `post`).
> **Note:** We'll look at how those attributes work in our [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data) article later on.
For now, add the above {{htmlelement("form")}} element into your HTML {{htmlelement("body")}}.
### The `<label>`, `<input>`, and `<textarea>` elements
Our contact form is not complex: the data entry portion contains three text fields, each with a corresponding {{HTMLelement("label")}}:
- The input field for the name is a {{HTMLelement("input/text", "single-line text field")}}.
- The input field for the email is an {{HTMLelement("input/email", "input of type email")}}: a single-line text field that accepts only email addresses.
- The input field for the message is a {{HTMLelement("textarea")}}; a multiline text field.
In terms of HTML code we need something like the following to implement these form widgets:
```html
<form action="/my-handling-form-page" method="post">
<ul>
<li>
<label for="name">Name:</label>
<input type="text" id="name" name="user_name" />
</li>
<li>
<label for="mail">Email:</label>
<input type="email" id="mail" name="user_email" />
</li>
<li>
<label for="msg">Message:</label>
<textarea id="msg" name="user_message"></textarea>
</li>
</ul>
</form>
```
Update your form code to look like the above.
The {{HTMLelement("li")}} elements are there to conveniently structure our code and make styling easier (see later in the article).
For usability and accessibility, we include an explicit label for each form control.
Note the use of the [`for`](/en-US/docs/Web/HTML/Attributes/for) attribute on all {{HTMLelement("label")}} elements, which takes as its value the [`id`](/en-US/docs/Web/HTML/Global_attributes/id) of the form control with which it is associated — this is how you associate a form control with its label.
There is great benefit to doing this — it associates the label with the form control, enabling mouse, trackpad, and touch device users to click on the label to activate the corresponding control, and it also provides an accessible name for screen readers to read out to their users.
You'll find further details of form labels in [How to structure a web form](/en-US/docs/Learn/Forms/How_to_structure_a_web_form).
On the {{HTMLelement("input")}} element, the most important attribute is the `type` attribute.
This attribute is extremely important because it defines the way the {{HTMLelement("input")}} element appears and behaves.
You'll find more about this in the [Basic native form controls](/en-US/docs/Learn/Forms/Basic_native_form_controls) article later on.
- In our simple example, we use the value {{HTMLelement("input/text", "text")}} for the first input — the default value for this attribute.
It represents a basic single-line text field that accepts any kind of text input.
- For the second input, we use the value {{HTMLelement("input/email", "email")}}, which defines a single-line text field that only accepts a well-formed email address.
This turns a basic text field into a kind of "intelligent" field that will perform some validation checks on the data typed by the user.
It also causes a more appropriate keyboard layout for entering email addresses (e.g. with an @ symbol by default) to appear on devices with dynamic keyboards, like smartphones.
You'll find out more about form validation in the [client-side form validation](/en-US/docs/Learn/Forms/Form_validation) article later on.
Last but not least, note the syntax of `<input>` vs. `<textarea></textarea>`.
This is one of the oddities of HTML.
The `<input>` tag is a {{glossary("void element")}}, meaning that it doesn't need a closing tag.
{{HTMLElement("textarea")}} is not a void element, meaning it should be closed with the proper ending tag.
This has an impact on a specific feature of forms: the way you define the default value.
To define the default value of an {{HTMLElement("input")}} element you have to use the [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute like this:
```html
<input type="text" value="by default this element is filled with this text" />
```
On the other hand, if you want to define a default value for a {{HTMLElement("textarea")}}, you put it between the opening and closing tags of the {{HTMLElement("textarea")}} element, like this:
```html
<textarea>
by default this element is filled with this text
</textarea>
```
### The `<button>` element
The markup for our form is almost complete; we just need to add a button to allow the user to send, or "submit", their data once they have filled out the form.
This is done by using the {{HTMLelement("button")}} element; add the following just above the closing `</ul>` tag:
```html
<li class="button">
<button type="submit">Send your message</button>
</li>
```
The {{htmlelement("button")}} element also accepts a `type` attribute — this accepts one of three values: `submit`, `reset`, or `button`.
- A click on a `submit` button (the default value) sends the form's data to the web page defined by the `action` attribute of the {{HTMLelement("form")}} element.
- A click on a `reset` button resets all the form widgets to their default value immediately. From a UX point of view, this is considered bad practice, so you should avoid using this type of button unless you really have a good reason to include one.
- A click on a `button` button does _nothing_! That sounds silly, but it's amazingly useful for building custom buttons — you can define their chosen functionality with JavaScript.
> **Note:** You can also use the {{HTMLElement("input")}} element with the corresponding `type` to produce a button, for example `<input type="submit">`. The main advantage of the {{HTMLelement("button")}} element is that the {{HTMLelement("input")}} element only allows plain text in its label whereas the {{HTMLelement("button")}} element allows full HTML content, allowing more complex, creative button content.
## Basic form styling
Now that you have finished writing your form's HTML code, try saving it and looking at it in a browser. At the moment, you'll see that it looks rather ugly.
> **Note:** If you don't think you've got the HTML code right, try comparing it with our finished example — see [first-form.html](https://github.com/mdn/learning-area/blob/main/html/forms/your-first-HTML-form/first-form.html) ([also see it live](https://mdn.github.io/learning-area/html/forms/your-first-HTML-form/first-form.html)).
Forms are notoriously tricky to style nicely. It is beyond the scope of this article to teach you form styling in detail, so for the moment we will just get you to add some CSS to make it look OK.
First of all, add a {{htmlelement("style")}} element to your page, inside your HTML head. It should look like so:
```html
<style>
…
</style>
```
Inside the `style` tags, add the following CSS:
```css
form {
/* Center the form on the page */
margin: 0 auto;
width: 400px;
/* Form outline */
padding: 1em;
border: 1px solid #ccc;
border-radius: 1em;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
form li + li {
margin-top: 1em;
}
label {
/* Uniform size & alignment */
display: inline-block;
width: 90px;
text-align: right;
}
input,
textarea {
/* To make sure that all text fields have the same font settings
By default, textareas have a monospace font */
font: 1em sans-serif;
/* Uniform text field size */
width: 300px;
box-sizing: border-box;
/* Match form field borders */
border: 1px solid #999;
}
input:focus,
textarea:focus {
/* Additional highlight for focused elements */
border-color: #000;
}
textarea {
/* Align multiline text fields with their labels */
vertical-align: top;
/* Provide space to type some text */
height: 5em;
}
.button {
/* Align buttons with the text fields */
padding-left: 90px; /* same size as the label elements */
}
button {
/* This extra margin represent roughly the same space as the space
between the labels and their text fields */
margin-left: 0.5em;
}
```
Save and reload, and you'll see that your form should look much less ugly.
> **Note:** You can find our version on GitHub at [first-form-styled.html](https://github.com/mdn/learning-area/blob/main/html/forms/your-first-HTML-form/first-form-styled.html) ([also see it live](https://mdn.github.io/learning-area/html/forms/your-first-HTML-form/first-form-styled.html)).
## Sending form data to your web server
The last part, and perhaps the trickiest, is to handle form data on the server side.
The {{HTMLelement("form")}} element defines where and how to send the data thanks to the [`action`](/en-US/docs/Web/HTML/Element/form#action) and [`method`](/en-US/docs/Web/HTML/Element/form#method) attributes.
We provide a `name` attribute for each form control.
The names are important on both the client- and server-side; they tell the browser which name to give each piece of data and, on the server side, they let the server handle each piece of data by name.
The form data is sent to the server as name/value pairs.
To name the data in a form, you need to use the `name` attribute on each form widget that will collect a specific piece of data.
Let's look at some of our form code again:
```html
<form action="/my-handling-form-page" method="post">
<ul>
<li>
<label for="name">Name:</label>
<input type="text" id="name" name="user_name" />
</li>
<li>
<label for="mail">Email:</label>
<input type="email" id="mail" name="user_email" />
</li>
<li>
<label for="msg">Message:</label>
<textarea id="msg" name="user_message"></textarea>
</li>
…
</ul>
</form>
```
In our example, the form will send 3 pieces of data named "`user_name`", "`user_email`", and "`user_message`".
That data will be sent to the URL "`/my-handling-form-page`" using the [HTTP `POST`](/en-US/docs/Web/HTTP/Methods/POST) method.
On the server side, the script at the URL "`/my-handling-form-page`" will receive the data as a list of 3 key/value items contained in the HTTP request.
The way this script will handle that data is up to you.
Each server-side language (PHP, Python, Ruby, Java, C#, etc.) has its own mechanism of handling form data.
It's beyond the scope of this guide to go deeply into that subject, but if you want to know more, we have provided some examples in our [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data) article later on.
## Summary
Congratulations, you've built your first web form. It looks like this live:
```html hidden
<form action="/my-handling-form-page" method="post">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="user_name" />
</div>
<div>
<label for="mail">Email:</label>
<input type="email" id="mail" name="user_email" />
</div>
<div>
<label for="msg">Message:</label>
<textarea id="msg" name="user_message"></textarea>
</div>
<div class="button">
<button type="submit">Send your message</button>
</div>
</form>
```
```css hidden
form {
/* Just to center the form on the page */
margin: 0 auto;
width: 400px;
/* To see the limits of the form */
padding: 1em;
border: 1px solid #ccc;
border-radius: 1em;
}
div + div {
margin-top: 1em;
}
label {
/* To make sure that all label have the same size and are properly align */
display: inline-block;
width: 90px;
text-align: right;
}
input,
textarea {
/* To make sure that all text field have the same font settings
By default, textarea are set with a monospace font */
font: 1em sans-serif;
/* To give the same size to all text field */
width: 300px;
-moz-box-sizing: border-box;
box-sizing: border-box;
/* To harmonize the look & feel of text field border */
border: 1px solid #999;
}
input:focus,
textarea:focus {
/* To give a little highlight on active elements */
border-color: #000;
}
textarea {
/* To properly align multiline text field with their label */
vertical-align: top;
/* To give enough room to type some text */
height: 5em;
/* To allow users to resize any textarea vertically
It works only on Chrome, Firefox and Safari */
resize: vertical;
}
.button {
/* To position the buttons to the same position of the text fields */
padding-left: 90px; /* same size as the label elements */
}
button {
/* This extra margin represent the same space as the space between
the labels and their text fields */
margin-left: 0.5em;
}
```
{{ EmbedLiveSample('Summary', '', '300') }}
That's only the beginning, however — now it's time to take a deeper look. Forms have way more power than what we saw here and the other articles in this module will help you to master the rest.
{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}
### Advanced Topics
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/test_your_skills_colon__basic_controls/index.md | ---
title: "Test your skills: Basic controls"
slug: Learn/Forms/Test_your_skills:_Basic_controls
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Basic native form controls](/en-US/docs/Learn/Forms/Basic_native_form_controls) article.
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Basic controls 1
This task starts you off nice and gently by asking you to create two `<input>` elements, for a user's ID and password, along with a submit button.
1. Create appropriate inputs for user ID and password.
2. You should also associate them with their text labels semantically.
3. Create a submit button inside the remaining list item, with button text of "Log in".
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/html/forms/tasks/basic-controls/basic-controls1.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/basic-controls/basic-controls1-download.html) to work in your own editor or in an online editor.
## Basic controls 2
The next task requires you to create working sets of checkboxes and radio buttons, from the provided text labels.
1. Turn the first `<fieldset>`'s contents into a set of radio buttons — you should only be able to select one pony character at once.
2. Make it so that the first radio button is selected upon page load.
3. Turn the second `<fieldset>`'s content into a set of checkboxes.
4. Add a couple more hotdog choices of your own.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/html/forms/tasks/basic-controls/basic-controls2.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/basic-controls/basic-controls2-download.html) to work in your own editor or in an online editor.
## Basic controls 3
The final task in this set requires you to create a file picker.
1. Create a basic file picker.
2. Allow the user to pick multiple files at once.
3. Allow the file picker to accept JPG and PNG images only.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/html/forms/tasks/basic-controls/basic-controls3.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/basic-controls/basic-controls3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/user_input_methods/index.md | ---
title: User input methods and controls
slug: Learn/Forms/User_input_methods
page-type: guide
---
Web forms require user input. When designing web forms, or really any web content, it's important to consider how users interact with their devices and browsers. Web user input goes beyond simple mouse and keyboard: think of touchscreens for example.
In this article, we take a look at the different ways users interact with forms and other web content and provide recommendations for managing user input, real-world examples, and links to further information.
As you develop more complex and interactive forms or other UI features, there are many HTML elements and JavaScript APIs you may want to investigate. For example, you may want to create custom form controls that require non-semantic elements to be content editable. You might want to support touch events, determine or control the screen's orientation, make a form take up the full screen, or enable drag and drop features. This guide introduces all these features, and directs you to more information on each topic.
To provide a good experience to the greatest number of users, you need to support multiple input methods, including mouse, keyboard, finger touch, and so on. Available input mechanisms depend on the capabilities of the device running the application.
You should always be mindful of keyboard accessibility — many web users only use the keyboard to navigate websites and apps, and locking them out of your functionality is a bad idea.
## Topics covered
- To support touch screen displays, [touch events](/en-US/docs/Web/API/Touch_events) interpret finger activity on touch-based user interfaces from mobile devices, to refrigerator panels, to museum kiosk displays.
- The [Fullscreen API](/en-US/docs/Web/API/Fullscreen_API) allows you to display your content in fullscreen mode, which is needed if your form is being served on a refrigerator or museum kiosk.
- When you need to create a custom form control, like a rich-text editor, the [`contentEditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) attribute enables creating editable controls from normally non-editable HTML elements.
- The [Drag and Drop API](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) allows users to drag elements around a page and drop them in different locations. This can help improve the user experience when it comes to selecting files for upload or reordering content modules within a page.
- When screen orientation matters for your layout, you can use [CSS media queries](/en-US/docs/Web/CSS/@media/orientation) to style your forms based on the browser orientation, or even use the [Screen Orientation API](/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation) to read the screen orientation state and perform other actions.
The following sections provide a set of recommendations and best practices for enabling the widest possible set of users to use your websites and applications.
## Supporting common input mechanisms
### Keyboard
Most users will use a keyboard to enter data into your form controls. Some will also use the keyboard to navigate to those form controls. To be accessible, and for better user experience, it's important to properly [label all form controls](/en-US/docs/Learn/Forms/Your_first_form#the_label_input_and_textarea_elements). When each form control has a correctly associated {{htmlelement("label")}}, your form will be fully accessible to all, most notably anyone navigating your form with a keyboard, a screen reader, and possibly no screen at all.
If you want to add additional keyboard support, such as validating a form control when a specific key is hit, you can use event listeners to capture and react to keyboard events. For example, if you want to add controls when any key gets pressed, you need to add an event listener on the window object:
```js
window.addEventListener("keydown", handleKeyDown, true);
window.addEventListener("keyup", handleKeyUp, true);
```
`handleKeyDown` and `handleKeyUp` are functions defining the control logic to be executed when the `keydown` and `keyup` events are fired.
> **Note:** Have a look at the [Events reference](/en-US/docs/Web/Events) and {{domxref("KeyboardEvent")}} guide to find out more about keyboard events.
### Mouse
You can also capture mouse and other pointer events. The events occurring when the user interacts with a pointing device such as a mouse are represented by the {{domxref("MouseEvent")}} DOM Interface. Common mouse events include [`click`](/en-US/docs/Web/API/Element/click_event), [`dblclick`](/en-US/docs/Web/API/Element/dblclick_event), [`mouseup`](/en-US/docs/Web/API/Element/mouseup_event), and [`mousedown`](/en-US/docs/Web/API/Element/mousedown_event). The list of all events using the Mouse Event Interface is provided in the [Events reference](/en-US/docs/Web/Events).
When the input device is a mouse, you can also control user input through the Pointer Lock API and implement Drag & Drop (see below). You can also [use CSS to test for pointer device](/en-US/docs/Learn/CSS/CSS_layout/Media_queries#use_of_pointing_devices) support.
### Finger touch
To provide additional support for touchscreen devices, it's a good practice to take into consideration the different capabilities in terms of screen resolution and user input. [Touch events](/en-US/docs/Web/API/Touch_events) can help you implement interactive elements and common interaction gestures on touchscreen devices.
If you want to use touch events, you need to add event listeners and specify handler functions, which will be called when the event gets fired:
```js
element.addEventListener("touchstart", handleStart, false);
element.addEventListener("touchcancel", handleCancel, false);
element.addEventListener("touchend", handleEnd, false);
element.addEventListener("touchmove", handleMove, false);
```
where `element` is the DOM element you want to register the touch events on.
> **Note:** For further information about what you can do with touch events, please read our [touch events guide](/en-US/docs/Web/API/Touch_events).
### Pointer Events
Mice aren't the only pointing devices. Your user's devices may incorporate multiple forms of input, like mouse, finger touch, and pen input. Each of these pointers has a different size. The [Pointer Events API](/en-US/docs/Web/API/Pointer_events) may come in handy if you need to manage events across devices by normalizing the handling of each one. A pointer can be any point of contact on the screen made by a mouse cursor, pen, touch (including multi-touch), or other pointing input device.
The events for handling generic pointer input look a lot like those for mouse: `pointerdown`, `pointermove`, `pointerup`, `pointerover`, `pointerout`, etc. The [`PointerEvent` interface](/en-US/docs/Web/API/PointerEvent) provides all the details you may want to capture about the pointer device, including its size, pressure, and angle.
## Implement controls
### Screen Orientation
If you need slightly different layouts depending on whether the user is in portrait or landscape mode, you can use [CSS media queries](/en-US/docs/Learn/CSS/CSS_layout/Media_queries#media_feature_rules) to define CSS for different layouts or form control widths based on the size or orientation of the screen when [styling web forms](/en-US/docs/Learn/Forms/Styling_web_forms).
When screen orientation matters for your form, you can read the screen orientation state, be informed when this state changes, and able to lock the screen orientation to a specific state (usually portrait or landscape) through the [Screen Orientation API](/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation).
- Orientation data can be retrieved through {{domxref("screenOrientation.type")}} or with CSS through the [`orientation`](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries#orientation) media feature.
- When the screen orientation changes, the {{domxref("ScreenOrientation.change_event", "change")}} event is fired on the screen object.
- Locking the screen orientation is made possible by invoking the {{domxref("ScreenOrientation.lock()")}} method.
- The {{domxref("ScreenOrientation.unlock()")}} method removes all the previous screen locks that have been set.
> **Note:** More information about the Screen Orientation API can be found in [Managing screen orientation](/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation).
### Fullscreen
If you need to present your form in fullscreen mode, such as when your form is displayed on a museum kiosk, toll booth, or really any publically displayed user interface, it is possible to do so by calling {{domxref("Element.requestFullscreen()")}} on that element:
```js
const elem = document.getElementById("myForm");
if (elem.requestFullscreen) {
elem.requestFullscreen();
}
```
> **Note:** To find out more about adding fullscreen functionality to your application, read our documentation about [using fullscreen mode](/en-US/docs/Web/API/Fullscreen_API).
### Drag & Drop
A common user interaction is the physical dragging of elements to be dropped elsewhere on the screen. Drag and drop can help improve the user experience when it comes to selecting files for upload or reordering content modules within a page. There's an API for that!
The [Drag & Drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) API enables users to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there.
Here is an example that allows a section of content to be dragged.
```html
<div
draggable="true"
ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">
This text <strong>may</strong> be dragged.
</div>
```
in which we:
- Set the [`draggable`](/en-US/docs/Web/HTML/Global_attributes#draggable) attribute to `true` on the element that you wish to make draggable.
- Add a listener for the [`dragstart`](/en-US/docs/Web/API/HTMLElement/dragstart_event) event and set the drag data within this listener.
> **Note:** You can find more information in the [MDN Drag & Drop documentation](/en-US/docs/Web/API/HTML_Drag_and_Drop_API).
### contentEditable
Generally, you should use a {{HTMLElement("textarea")}} or an appropriate {{HTMLElement("input")}} type within a {{HTMLElement("form")}} to collect data from users, along with a descriptive {{HTMLElement("label")}}. But these elements may not meet your needs. For example, rich text editors capture italic, bold, and normal text, but no native form control captures rich text. This use case requires you to create a custom control that is stylable _and_ editable. There's an attribute for that!
Any DOM element can be made directly editable using the [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes#contenteditable) attribute.
```css hidden
div {
width: 300px;
height: 130px;
border: 1px solid gray;
}
```
```html
<div contenteditable="true">This text can be edited by the user.</div>
```
The `contenteditable` attribute automatically adds the element to the document's default tabbing order, meaning the [`tabindex`](/en-US/docs/Web/HTML/Global_attributes#tabindex) attribute does not need to be added. However, when using non-semantic elements for data entry when [creating your own form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls), you will need to add JavaScript and [ARIA](/en-US/docs/Web/Accessibility/ARIA) to retrofit the element with form control functionality for everything else.
To provide a good user experience, any custom form control you create must be accessible and function like native form controls:
- The element's [`role`](/en-US/docs/Web/Accessibility/ARIA/Roles), [label](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby), and [description](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) need to be added with ARIA.
- All user input methods needs to be supported, including [keyboard](#keyboard), [mouse](#mouse), [touch](#finger_touch), and [pointer](#pointer_events) events, all described above.
- JavaScript is required to handle functionality such as [validation](/en-US/docs/Learn/Forms/Form_validation), [submission](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data), and [saving](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript) of user-updated content.
{{EmbedLiveSample("contentEditable")}}
> **Note:** Examples and other resources can be found in the [Content Editable guide](/en-US/docs/Web/HTML/Global_attributes/contenteditable).
## Tutorials
- [Touch events Guide](/en-US/docs/Web/API/Touch_events)
- [Managing screen orientation](/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation)
- [Using fullscreen mode](/en-US/docs/Web/API/Fullscreen_API)
- [Drag Operations Guide](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations)
- [Form validation](/en-US/docs/Learn/Forms/Form_validation)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
## Reference
- {{domxref("MouseEvent")}} interface
- {{domxref("KeyboardEvent")}} interface
- [Touch events](/en-US/docs/Web/API/Touch_events) API
- [Pointer Lock](/en-US/docs/Web/API/Pointer_Lock_API) API
- [Screen Orientation](/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation) API
- [Fullscreen](/en-US/docs/Web/API/Fullscreen_API) API
- [Drag & Drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) API
- HTML [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) attribute
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/test_your_skills_colon__form_validation/index.md | ---
title: "Test your skills: Form validation"
slug: Learn/Forms/Test_your_skills:_Form_validation
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Client-side form validation](/en-US/docs/Learn/Forms/Form_validation) article.
> **Note:** You can try solutions in the interactive editors on this page or in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Form validation 1
In this task, we are providing you with a simple support query form, and we want you to add some validation features to it:
1. Make all of the input fields mandatory to complete before the form can be submitted.
2. Change the type of the "Email address" and "Phone number" fields to make the browser apply some more specific validation suitable for the data being asked for.
3. Give the "User name" field a required length of between 5 and 20 characters, the "Phone number" field a maximum length of 15 characters, and the "Comment" field a maximum length of 200 characters.
Try submitting your form — it should refuse to submit until the above constraints are followed, and give suitable error messages. To help, you might want to consider adding some simple CSS to show when a form field is valid or invalid.
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/form-validation/form-validation1-download.html) to work in your own editor or in an online editor.
## Form validation 2
Now we want you to take the same form you saw in the previous task (use your previous answer if you want to), and add some more specific pattern validation to the first three fields using regular expressions.
1. All of the user names in our application consist of a single letter, followed by a dot, followed by three or more letters or numbers. All letters should be lowercase.
2. All of the email addresses for our users consist of one or more letters (lower or upper case) or numbers, followed by "@bigcorp.eu".
3. Remove the length validation from the phone number field if it is present, and set it so that it accepts 10 digits — either 10 digits in a row, or a pattern of three digits, three digits, then four digits, separated by either spaces, dashes, or dots.
> **Note:** Regular expressions are really challenging if you are new to them, but don't despair — have a go and see where you get to; there is no shame in asking for some help. You can find everything you need to answer these questions at our [regular expression reference](/en-US/docs/Web/JavaScript/Guide/Regular_expressions), and by searching on [Stack Overflow](https://stackoverflow.com/).
Again, to help you might want to consider adding some simple CSS to show when a form field is valid or invalid.
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/form-validation/form-validation2-download.html) to work in your own editor or in an online editor.
## Form validation 3
In our final task for this set, we are providing you with a similar example to what you saw in the accompanying article — a simple email address entry input. We would like you to use the constraint validation API, plus some form validation attributes, to program some custom error messages.
1. Make the input mandatory to fill in, and give it a minimum length of 10 characters.
2. Add an event listener that checks whether the inputted value is an email address, and whether it is long enough. If it doesn't look like an email address or is too short, provide the user with appropriate custom error messages.
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/html/forms/tasks/form-validation/form-validation3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/forms | data/mdn-content/files/en-us/learn/forms/styling_web_forms/index.md | ---
title: Styling web forms
slug: Learn/Forms/Styling_web_forms
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Forms/Other_form_controls","Learn/Forms/Advanced_form_styling","Learn/Forms")}}
In the previous few articles, we showed how to create web forms in HTML. Now, we'll show how to style them in [CSS](/en-US/docs/Web/CSS).
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">HTML</a> and
<a href="/en-US/docs/Learn/CSS/First_steps">CSS</a>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the issues behind styling forms, and learn some of the
basic styling techniques that will be useful to you.
</td>
</tr>
</tbody>
</table>
## Challenges in styling form widgets
### History
In 1995, [the HTML 2 specification](https://www.ietf.org/rfc/rfc1866.txt) introduced form controls (a.k.a. "form widgets", or "form elements"). But CSS wasn't released until late 1996, and wasn't supported by most browsers until years afterward; so, in the interim, browsers relied on the underlying operating system to render form widgets.
Even with CSS available, browser vendors were reluctant at first to make form elements stylable, because users were so accustomed to the looks of their respective browsers. But things have changed, and forms widgets are now mostly stylable, with a few exceptions.
### Types of widgets
#### Easy-to-style
1. {{HTMLElement("form")}}
2. {{HTMLElement("fieldset")}} and {{HTMLElement("legend")}}
3. Single-line text {{HTMLElement("input")}}s (e.g. type text, url, email), except for [`<input type="search">`](/en-US/docs/Web/HTML/Element/input/search).
4. Multi-line {{HTMLElement("textarea")}}
5. Buttons (both {{HTMLElement("input")}} and {{HTMLElement("button")}})
6. {{HTMLElement("label")}}
7. {{HTMLElement("output")}}
#### Harder-to-style
- Checkboxes and radio buttons
- [`<input type="search">`](/en-US/docs/Web/HTML/Element/input/search)
The article [Advanced form styling](/en-US/docs/Learn/Forms/Advanced_form_styling) shows how to style these.
#### Having internals can't be styled in CSS alone
- [`<input type="color">`](/en-US/docs/Web/HTML/Element/input/color)
- Date-related controls such as [`<input type="datetime-local">`](/en-US/docs/Web/HTML/Element/input/datetime-local)
- [`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range)
- [`<input type="file">`](/en-US/docs/Web/HTML/Element/input/file)
- Elements involved in creating dropdown widgets, including {{HTMLElement("select")}}, {{HTMLElement("option")}}, {{HTMLElement("optgroup")}} and {{HTMLElement("datalist")}}.
- {{HTMLElement("progress")}} and {{HTMLElement("meter")}}
For example, the date picker calendar, and the button on \<select> that displays an options list when clicked, can't be styled using CSS alone.
The articles [Advanced form styling](/en-US/docs/Learn/Forms/Advanced_form_styling) and [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls) describe how to style these.
> **Note:** some proprietary CSS pseudo-elements, such as {{cssxref('::-moz-range-track')}}, are capable of styling such internal components, but these aren't consistent across browsers, so aren't very reliable. We will mention these later.
## Styling simple form widgets
The "easy-to-style" widgets in the previous section may be styled using techniques from the articles [Your first form](/en-US/docs/Learn/Forms/Your_first_form) and [CSS building blocks](/en-US/docs/Learn/CSS/Building_blocks). There are also special selectors — [UI pseudo-classes](/en-US/docs/Learn/Forms/UI_pseudo-classes) — that enable styling based on the current state of the UI.
We'll walk through an example at the end of this article — but first, here are some special aspects of form styling that are worth knowing about.
### Fonts and text
CSS font and text features can be used easily with any widget (and yes, you can use {{cssxref("@font-face")}} with form widgets). However, browser behavior is often inconsistent. By default, some widgets do not inherit {{cssxref("font-family")}} and {{cssxref("font-size")}} from their parents. Many browsers use the system's default appearance instead. To make your forms' appearance consistent with the rest of your content, you can add the following rules to your stylesheet:
```css
button,
input,
select,
textarea {
font-family: inherit;
font-size: 100%;
}
```
The {{cssxref('inherit')}} property value causes the property value to match the computed value of the property of its parent element; inheriting the value of the parent.
The screenshots below show the difference. On the left is the default rendering of an `<input type="text">`, `<input type="date">`, {{htmlelement('select')}}, {{htmlelement('textarea')}}, `<input type="submit">`, and a `<button>` in Chrome on macOS, with the platform's default font style in use. On the right are the same elements, with our above style rule applied.

The defaults differed in a number of ways. Inheriting should change their fonts to that of the parent's font family — in this case, the default serif font of the parent container. They all do, with a strange exception — `<input type="submit">` does not inherit from the parent paragraph in Chrome. Rather, it uses the {{cssxref('font-family#Values', 'font-family: system-ui')}}. This is another reason to use `<button>` elements over their equivalent input types!
There's a lot of debate as to whether forms look better using the system default styles, or customized styles designed to match your content. This decision is yours to make, as the designer of your site, or web application.
### Box sizing
All text fields have complete support for every property related to the CSS box model, such as {{cssxref("width")}}, {{cssxref("height")}}, {{cssxref("padding")}}, {{cssxref("margin")}}, and {{cssxref("border")}}. As before, however, browsers rely on the system default styles when displaying these widgets. It's up to you to define how you wish to blend them into your content. If you want to keep the native look and feel of the widgets, you'll face a little difficulty if you want to give them a consistent size.
**This is because each widget has its own rules for border, padding, and margin.** To give the same size to several different widgets, you can use the {{cssxref("box-sizing")}} property along with some consistent values for other properties:
```css
input,
textarea,
select,
button {
width: 150px;
padding: 0;
margin: 0;
box-sizing: border-box;
}
```
In the screenshot below, the left column shows the default rendering of an `<input type="radio">`, `<input type="checkbox">`, `<input type="range">`, `<input type="text">`, `<input type="date">`, {{htmlelement('select')}}, {{htmlelement('textarea')}}, `<input type="submit">`, and {{htmlelement('button')}}. The right column on the other hand shows the same elements with our above rule applied to them. Notice how this lets us ensure that all of the elements occupy the same amount of space, despite the platform's default rules for each kind of widget.

What may not be apparent via the screenshot is that the radio and checkbox controls still look the same, but they are centered in the 150px of horizontal space provided by the {{cssxref('width')}} property. Other browsers may not center the widgets, but they do adhere to the space allotted.
### Legend placement
The {{HTMLElement("legend")}} element is okay to style, but it can be a bit tricky to control the placement of it. By default, it is always positioned over the top border of its {{HTMLElement("fieldset")}} parent, near the top left corner. To position it somewhere else, for example inside the fieldset somewhere, or near the bottom left corner, you need to rely on the positioning.
Take the following example:
{{EmbedGHLiveSample("learning-area/html/forms/native-form-widgets/positioned-legend.html", '100%', 400)}}
To position the legend in this manner, we used the following CSS (other declarations removed for brevity):
```css
fieldset {
position: relative;
}
legend {
position: absolute;
bottom: 0;
right: 0;
}
```
The `<fieldset>` needs to be positioned too, so that the `<legend>` is positioned relative to it (otherwise the `<legend>` would be positioned relative to the `<body>`).
The {{HTMLElement("legend")}} element is very important for accessibility — it will be spoken by assistive technologies as part of the label of each form element inside the fieldset — but using a technique like the one above is fine. The legend contents will still be spoken in the same way; it is just the visual position that has changed.
> **Note:** You could also use the {{cssxref("transform")}} property to help you with positioning your `<legend>`. However, when you position it with for example a `transform: translateY();`, it moves but leaves an ugly gap in the `<fieldset>` border, which is not easy to get rid of.
## A specific styling example
Let's look at a concrete example of how to style an HTML form. We will build a fancy-looking "postcard" contact form; [see here for the finished version](https://mdn.github.io/learning-area/html/forms/postcard-example/).
If you want to follow along with this example, make a local copy of our [postcard-start.html file](https://github.com/mdn/learning-area/blob/main/html/forms/postcard-example/postcard-start.html), and follow the below instructions.
### The HTML
The HTML is only slightly more involved than the example we used in [the first article of this guide](/en-US/docs/Learn/Forms/Your_first_form); it just has a few extra IDs and a heading.
```html
<form>
<h1>to: Mozilla</h1>
<div id="from">
<label for="name">from:</label>
<input type="text" id="name" name="user_name" />
</div>
<div id="reply">
<label for="mail">reply:</label>
<input type="email" id="mail" name="user_email" />
</div>
<div id="message">
<label for="msg">Your message:</label>
<textarea id="msg" name="user_message"></textarea>
</div>
<div class="button">
<button type="submit">Send your message</button>
</div>
</form>
```
Add the above code into the body of your HTML.
### Organizing your assets
This is where the fun begins! Before we start coding, we need three additional assets:
1. [The postcard background](background.jpg) — download this image and save it in the same directory as your working HTML file.
2. A typewriter font: [The "Mom's Typewriter" font from dafont.com](https://www.dafont.com/moms-typewriter.font?back=theme) — download the TTF file into the same directory as above.
3. A hand-drawn font: [The "Journal" font from dafont.com](https://www.dafont.com/journal.font) — download the TTF file into the same directory as above.
Your fonts need some more processing before you start:
1. Go to the fontsquirrel.com [Webfont Generator](https://www.fontsquirrel.com/tools/webfont-generator).
2. Using the form, upload both your font files and generate a webfont kit. Download the kit to your computer.
3. Unzip the provided zip file.
4. Inside the unzipped contents you will find some font files (at the time of writing, two `.woff` files and two `.woff2` files; they might vary in the future.) Copy these files into a directory called fonts, in the same directory as before. We are using two different files for each font to maximize browser compatibility; see our [Web fonts](/en-US/docs/Learn/CSS/Styling_text/Web_fonts) article for a lot more information.
### The CSS
Now we can dig into the CSS for the example. Add all the code blocks shown below inside the {{htmlelement("style")}} element, one after another.
#### Overall layout
First, we prepare by defining our {{cssxref("@font-face")}} rules, and all the basic styles set on the {{HTMLElement("body")}} and {{HTMLElement("form")}} elements. If the fontsquirrel output was different from what we described above, you can find the correct `@font-face` blocks inside your downloaded webfont kit, in the `stylesheet.css` file (you'll need to replace the below `@font-face` blocks with them, and update the paths to the font files):
```css
@font-face {
font-family: "handwriting";
src:
url("fonts/journal-webfont.woff2") format("woff2"),
url("fonts/journal-webfont.woff") format("woff");
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: "typewriter";
src:
url("fonts/momot___-webfont.woff2") format("woff2"),
url("fonts/momot___-webfont.woff") format("woff");
font-weight: normal;
font-style: normal;
}
body {
font: 1.3rem sans-serif;
padding: 0.5em;
margin: 0;
background: #222;
}
form {
position: relative;
width: 740px;
height: 498px;
margin: 0 auto;
padding: 1em;
box-sizing: border-box;
background: #fff url(background.jpg);
/* we create our grid */
display: grid;
grid-gap: 20px;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: 10em 1em 1em 1em;
}
```
Notice that we've used some [CSS Grid](/en-US/docs/Web/CSS/CSS_grid_layout) and [Flexbox](/en-US/docs/Web/CSS/CSS_flexible_box_layout) to lay out the form. Using this we can easily position our elements, including the title and all the form elements:
```css
h1 {
font:
1em "typewriter",
monospace;
align-self: end;
}
#message {
grid-row: 1 / 5;
}
#from,
#reply {
display: flex;
}
```
#### Labels and controls
Now we can start working on the form elements themselves. First, let's ensure that the {{HTMLElement("label")}}s are given the right font:
```css
label {
font:
0.8em "typewriter",
sans-serif;
}
```
The text fields require some common rules. In other words, we remove their {{cssxref("border","borders")}} and {{cssxref("background","backgrounds")}}, and redefine their {{cssxref("padding")}} and {{cssxref("margin")}}:
```css
input,
textarea {
font:
1.4em/1.5em "handwriting",
cursive,
sans-serif;
border: none;
padding: 0 10px;
margin: 0;
width: 80%;
background: none;
}
```
When one of these fields gains focus, we highlight them with a light grey, transparent, background (it is always important to have focus style, for usability and keyboard accessibility):
```css
input:focus,
textarea:focus {
background: rgb(0 0 0 / 10%);
border-radius: 5px;
}
```
Now that our text fields are complete, we need to adjust the display of the single and multiple-line text fields to match, since they won't typically look the same using the defaults.
#### Tweaking the textareas
{{HTMLElement("textarea")}} elements default to being rendered as an inline-block element. The two important things here are the {{cssxref("resize")}} and {{cssxref("overflow")}} properties. While our design is a fixed-size design, and we could use the `resize` property to prevent users from resizing our multi-line text field, it is best to not prevent users from resizing a textarea if they so choose. The {{cssxref("overflow")}} property is used to make the field render more consistently across browsers. Some browsers default to the value `auto`, while some default to the value `scroll`. In our case, it's better to be sure everyone will use `auto`:
```css
textarea {
display: block;
padding: 10px;
margin: 10px 0 0 -10px;
width: 100%;
height: 90%;
border-right: 1px solid;
/* resize : none; */
overflow: auto;
}
```
#### Styling the submit button
The {{HTMLElement("button")}} element is really convenient to style with CSS; you can do whatever you want, even using [pseudo-elements](/en-US/docs/Web/CSS/Pseudo-elements):
```css
button {
padding: 5px;
font: bold 0.6em sans-serif;
border: 2px solid #333;
border-radius: 5px;
background: none;
cursor: pointer;
transform: rotate(-1.5deg);
}
button:after {
content: " >>>";
}
button:hover,
button:focus {
background: #000;
color: #fff;
}
```
### The final result
And voilà! Your form should now look like this:

> **Note:** If your example does not work quite as you expected and you want to check it against our version, you can find it on GitHub — see it [running live](https://mdn.github.io/learning-area/html/forms/postcard-example/) (also see [the source code](https://github.com/mdn/learning-area/tree/main/html/forms/postcard-example)).
## Test your skills
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see [Test your skills: Styling basics](/en-US/docs/Learn/Forms/Test_your_skills:_Styling_basics).
## Summary
As you can see, as long as we want to build forms with just text fields and buttons, it's easy to style them using CSS. [In the next article](/en-US/docs/Learn/Forms/Advanced_form_styling), we will see how to handle form widgets which fall into the "bad" and "ugly" categories.
{{PreviousMenuNext("Learn/Forms/Other_form_controls","Learn/Forms/Advanced_form_styling","Learn/Forms")}}
### Advanced Topics
- [How to build custom form controls](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls)
- [Sending forms through JavaScript](/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript)
- [Property compatibility table for form widgets](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
| 0 |
data/mdn-content/files/en-us/learn | data/mdn-content/files/en-us/learn/tools_and_testing/index.md | ---
title: Tools and testing
slug: Learn/Tools_and_testing
page-type: learn-topic
---
{{LearnSidebar}}
Once you've started to become comfortable programming with core web technologies (like HTML, CSS, and JavaScript), and you start to get more experience, read more resources, and learn more tips and tricks, you'll start to come across all kind of tools, from JavaScript frameworks, to testing and automation tools, and more besides. As your web projects become larger and more complex, you'll want to start taking advantage of some of these tools, working out a reliable toolchain to give your development process superpowers.
On top of that, we still need to keep cross-browser support in the forefront of our minds, and make sure that our code follows best practices that allow our projects to work across different browsers and devices that our users are using to browse the Web, and be usable by people with disabilities.
Working out what tools you should be using can be a difficult process, so we have written this set of articles to inform you of what types of tool are available, what they can do for you, and how to make use of the current industry favorites.
> **Note:** We have referenced a number of tools in this topic, not because we endorse them or think they are the best, but because we know they work and have good industry support. In most cases there are other tools available, old ones will go out of fashion, and new ones will no doubt appear.
> **Callout:**
>
> #### Looking to become a front-end web developer?
>
> We have put together a course that includes all the essential information you need to
> work towards your goal.
>
> [**Get started**](/en-US/docs/Learn/Front-end_web_developer)
## Prerequisites
You should really learn the basics of the core [HTML](/en-US/docs/Learn/HTML), [CSS](/en-US/docs/Learn/CSS), and [JavaScript](/en-US/docs/Learn/JavaScript) languages first before attempting to use many of the tools detailed here. For example, you'll need to know the fundamentals of these languages before you start debugging problems in complex web code, making effective use of JavaScript frameworks, or writing tests and running them against your code using test runners.
In addition, you should start with the first module in this topic, which gives a useful overview of the general area.
## Modules
- [Understanding client-side web development tools](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools)
- : Client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. We finish up by providing a complete toolchain example showing you how to get productive.
- [Understanding client-side JavaScript frameworks](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks)
- : JavaScript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications. Many modern companies use frameworks as a standard part of their tooling, so many front-end development jobs now require framework experience. This module gives you some fundamental background knowledge about how client-side frameworks work and how they fit into your toolset, before moving on to tutorial series covering some of today's most popular ones.
- [Git and GitHub](/en-US/docs/Learn/Tools_and_testing/GitHub)
- : All developers will use some kind of **version control system** (**VCS**), a tool to allow them to collaborate with other developers on a project without danger of them overwriting each other's work, and roll back to previous versions of the code base if a problem is discovered later on. The most popular VCS (at least among web developers) is **Git**, along with **GitHub**, a site that provides hosting for your repositories and several tools for working with them. This module aims to teach you what you need to know about both of them.
- [Cross browser testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing)
- : This module looks specifically at the area of testing web projects across different browsers. Here we look at identifying your target audience (e.g. what users, browsers and devices do you most need to worry about?), how to go about testing, the main issues that you'll face with different types of code and how to fix/mitigate those, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing.
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing | data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing/index.md | ---
title: Cross browser testing
slug: Learn/Tools_and_testing/Cross_browser_testing
page-type: learn-module
---
{{LearnSidebar}}
This module focuses on testing web projects across different browsers. We look at identifying your target audience (e.g. what users, browsers, and devices do you most need to worry about?), how to go about doing testing, the main issues that you'll face with different types of code and how to mitigate them, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing.
> **Callout:**
>
> #### Looking to become a front-end web developer?
>
> We have put together a course that includes all the essential information you need to
> work towards your goal.
>
> [**Get started**](/en-US/docs/Learn/Front-end_web_developer)
## Prerequisites
You should really learn the basics of the core [HTML](/en-US/docs/Learn/HTML), [CSS](/en-US/docs/Learn/CSS), and [JavaScript](/en-US/docs/Learn/JavaScript) languages first before attempting to use the tools detailed here.
## Guides
- [Introduction to cross browser testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction)
- : This article starts the module off by providing an overview of the topic of cross browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?"
- [Strategies for carrying out testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies)
- : Next, we drill down into carrying out testing, looking at identifying a target audience (e.g. what browsers, devices, and other segments should you make sure are tested), lo-fi testing strategies (get yourself a range of devices and some virtual machines and do ad hoc tests when needed), higher tech strategies (automation, using dedicated testing apps), and testing with user groups.
- [Handling common HTML and CSS problems](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS)
- : With the scene set, we'll now look specifically at the common cross-browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handling CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
- [Handling common JavaScript problems](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript)
- : Now we'll look at common cross-browser JavaScript problems and how to fix them. This includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern JavaScript features working in older browsers, and more.
- [Handling common accessibility problems](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility)
- : Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues.
- [Implementing feature detection](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Feature_detection)
- : Feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather than crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as `@supports`.
- [Introduction to automated testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing)
- : Manually running tests on several browsers and devices, several times per day, can get tedious and time-consuming. To handle this efficiently, you should become familiar with automation tools. In this article, we look at what is available, how to use task runners, and the basics of how to use commercial browser test automation apps such as Sauce Labs and Browser Stack.
- [Setting up your own test automation environment](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment)
- : In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial apps like the ones discussed in the previous article.
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing | data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing/feature_detection/index.md | ---
title: Implementing feature detection
slug: Learn/Tools_and_testing/Cross_browser_testing/Feature_detection
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/Accessibility","Learn/Tools_and_testing/Cross_browser_testing/Automated_testing", "Learn/Tools_and_testing/Cross_browser_testing")}}
Feature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn't), so that the browser can always provide a working experience rather than crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as `@supports`.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages; an idea
of the high-level
<a
href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction"
>principles of cross-browser testing</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand what the concept of feature detection is, and be able to
implement suitable solutions in CSS and JavaScript.
</td>
</tr>
</tbody>
</table>
## The concept of feature detection
The idea behind feature detection is that you can run a test to determine whether a feature is supported in the current browser, and then conditionally run code to provide an acceptable experience both in browsers that _do_ support the feature, and browsers that _don't_. If you don't do this, browsers that don't support the features you are using in your code may not display your sites properly or might fail altogether, creating a bad user experience.
Let's recap and look at the example we touched on in our [Handling common JavaScript problems](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript#feature_detection) — the [Geolocation API](/en-US/docs/Web/API/Geolocation_API) (which exposes available location data for the device the web browser is running on) has the main entry point for its use, a `geolocation` property available on the global [Navigator](/en-US/docs/Web/API/Navigator) object. Therefore, you can detect whether the browser supports geolocation or not by using something like the following:
```js
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function (position) {
// show the location on a map, such as the Google Maps API
});
} else {
// Give the user a choice of static maps
}
```
Before we move on, we'd like to say one thing upfront — don't confuse feature detection with **browser sniffing** (detecting what specific browser is accessing the site) — this is a terrible practice that should be discouraged at all costs. See [Using bad browser sniffing code](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript#using_bad_browser_sniffing_code) for more details.
## Writing your own feature detection tests
In this section, we'll look at implementing your own feature detection tests, in both CSS and JavaScript.
### CSS
You can write tests for CSS features by testing for the existence of _[element.style.property](/en-US/docs/Web/API/HTMLElement/style)_ (e.g. `paragraph.style.rotate`) in JavaScript.
A classic example might be to test for [Subgrid](/en-US/docs/Web/CSS/CSS_grid_layout/Subgrid) support in a browser; for browsers that support the `subgrid` value for a subgrid value for [`grid-template-columns`](/en-US/docs/Web/CSS/grid-template-columns) and [`grid-template-rows`](/en-US/docs/Web/CSS/grid-template-rows), we can use subgrid in our layout. For browsers that don't, we could use regular grid that works fine but is not as cool-looking.
Using this as an example, we could include a subgrid stylesheet if the value is supported and a regular grid stylesheet if not. To do so, we could include two stylesheets in the head of our HTML file: one for all the styling, and one that implements the default layout if subgrid is not supported:
```html
<link href="basic-styling.css" rel="stylesheet" />
<link class="conditional" href="grid-layout.css" rel="stylesheet" />
```
Here, `basic-styling.css` handles all the styling that we want to give to every browser. We have two additional CSS files, `grid-layout.css` and `subgrid-layout.css`, which contain the CSS we want to selectively apply to browsers depending on their support levels.
We use JavaScript to test the support for the subgrid value, then update the `href` of our conditional stylesheet based on browser support.
We can add a `<script></script>` to our document, filled with the following JavaScript
```js
const conditional = document.querySelector(".conditional");
if (CSS.supports("grid-template-columns", "subgrid")) {
conditional.setAttribute("href", "subgrid-layout.css");
}
```
In our conditional statement, we test to see if the{{cssxref("grid-template-columns")}} property supports the `subgrid` value using [`CSS.supports()`](/en-US/docs/Web/API/CSS/supports_static).
#### @supports
CSS has a native feature detection mechanism: the {{cssxref("@supports")}} at-rule. This works in a similar manner to [media queries](/en-US/docs/Web/CSS/CSS_media_queries) except that instead of selectively applying CSS depending on a media feature like a resolution, screen width or aspect ratio, it selectively applies CSS depending on whether a CSS feature is supported, similar to `CSS.supports()`.
For example, we could rewrite our previous example to use `@supports`:
```css
@supports (grid-template-columns: subgrid) {
main {
display: grid;
grid-template-columns: repeat(9, 1fr);
grid-template-rows: repeat(4, minmax(100px, auto));
}
.item {
display: grid;
grid-column: 2 / 7;
grid-row: 2 / 4;
grid-template-columns: subgrid;
grid-template-rows: repeat(3, 80px);
}
.subitem {
grid-column: 3 / 6;
grid-row: 1 / 3;
}
}
```
This at-rule block applies the CSS rule within only if the current browser supports the `grid-template-columns: subgrid;` declaration. For a condition with a value to work, you need to include a complete declaration (not just a property name) and NOT include the semicolon on the end.
`@supports` also has `AND`, `OR`, and `NOT` logic available — the other block applies the regular grid layout if the subgrid option is not available:
```css
@supports not (grid-template-columns: subgrid) {
/* rules in here */
}
```
This is more convenient than the previous example — we can do all of our feature detection in CSS, no JavaScript required, and we can handle all the logic in a single CSS file, cutting down on HTTP requests. For this reason it is the preferred method of determining browser support for CSS features.
### JavaScript
We already saw an example of a JavaScript feature detection test earlier on. Generally, such tests are done via one of a few common patterns.
Common patterns for detectable features include:
- Members of an object
- : Check whether a particular method or property (typically an entry point into using the API or other feature you are detecting) exists in its parent `Object`.
Our earlier example used this pattern to detect [Geolocation](/en-US/docs/Web/API/Geolocation_API) support by testing the [`navigator`](/en-US/docs/Web/API/Navigator) object for a `geolocation` member:
```js
if ("geolocation" in navigator) {
// Access navigator.geolocation APIs
}
```
- Properties of an element
- : Create an element in memory using {{domxref("Document.createElement()")}} and then check if a property exists on it.
This example shows a way of detecting [Canvas API](/en-US/docs/Web/API/Canvas_API) support:
```js
function supports_canvas() {
return !!document.createElement("canvas").getContext;
}
if (supports_canvas()) {
// Create and draw on canvas elements
}
```
> **Note:** The double `NOT` in the above example (`!!`) is a way to force a return value to become a "proper" boolean value, rather than a {{glossary("Truthy")}}/{{glossary("Falsy")}} value that may skew the results.
- Specific return values of a method on an element
- : Create an element in memory using {{domxref("Document.createElement()")}} and then check if a method exists on it. If it does, check what value it returns. See the feature test in [Dive into HTML Video Format detection](https://diveinto.html5doctor.com/detect.html#video-formats) for an example of this pattern.
- Retention of assigned property value by an element
- : Create an element in memory using {{domxref("Document.createElement()")}}, set a property to a specific value, then check to see if the value is retained. See the feature test in [Dive into HTML \<input> type detection](https://diveinto.html5doctor.com/detect.html#input-types) for an example of this pattern.
Bear in mind that some features are, however, known to be undetectable. In these cases, you'll need to use a different approach, such as using a {{Glossary("Polyfill", "polyfill")}}.
#### matchMedia
We also wanted to mention the {{domxref("Window.matchMedia")}} JavaScript feature at this point too. This is a property that allows you to run media query tests inside JavaScript. It looks like this:
```js
if (window.matchMedia("(max-width: 480px)").matches) {
// run JavaScript in here.
}
```
As an example, our [Snapshot](https://github.com/chrisdavidmills/snapshot) demo makes use of it to selectively apply the Brick JavaScript library and use it to handle the UI layout, but only for the small screen layout (480px wide or less). We first use the `media` attribute to only apply the Brick CSS to the page if the page width is 480px or less:
```html
<link
href="dist/brick.css"
rel="stylesheet"
media="all and (max-width: 480px)" />
```
We then use `matchMedia()` in the JavaScript several times, to only run Brick navigation functions if we are on the small screen layout (in wider screen layouts, everything can be seen at once, so we don't need to navigate between different views).
```js
if (window.matchMedia("(max-width: 480px)").matches) {
deck.shuffleTo(1);
}
```
## Summary
This article covered feature detection in a reasonable amount of detail, going through the main concepts and showing you how to implement your own feature detection tests.
Next up, we'll start looking at automated testing.
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/Accessibility","Learn/Tools_and_testing/Cross_browser_testing/Automated_testing", "Learn/Tools_and_testing/Cross_browser_testing")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing | data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing/javascript/index.md | ---
title: Handling common JavaScript problems
slug: Learn/Tools_and_testing/Cross_browser_testing/JavaScript
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS","Learn/Tools_and_testing/Cross_browser_testing/Accessibility", "Learn/Tools_and_testing/Cross_browser_testing")}}
Now we'll look at common cross-browser JavaScript problems and how to fix them.
This includes information on using browser dev tools to track down and fix problems, using Polyfills and libraries to work around problems, getting modern JavaScript features working in older browsers, and more.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages; an idea of the high-level <a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction">principles of cross browser testing</a>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To be able to diagnose common JavaScript cross-browser problems, and use appropriate tools and techniques to fix them.
</td>
</tr>
</tbody>
</table>
## The trouble with JavaScript
Historically, JavaScript was plagued with cross-browser compatibility problems — back in the 1990s, the main browser choices back then (Internet Explorer and Netscape) had scripting implemented in different language flavors (Netscape had JavaScript, IE had JScript and also offered VBScript as an option), and while at least JavaScript and JScript were compatible to some degree (both based on the {{glossary("ECMAScript")}} specification), things were often implemented in conflicting, incompatible ways, causing developers many nightmares.
Such incompatibility problems persisted well into the early 2000s, as old browsers were still being used and still needed supporting. For example, code to create {{domxref("XMLHttpRequest")}} objects had to have special handling for Internet Explorer 6:
```js
if (window.XMLHttpRequest) {
// Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
```
This is one of the main reasons why libraries like [jQuery](https://jquery.com/) came into existence — to abstract away differences in browser implementations, so a developer could just use, for example, [`jQuery.ajax()`](https://api.jquery.com/jquery.ajax/), which would then handle the differences in the background.
Things have improved significantly since then; modern browsers do a good job of supporting "classic JavaScript features", and the requirement to use such code has diminished as the requirement to support older browsers has lessened (although bear in mind that they have not gone away altogether).
These days, most cross-browser JavaScript problems are seen:
- When poor-quality browser-sniffing code, feature-detection code, and vendor prefix usage block browsers from running code they could otherwise use just fine.
- When developers make use of new/nascent JavaScript features, modern Web APIs, etc.) in their code, and find that such features don't work in older browsers.
We'll explore all these problems and more below.
## Fixing general JavaScript problems
As we said in the [previous article](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS#first_things_first_fixing_general_problems) on HTML/CSS, you should make sure your code is working generally, before going on to concentrate on the cross-browser issues. If you are not already familiar with the basics of [Troubleshooting JavaScript](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong), you should study that article before moving on. There are a number of common JavaScript problems that you will want to be mindful of, such as:
- Basic syntax and logic problems (again, check out [Troubleshooting JavaScript](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong)).
- Making sure variables, etc. are defined in the correct scope, and you are not running into conflicts between items declared in different places (see [Function scope and conflicts](/en-US/docs/Learn/JavaScript/Building_blocks/Functions#function_scope_and_conflicts)).
- Confusion about [this](/en-US/docs/Web/JavaScript/Reference/Operators/this), in terms of what scope it applies to, and therefore if its value is what you intended. You can read [What is "this"?](/en-US/docs/Learn/JavaScript/Objects/Basics#what_is_this) for a light introduction; you should also study examples like [this one](https://github.com/mdn/learning-area/blob/7ed039d17e820c93cafaff541aa65d874dde8323/javascript/oojs/assessment/main.js#L143), which shows a typical pattern of saving a `this` scope to a separate variable, then using that variable in nested functions so you can be sure you are applying functionality to the correct `this` scope.
- Incorrectly using functions inside loops that iterate with a global variable (more generally "getting the scope wrong").
> **Callout:**
> For example, in [bad-for-loop.html](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/javascript/bad-for-loop.html) (see [source code](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/javascript/bad-for-loop.html)), we loop through 10 iterations using a variable defined with `var`, each time creating a paragraph and adding an [onclick](/en-US/docs/Web/API/Element/click_event) event handler to it. When clicked, we want each one to display an alert message containing its number (the value of `i` at the time it was created). Instead they all report `i` as 11 — because the `for` loop does all its iterating before nested functions are invoked.
>
> The easiest solution is to declare the iteration variable with `let` instead of `var`—the value of `i` associated with the function is then unique to each iteration. See [good-for-loop.html](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/javascript/good-for-loop.html) (see the [source code](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/javascript/good-for-loop.html) also) for a version that works.
- Making sure [asynchronous operations](/en-US/docs/Learn/JavaScript/Asynchronous) have completed before trying to use the values they return. This usually means understanding how to use _promises_: using [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) appropriately or running the code to handle the result of an asynchronous call in the promise's {{jsxref("Promise.then()", "then()")}} handler. See [How to use promises](/en-US/docs/Learn/JavaScript/Asynchronous/Promises) for an introduction to this topic.
> **Note:** [Buggy JavaScript Code: The 10 Most Common Mistakes JavaScript Developers Make](https://www.toptal.com/javascript/10-most-common-javascript-mistakes) has some nice discussions of these common mistakes and more.
### Linters
As with [HTML and CSS](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS#linters), you can ensure better quality, less error-prone JavaScript code using a linter, which points out errors and can also flag up warnings about bad practices, etc., and be customized to be stricter or more relaxed in their error/warning reporting. The JavaScript/ECMAScript linters we'd recommend are [JSHint](https://jshint.com/) and [ESLint](https://eslint.org/); these can be used in a variety of ways, some of which we'll detail below.
#### Online
The [JSHint homepage](https://jshint.com/) provides an online linter, which allows you to enter your JavaScript code on the left and provides an output on the right, including metrics, warnings, and errors.

#### Code editor plugins
It is not very convenient to have to copy and paste your code over to a web page to check its validity several times. What you really want is a linter that will fit into your standard workflow with the minimum of hassle. Many code editors have linter plugins. For example, see the "Plugins for text editors and IDEs" section of the [JSHint install page](https://jshint.com/install/).
#### Other uses
There are other ways to use such linters; you can read about them on the [JSHint](https://jshint.com/install/) and [ESLint](https://eslint.org/docs/user-guide/getting-started) install pages.
It is worth mentioning command line uses — you can install these tools as command line utilities (available via the CLI — command line interface) using npm (Node Package Manager — you'll have to install [NodeJS](https://nodejs.org/en/) first). For example, the following command installs JSHint:
```bash
npm install -g jshint
```
You can then point these tools at JavaScript files you want to lint, for example:

You can also use these tools with a task runner/build tool such as [Gulp](https://gulpjs.com/) or [Webpack](https://webpack.github.io/) to automatically lint your JavaScript during development. (see [Using a task runner to automate testing tools](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing#using_a_task_runner_to_automate_testing_tools) in a later article.) See [ESLint integrations](https://eslint.org/docs/user-guide/integrations) for ESLint options; JSHint is supported out of the box by Grunt, and also has other integrations available, e.g. [JSHint loader for Webpack](https://github.com/webpack-contrib/jshint-loader).
> **Note:** ESLint takes a bit more setup and configuration than JSHint, but it is more powerful too.
### Browser developer tools
Browser developer tools have many useful features for helping to debug JavaScript. For a start, the JavaScript console will report errors in your code.
Make a local copy of our [fetch-broken](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/javascript/fetch-broken) example (see the [source code](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/javascript/fetch-broken) also).
If you look at the console, you'll see an error message. The exact wording is browser-dependent, but it will be something like: "Uncaught TypeError: heroes is not iterable", and the referenced line number is 25. If we look at the source code, the relevant code section is this:
```js
function showHeroes(jsonObj) {
const heroes = jsonObj["members"];
for (const hero of heroes) {
// ...
}
}
```
So the code falls over as soon as we try to use `jsonObj` (which as you might expect, is supposed to be a [JSON object](/en-US/docs/Learn/JavaScript/Objects/JSON)). This is supposed to be fetched from an external `.json` file using the following {{domxref("fetch()")}} call:
```js
const requestURL =
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
const response = fetch(requestURL);
populateHeader(response);
showHeroes(response);
```
But this fails.
#### The Console API
You may already know what is wrong with this code, but let's explore it some more to show how you could investigate this. For a start, there is a [Console](/en-US/docs/Web/API/console) API that allows JavaScript code to interact with the browser's JavaScript console. It has a number of features available, but the one you'll use most often is [`console.log()`](/en-US/docs/Web/API/console/log_static), which prints a custom message to the console.
Try adding a `console.log()` call to log the return value of `fetch()`, like this:
```js
const requestURL =
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
const response = fetch(requestURL);
console.log(`Response value: ${response}`);
const superHeroes = response;
populateHeader(superHeroes);
showHeroes(superHeroes);
```
Refresh the page in the browser. This time, before the error message, you'll see a new message logged to the console:
```plain
Response value: [object Promise]
```
The `console.log()` output shows that the return value of `fetch()` is not the JSON data, it's a {{jsxref("Promise")}}. The `fetch()` function is asynchronous: it returns a `Promise` that is fulfilled only when the actual response has been received from the network. Before we can use the response, we have to wait for the `Promise` to be fulfilled.
We can do this by putting the code that uses the response inside the {{jsxref("Promise.prototype.then()", "then()")}} method of the returned `Promise`, like this:
```js
const response = fetch(requestURL);
fetch(requestURL).then((response) => {
populateHeader(response);
showHeroes(response);
});
```
To summarize, anytime something is not working and a value does not appear to be what it is meant to be at some point in your code, you can use `console.log()` to print it out and see what is happening.
#### Using the JavaScript debugger
Unfortunately, we still have the same error — the problem has not gone away. Let's investigate this now, using a more sophisticated feature of browser developer tools: the [JavaScript debugger](https://firefox-source-docs.mozilla.org/devtools-user/debugger/index.html) as it is called in Firefox.
> **Note:** Similar tools are available in other browsers; the [Sources tab](https://developer.chrome.com/docs/devtools/#sources) in Chrome, Debugger in Safari (see [Safari Web Development Tools](https://developer.apple.com/safari/tools/)), etc.
In Firefox, the Debugger tab looks like this:

- On the left, you can select the script you want to debug (in this case we have only one).
- The center panel shows the code in the selected script.
- The right-hand panel shows useful details pertaining to the current environment — _Breakpoints_, _Callstack_ and currently active _Scopes_.
The main feature of such tools is the ability to add breakpoints to code — these are points where the execution of the code stops, and at that point you can examine the environment in its current state and see what is going on.
Let's get to work. The error is now being thrown at line 26. Click on line number 26 in the center panel to add a breakpoint to it (you'll see a blue arrow appear over the top of it). Now refresh the page (Cmd/Ctrl + R) — the browser will pause execution of the code at line 51. At this point, the right-hand side will update to show some very useful information.

- Under _Breakpoints_, you'll see the details of the break-point you have set.
- Under _Call Stack_, you'll see a few entries — this is basically a list of the series of functions that were invoked to cause the current function to be invoked. At the top, we have `showHeroes()` the function we are currently in, and second we have `onload`, which stores the event handler function containing the call to `showHeroes()`.
- Under _Scopes_, you'll see the currently active scope for the function we are looking at. We only have three — `showHeroes`, `block`, and `Window` (the global scope). Each scope can be expanded to show the values of variables inside the scope when execution of the code was stopped.
We can find out some very useful information in here.
1. Expand the `showHeroes` scope — you can see from this that the heroes variable is `undefined`, indicating that accessing the `members` property of `jsonObj` (first line of the function) didn't work.
2. You can also see that the `jsonObj` variable is storing a {{domxref("Response")}} object, not a JSON object.
The argument to `showHeroes()` is the value the `fetch()` promise was fulfilled with. So this promise is not in the JSON format: it is a `Response` object. There's an extra step needed to retrieve the content of the response as a JSON object.
We'd like you to try fixing this problem yourself. To get you started, see the documentation for the {{domxref("Response")}} object. If you get stuck, you can find the fixed source code at <https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/javascript/fetch-fixed>.
> **Note:** The debugger tab has many other useful features that we've not discussed here, for example conditional breakpoints and watch expressions. For a lot more information, see the [Debugger](https://firefox-source-docs.mozilla.org/devtools-user/debugger/index.html) page.
### Performance issues
As your apps get more complex and you start to use more JavaScript, you may start to run into performance problems, especially when viewing apps on slower devices. Performance is a big topic, and we don't have time to cover it in detail here. Some quick tips are as follows:
- To avoid loading more JavaScript than you need, bundle your scripts into a single file using a solution like [Browserify](https://browserify.org/). In general, reducing the number of HTTP requests is very good for performance.
- Make your files even smaller by minifying them before you load them onto your production server. Minifying squashes all the code together onto a huge single line, making it take up far less file size. It is ugly, but you don't need to read it when it is finished! This is best done using a minification tool like [Uglify](https://github.com/mishoo/UglifyJS) (there's also an online version — see [JSCompress.com](https://jscompress.com/))
- When using APIs, make sure you turn off the API features when they are not being used; some API calls can be really expensive on processing power. For example, when showing a video stream, make sure it is turned off when you can't see it. When tracking a device's location using repeated Geolocation calls, make sure you turn it off when the user stops using it.
- Animations can be really costly for performance. A lot of JavaScript libraries provide animation capabilities programmed by JavaScript, but it is much more cost effective to do the animations via native browser features like [CSS Animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations) (or the nascent [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)) than JavaScript. Read Brian Birtles' [Animating like you just don't care with Element.animate](https://hacks.mozilla.org/2016/08/animating-like-you-just-dont-care-with-element-animate/) for some really useful theory on why animation is expensive, tips on how to improve animation performance, and information on the Web Animations API.
> **Note:** Addy Osmani's [Writing Fast, Memory-Efficient JavaScript](https://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/) contains a lot of detail and some excellent tips for boosting JavaScript performance.
## Cross-browser JavaScript problems
In this section, we'll look at some of the more common cross-browser JavaScript problems. We'll break this down into:
- Using modern core JavaScript features
- Using modern Web API features
- Using bad browser sniffing code
- Performance problems
### Using modern JavaScript/API features
In the [previous article](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS#older_browsers_not_supporting_modern_features) we described some of the ways in which HTML and CSS errors and unrecognized features can be handled due to the nature of the languages. JavaScript is not as permissive as HTML and CSS however — if the JavaScript engine encounters mistakes or unrecognized syntax, such as when new, unsupported features are used, more often than not it will throw errors.
There are a few strategies for handling new feature support; let's explore the most common ones.
> **Note:** These strategies do not exist in separate silos — you can, of course combine them as needed. For example, you could use feature detection to determine whether a feature is supported; if it isn't, you could then run code to load a polyfill or a library to handle the lack of support.
#### Feature detection
The idea behind feature detection is that you can run a test to determine whether a JavaScript feature is supported in the current browser, and then conditionally run code to provide an acceptable experience both in browsers that do and don't support the feature. As a quick example, the [Geolocation API](/en-US/docs/Web/API/Geolocation_API) (which exposes available location data for the device the web browser is running on) has a main entry point for its use — a `geolocation` property available on the global [Navigator](/en-US/docs/Web/API/Navigator) object. Therefore, you can detect whether the browser supports geolocation or not by using something like the following:
```js
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
// show the location on a map, perhaps using the Google Maps API
});
} else {
// Give the user a choice of static maps instead perhaps
}
```
You could also write such a test for a CSS feature, for example by testing for the existence of _[element.style.property](/en-US/docs/Web/API/HTMLElement/style)_ (e.g. `paragraph.style.transform !== undefined`).
If you're looking to apply styles if a CSS feature is supported, you can directly use the [@supports](/en-US/docs/Web/CSS/@supports) at-rule (known as a feature query).
For example, to check whether the browser supports CSS container queries, you could do something like this:
```css
@supports (container-type: inline-size) {
/* Use container queries if supported */
}
```
As a last point, don't confuse feature detection with **browser sniffing** (detecting what specific browser is accessing the site) — this is a terrible practice that should be discouraged at all costs. See [Using bad browser sniffing code](#using_bad_browser_sniffing_code), later on, for more details.
> **Note:** Feature detection will be covered in a lot more detail in its own dedicated article, later in the module.
#### Libraries
JavaScript libraries are essentially third party units of code that you can attach to your page, providing you with a wealth of ready-made functionality that can be used straight away, saving you a lot of time in the process. A lot of JavaScript libraries probably came into existence because their developer was writing a set of common utility functions to save them time when writing future projects, and decided to release them into the wild because other people might find them useful too.
JavaScript libraries tend to come in a few main varieties (some libraries will serve more than one of these purposes):
- Utility libraries: Provide a bunch of functions to make mundane tasks easier and less boring to manage. [jQuery](https://jquery.com/) for example provides its own fully-featured selectors and DOM manipulation libraries, to allow CSS-selector type selecting of elements in JavaScript and easier DOM building. It is not so important now we have modern features like {{domxref("Document.querySelector()")}}/{{domxref("Document.querySelectorAll()")}}/{{domxref("Node")}} methods available across browsers, but it can still be useful when older browsers need supporting.
- Convenience libraries: Make difficult things easier to do. For example, the [WebGL API](/en-US/docs/Web/API/WebGL_API) is really complex and challenging to use when you write it directly, so the [Three.js](https://threejs.org/) library (and others) is built on top of WebGL and provides a much easier API for creating common 3D objects, lighting, textures, etc.
The [Service Worker API](/en-US/docs/Web/API/Service_Worker_API) is also very complex to use, so code libraries have started appearing to make common Service Worker uses-cases much easier to implement (see the [Service Worker Cookbook](https://github.com/mdn/serviceworker-cookbook) for several useful code samples).
- Effects libraries: These libraries are designed to allow you to easily add special effects to your websites. This was more useful back when "DHTML" was a popular buzzword, and implementing an effect involved a lot of complex JavaScript, but these days browsers have a lot of built in CSS features and APIs to implementing effects more easily.
- UI libraries: Provide methods for implementing complex UI features that would otherwise be challenging to implement and get working cross browser, for example [Foundation](https://get.foundation/), [Bootstrap](https://getbootstrap.com/), and [Material-UI](https://mui.com/) (the latter is a set of components for use with the React framework). These tend to be used as the basis of an entire site layout; it is often difficult to drop them in just for one UI feature.
- Normalization libraries: Give you a simple syntax that allows you to easily complete a task without having to worry about cross browser differences. The library will manipulate appropriate APIs in the background so the functionality will work whatever the browser (in theory). For example, [LocalForage](https://github.com/localForage/localForage) is a library for client-side data storage, which provides a simple syntax for storing and retrieving data. In the background, it uses the best API the browser has available for storing the data, whether that is [IndexedDB](/en-US/docs/Web/API/IndexedDB_API), [Web Storage](/en-US/docs/Web/API/Web_Storage_API), or even Web SQL (which is now deprecated, but is still supported in Chromium-based browsers in secure contexts). As another example, jQuery
When choosing a library to use, make sure that it works across the set of browsers you want to support, and test your implementation thoroughly. Also make sure that the library is popular and well-supported, and isn't likely to just become obsolete next week. Talk to other developers to find out what they recommend, see how much activity and how many contributors the library has on GitHub (or wherever else it is stored), etc.
Library usage at a basic level tends to consist of downloading the library's files (JavaScript, possibly some CSS or other dependencies too) and attaching them to your page (e.g. via a {{htmlelement("script")}} element), although there are normally many other usage options for such libraries, like installing them as [Bower](https://bower.io/) components, or including them as dependencies via the [Webpack](https://webpack.github.io/) module bundler. You will have to read the libraries' individual install pages for more information.
> **Note:** You will also come across JavaScript frameworks in your travels around the Web, like [Ember](https://emberjs.com/) and [Angular](https://angularjs.org/). Whereas libraries are often usable for solving individual problems and dropping into existing sites, frameworks tend to be more along the lines of complete solutions for developing complex web applications.
#### Polyfills
Polyfills also consist of 3rd party JavaScript files that you can drop into your project, but they differ from libraries — whereas libraries tend to enhance existing functionality and make things easier, polyfills provide functionality that doesn't exist at all. Polyfills use JavaScript or other technologies entirely to build in support for a feature that a browser doesn't support natively. For example, you might use a polyfill like [es6-promise](https://github.com/stefanpenner/es6-promise) to make promises work in browsers where they are not supported natively.
Let's work through an exercise — in this example used for demonstration purposes only, we use a Fetch polyfill and an es6-promise polyfill. While Fetch and promises are fully supported in modern browsers, if we were targeting a browser that did not support Fetch that browser would likely not support Fetch either, and Fetch makes heavy use of promises:
1. To get started, make a local copy of our [fetch-polyfill.html](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/javascript/fetch-polyfill.html) example and [our nice image of some flowers](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/javascript/flowers.jpg) in a new directory. We are going to write code to fetch the flowers image and display it in the page.
2. Next, save a copy of the [Fetch polyfill](https://raw.githubusercontent.com/github/fetch/master/fetch.js) in the same directory as the HTML.
3. Apply the polyfill scripts to the page using the following code — place these above the existing {{htmlelement("script")}} element so they will be available on the page already when we start trying to use Fetch (we are also loading a Promise polyfill from a CDN, as IE11 does support promises, which fetch requires):
```html
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js"></script>
<script src="fetch.js"></script>
```
4. Inside the original {{htmlelement("script")}}, add the following code:
```js
const myImage = document.querySelector(".my-image");
fetch("flowers.jpg").then((response) => {
response.blob().then((myBlob) => {
const objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
});
```
5. If you load it in a browser that doesn't support [Fetch](/en-US/docs/Web/API/fetch), you should still see the flower image appear — cool!

> **Note:** You can find our finished version at [fetch-polyfill-finished.html](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/javascript/fetch-polyfill-finished.html) (see also the [source code](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/javascript/fetch-polyfill-finished.html)).
> **Note:** Again, there are many different ways to make use of the different polyfills you will encounter — consult each polyfill's individual documentation.
One thing you might be thinking is "why should we always load the polyfill code, even if we don't need it?" This is a good point — as your sites get more complex and you start to use more libraries, polyfills, etc., you can start to load a lot of extra code, which can start to affect performance, especially on less-powerful devices. It makes sense to only load files as needed.
Doing this requires some extra setup in your JavaScript. You need some kind of a feature detection test that detects whether the browser supports the feature we are trying to use:
```js
if (browserSupportsAllFeatures()) {
main();
} else {
loadScript("polyfills.js", main);
}
function main(err) {
// actual app code goes in here
}
```
So first we run a conditional that checks whether the function `browserSupportsAllFeatures()` returns true. If it does, we run the `main()` function, which will contain all our app's code. `browserSupportsAllFeatures()` looks like this:
```js
function browserSupportsAllFeatures() {
return window.Promise && window.fetch;
}
```
Here we are testing whether the [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) object and [`fetch()`](/en-US/docs/Web/API/fetch) function exist in the browser. If both do, the function returns true. If the function returns `false`, then we run the code inside the second part of the conditional — this runs a function called loadScript(), which loads the polyfills into the page, then runs `main()` after the loading has finished. `loadScript()` looks like this:
```js
function loadScript(src, done) {
const js = document.createElement("script");
js.src = src;
js.onload = () => {
done();
};
js.onerror = () => {
done(new Error(`Failed to load script ${src}`));
};
document.head.appendChild(js);
}
```
This function creates a new `<script>` element, then sets its `src` attribute to the path we specified as the first argument (`'polyfills.js'` when we called it in the code above). When it has loaded, we run the function we specified as the second argument (`main()`). If an error occurs in the loading of the script, we still call the function, but with a custom error that we can retrieve to help debug a problem if it occurs.
Note that polyfills.js is basically the two polyfills we are using put together into one file. We did this manually, but there are cleverer solutions that will automatically generate bundles for you — see [Browserify](https://browserify.org/) (see [Getting started with Browserify](https://www.sitepoint.com/getting-started-browserify/) for a basic tutorial). It is a good idea to bundle JS files into one like this — reducing the number of HTTP requests you need to make improves the performance of your site.
You can see this code in action in [fetch-polyfill-only-when-needed.html](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/javascript/fetch-polyfill-only-when-needed.html) (see the [source code also](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/javascript/fetch-polyfill-only-when-needed.html)). We'd like to make it clear that we can't take credit for this code — it was originally written by Philip Walton. Check out his article [Loading Polyfills Only When Needed](https://philipwalton.com/articles/loading-polyfills-only-when-needed/) for the original code, plus a lot of useful explanation around the wider subject).
> **Note:** There are some 3rd party options to consider, for example [Polyfill.io](https://polyfill.io/) — this is a meta-polyfill library that will look at each browser's capabilities and apply polyfills as needed, depending on what APIs and JS features you are using in your code.
#### JavaScript transpiling
Another option that is becoming popular for people who want to use modern JavaScript features now is converting code that uses recent ECMAScript features to a version that will work in older browsers.
> **Note:** This is called "transpiling" — you are not compiling code into a lower level to be run on a computer (like you would say with C code); instead, you are changing it into a syntax that exists at a similar level of abstraction so it can be used in the same way, but in slightly different circumstances (in this case, transforming one flavor of JavaScript into another).
A common transpiler is [Babel.js](https://babeljs.io/) but there are others.
### Don't browser sniff
Historically developers used _browser sniffing code_ to detect which browser the user was using, and give them appropriate code to work on that browser.
All browsers have a **user-agent** string, which identifies what the browser is (version, name, OS, etc.). Many developers implemented bad browser sniffing code and didn't maintain it. This lead to supporting browsers getting locked out of using websites they could easily render. This became so common that browsers started to lie about what browser they were in their user-agent strings (or claim they were all browsers), to get around sniffing code. Browsers also implemented facilities to allow users to change what user-agent string the browser reported when queried with JavaScript. This all made browser sniffing even more error prone, and ultimately pointless.
[History of the browser user-agent string](https://webaim.org/blog/user-agent-string-history/) by Aaron Andersen provides a useful and amusing take on the history of browser sniffing.
Use [feature detection](#feature_detection) (and CSS @supports for CSS feature detection) to reliably detect whether a feature is supported. But doing so, you won't need to change your code when new browser versions come out.
### Handling JavaScript prefixes
In the previous article, we included quite a lot of discussion about [handling CSS prefixes](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS#handling_css_prefixes). Well, new JavaScript implementations used to use prefixes as well, with JavaScript using {{Glossary("camel_case", "camel case")}} rather than {{Glossary("kebab_case", "hyphenation")}} like CSS. For example, if a prefix was being used on a new jshint API object called `Object`:
- Mozilla would use `mozObject`
- Chrome/Opera/Safari would use `webkitObject`
- Microsoft would use `msObject`
Here's an example, taken from our [violent-theremin demo](https://mdn.github.io/webaudio-examples/violent-theremin/) (see [source code](https://github.com/mdn/webaudio-examples/tree/main/violent-theremin)), which uses a combination of the [Canvas API](/en-US/docs/Web/API/Canvas_API) and the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) to create a fun (and noisy) drawing tool:
```js
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
```
In the case of the Web Audio API, the key entry points to using the API were supported in Chrome/Opera via `webkit` prefixed versions (they now support the unprefixed versions). The easy way to get around this situation is to create a new version of the objects that are prefixed in some browsers, and make it equal to the non-prefixed version, OR the prefixed version (OR any other prefixed versions that need consideration) — whichever one is supported by the browser currently viewing the site will be used.
Then we use that object to manipulate the API, rather than the original one. In this case we are creating a modified [AudioContext](/en-US/docs/Web/API/AudioContext) constructor, then creating a new audio context instance to use for our Web Audio coding.
This pattern can be applied to just about any prefixed JavaScript feature. JavaScript libraries/polyfills also make use of this kind of code, to abstract browser differences away from the developer as much as possible.
Again, prefixed features were never supposed to be used in production websites — they are subject to change or removal without warning, and cause cross browser issues. If you insist on using prefixed features, make sure you use the right ones. You can look up what browsers require prefixes for different JavaScript/API features on MDN reference pages, and sites like [caniuse.com](https://caniuse.com/). If you are unsure, you can also find out by doing some testing directly in browsers.
For example, try going into your browser's developer console and start typing
```js
window.AudioContext;
```
If this feature is supported in your browser, it will autocomplete.
## Finding help
There are many other issues you'll encounter with JavaScript; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's [Finding help section](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS#finding_help) for our best advice.
## Summary
So that's JavaScript. Simple huh? Maybe not so simple, but this article should at least give you a start, and some ideas on how to tackle the JavaScript-related problems you will come across.
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS","Learn/Tools_and_testing/Cross_browser_testing/Accessibility", "Learn/Tools_and_testing/Cross_browser_testing")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing | data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing/html_and_css/index.md | ---
title: Handling common HTML and CSS problems
slug: Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies","Learn/Tools_and_testing/Cross_browser_testing/JavaScript", "Learn/Tools_and_testing/Cross_browser_testing")}}
With the scene set, we'll now look specifically at the common cross-browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handling CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages; an idea
of the high level
<a
href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction"
>principles of cross browser testing</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To be able to diagnose common HTML and CSS cross browser problems, and
use appropriate tools and techniques to fix them.
</td>
</tr>
</tbody>
</table>
## The trouble with HTML and CSS
Some of the trouble with HTML and CSS lies with the fact that both languages are fairly simple, and often developers don't take them seriously, in terms of making sure the code is well-crafted, efficient, and semantically describes the purpose of the features on the page. In the worst cases, JavaScript is used to generate the entire web page content and style, which makes your pages inaccessible, and less performant (generating DOM elements is expensive). In other cases, nascent features are not supported consistently across browsers, which can make some features and styles not work for some users. Responsive design problems are also common — a site that looks good in a desktop browser might provide a terrible experience on a mobile device, because the content is too small to read, or perhaps the site is slow because of expensive animations.
Let's go forth and look at how we can reduce cross browser errors that result from HTML/CSS.
## First things first: fixing general problems
We said in the [first article of this series](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction#testingdiscovery) that a good strategy to begin with is to test in a couple of modern browsers on desktop/mobile, to make sure your code is working generally, before going on to concentrate on the cross browser issues.
In our [Debugging HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML) and [Debugging CSS](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS) articles, we provided some really basic guidance on debugging HTML/CSS — if you are not familiar with the basics, you should definitely study these articles before carrying on.
Basically, it is a matter of checking whether your HTML and CSS code is well formed and doesn't contain any syntax errors.
> **Note:** One common problem with CSS and HTML arises when different CSS rules begin to conflict with one another. This can be especially problematic when you are using third party code. For example, you might use a CSS framework and find that one of the class names it uses clashes with one you've already used for a different purpose. Or you might find that HTML generated by some kind of third party API (generating ad banners, for example) includes a class name or ID that you are already using for a different purpose. To ensure this doesn't happen, you need to research the tools you are using first and design your code around them. It is also worth "namespacing" CSS, e.g. if you have a widget, make sure it has a distinct class, and then start the selectors that select elements inside the widget with this class, so conflicts are less likely. For example `.audio-player ul a`.
### Validation
For HTML, validation involves making sure all your tags are properly closed and nested, you are using a DOCTYPE, and you are using tags for their correct purpose. A good strategy is to validate your code regularly. One service that can do this is the W3C [Markup Validation Service](https://validator.w3.org/), which allows you to point to your code, and returns a list of errors:

CSS has a similar story — you need to check that your property names are spelled correctly, property values are spelled correctly and are valid for the properties they are used on, you are not missing any curly braces, and so on. The W3C has a [CSS Validator](https://jigsaw.w3.org/css-validator/) available too, for this purpose.
### Linters
Another good option to choose is a so-called Linter application, which not only points out errors, but can also flag up warnings about bad practices in your CSS, and other points besides. Linters can generally be customized to be stricter or more relaxed in their error/warning reporting.
There are many online linter applications, the best of which are probably [Dirty Markup](https://www.10bestdesign.com/dirtymarkup/) (HTML, CSS, JavaScript), and [CSS Lint](http://csslint.net/) (CSS only). These allows you to paste your code into a window, and it will flag up any errors with crosses, which can then be hovered to get an error message informing you what the problem is. Dirty Markup also allows you to make fixes to your markup using the _Clean_ button.

However, it is not very convenient to have to copy and paste your code over to a web page to check its validity several times. What you really want is a linter that will fit into your standard workflow with the minimum of hassle.
Many code editors have linter plugins. For example, see:
- [SublimeLinter](https://www.sublimelinter.com/) for Sublime Text
- [Notepad++ linter](https://sourceforge.net/projects/notepad-linter/)
- [VSCode linters](https://marketplace.visualstudio.com/search?target=vscode&category=Linters&sortBy=Installs)
### Browser developer tools
The developer tools built into most browsers also feature useful tools for hunting down errors, mainly for CSS.
> **Note:** HTML errors don't tend to show up so easily in dev tools, as the browser will try to correct badly-formed markup automatically; the W3C validator is the best way to find HTML errors — see [Validation](#validation) above.
As an example, in Firefox the CSS inspector will show CSS declarations that aren't applied crossed out, with a warning triangle. Hovering the warning triangle will provide a descriptive error message:

Other browser devtools have similar features.
## Common cross browser problems
Now let's move on to look at some of the most common cross browser HTML and CSS problems. The main areas we'll look at are lack of support for modern features, and layout issues.
### Browsers not supporting modern features
This is a common problem, especially when you need to support old browsers or you are using features that are implemented in some browsers but not yet in all. In general, most core HTML and CSS functionality (such as basic HTML elements, CSS basic colors and text styling) works across all the browsers you'll want to support; more problems are uncovered when you start wanting to use newer HTML, CSS, and APIs. MDN displays browser compatibility data for each feature documented; for example, see the [browser support table for the `:has()` pseudo-class](/en-US/docs/Web/CSS/:has#browser_compatibility).
Once you've identified a list of technologies you will be using that are not universally supported, it is a good idea to research what browsers they are supported in, and what related techniques are useful. See [Finding help](#finding_help) below.
#### HTML fallback behavior
Some problems can be solved by just taking advantage of the natural way in which HTML/CSS work.
Unrecognized HTML elements are treated by the browser as anonymous inline elements (effectively inline elements with no semantic value, similar to {{htmlelement("span")}} elements). You can still refer to them by their names, and style them with CSS, for example — you just need to make sure they are behaving as you want them to. Style them just as you would any other element, including setting the `display` property to something other than `inline` if needed.
More complex elements like HTML [`<video>`](/en-US/docs/Web/HTML/Element/video), [`<audio>`](/en-US/docs/Web/HTML/Element/audio), [`<picture>`](/en-US/docs/Web/HTML/Element/picture), [`<object>`](/en-US/docs/Web/HTML/Element/object), and [`<canvas>`](/en-US/docs/Web/HTML/Element/canvas) (and other features besides) have natural mechanisms for fallbacks to be added in case the resources linked to are not supported. You can add fallback content in between the opening and closing tags, and non-supporting browsers will effectively ignore the outer element and run the nested content.
For example:
```html
<video id="video" controls preload="metadata" poster="img/poster.jpg">
<source
src="video/tears-of-steel-battle-clip-medium.webm"
type="video/webm" />
<!-- Offer download -->
<p>
Your browser does not support WebM video; here is a link to
<a href="video/tears-of-steel-battle-clip-medium.mp4"
>view the video directly</a
>
</p>
</video>
```
This example includes a simple link allowing you to download the video if even the HTML video player doesn't work, so at least the user can still access the video.
Another example is form elements. When new [`<input>`](/en-US/docs/Web/HTML/Element/input) types were introduced for inputting specific information into forms, such as times, dates, colors, numbers, etc., if a browser didn't support the new feature, the browser used the default of `type="text"`. Input types were added, which are very useful, particularly on mobile platforms, where providing a pain-free way of entering data is very important for the user experience. Platforms provide different UI widgets depending on the input type, such as a calendar widget for entering dates. Should a browser not support an input type, the user can still enter the required data.
The following example shows date and time inputs:
```html
<form>
<div>
<label for="date">Enter a date:</label>
<input id="date" type="date" />
</div>
<div>
<label for="time">Enter a time:</label>
<input id="time" type="time" />
</div>
</form>
```
The output of this code is as follows:
{{EmbedGHLiveSample("learning-area/tools-testing/cross-browser-testing/html-css/forms-test", '100%', 150)}}
> **Note:** You can also see this running live as [forms-test.html](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/html-css/forms-test.html) on GitHub (see the [source code](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/html-css/forms-test.html) also).
If you view the example, you'll see the UI features in action as you try to input data. On devices with dynamic keyboards, type-specific keypads will be displayed. On a non-supporting browser, the inputs will just default to normal text inputs, meaning the user can still enter the correct information.
#### CSS fallback behavior
CSS is arguably better at fallbacks than HTML. If a browser encounters a declaration or rule it doesn't understand, it just skips it completely without applying it or throwing an error. This might be frustrating for you and your users if such a mistake slips through to production code, but at least it means the whole site doesn't come crashing down because of one error, and if used cleverly you can use it to your advantage.
Let's look at an example — a simple box styled with CSS, which has some styling provided by various CSS features:

> **Note:** You can also see this example running live on GitHub as [button-with-fallback.html](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/html-css/button-with-fallback.html) (also see the [source code](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/html-css/button-with-fallback.html)).
The button has a number of declarations that style, but the two we are most interested in are as follows:
```css
button {
/* … */
background-color: #ff0000;
background-color: rgb(255 0 0 / 100%);
box-shadow:
inset 1px 1px 3px rgb(255 255 255 / 40%),
inset -1px -1px 3px rgb(0 0 0 / 40%);
}
button:hover {
background-color: rgb(255 0 0 / 50%);
}
button:active {
box-shadow:
inset 1px 1px 3px rgb(0 0 0 / 40%),
inset -1px -1px 3px rgb(255 255 255 / 40%);
}
```
Here we are providing an [RGB](/en-US/docs/Web/CSS/color_value/rgb) {{cssxref("background-color")}} that changes opacity on hover to give the user a hint that the button is interactive, and some semi-transparent inset {{cssxref("box-shadow")}} shades to give the button a bit of texture and depth. While now fully supported, RGB colors and box shadows haven't been around forever; starting in IE9. Browsers that didn't support RGB colors would ignore the declaration meaning in old browsers the background just wouldn't show up at all so the text would be unreadable, no good at all!

To sort this out, we have added a second `background-color` declaration, which just specifies a hex color — this is supported way back in really old browsers, and acts as a fallback if the modern shiny features don't work. What happens is a browser visiting this page first applies the first `background-color` value; when it gets to the second `background-color` declaration, it will override the initial value with this value if it supports RGB colors. If not, it will just ignore the entire declaration and move on.
> **Note:** The same is true for other CSS features like [media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries), [`@font-face`](/en-US/docs/Web/CSS/@font-face) and [`@supports`](/en-US/docs/Web/CSS/@supports) blocks — if they are not supported, the browser just ignores them.
#### Selector support
Of course, no CSS features will apply at all if you don't use the right [selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors) to select the element you want to style!
In a comma-separated list of selectors, if you just write a selector incorrectly, it may not match any element. If, however, a selector is invalid, the **entire** list of selectors is ignored, along with the entire style block. For this reason, only include a `:-moz-` prefixed pseudo class or pseudo-element in a [forgiving selector list](/en-US/docs/Web/CSS/Selector_list#forgiving_selector_list), such as `:where(::-moz-thumb)`. Don't include a `:-moz-` prefixed pseudo class or pseudo-element within a comma-separated group of selectors outside of a [`:is()`](/en-US/docs/Web/CSS/:is) or [`:where()`](/en-US/docs/Web/CSS/:where) forgiving selector list as all browsers other than Firefox will ignore the entire block. Note that both `:is()` and `:where()` can be passed as parameters in other selector lists, including [`:has()`](/en-US/docs/Web/CSS/:has) and [`:not()`](/en-US/docs/Web/CSS/:not).
We find that it is helpful to inspect the element you are trying to style using your browser's dev tools, then look at the DOM tree breadcrumb trail that DOM inspectors tend to provide to see if your selector makes sense compared to it.
For example, in the Firefox dev tools, you get this kind of output at the bottom of the DOM inspector:

If for example you were trying to use this selector, you'd be able to see that it wouldn't select the input element as desired:
```css
form > #date
```
(The `date` form input isn't a direct child of the `<form>`; you'd be better off using a general descendant selector instead of a child selector).
#### Handling CSS prefixes
Another set of problems comes with CSS prefixes — these are a mechanism originally used to allow browser vendors to implement their own version of a CSS (or JavaScript) feature while the technology is in an experimental state, so they can play with it and get it right without conflicting with other browser's implementations, or the final unprefixed implementations.
For example, Firefox uses `-moz-` and Chrome/Edge/Opera/Safari use `-webkit-`. Other prefixes you may encounter in old code include `-ms-`, used by Internet Explorer and early versions of Edge, and `-o`, used in the original versions of Opera.
Prefixed features were never supposed to be used in production websites — they are subject to change or removal without warning, may cause performance issues in old browser versions that require them, and have been the cause of cross-browser issues. This is particularly a problem, for example, when developers decide to use only the `-webkit-` version of a property, which implied that the site won't work in other browsers. This actually happened so much that other browser vendors implemented `-webkit-` prefixed versions of several CSS properties. While browsers still support some prefixed property names, property values, and pseudo classes, now experimental features are put behind flags so that web developers can test them during development.
If using a prefix, make sure it is needed; that the property is one of the few remaining prefixed features. You can look up what browsers require prefixes on MDN reference pages, and sites like [caniuse.com](https://caniuse.com/). If you are unsure, you can also find out by doing some testing directly in browsers. Include the standard non-prefixed version after the prefixed style declaration; it will be ignored if not supported and used when supported.
```css
.masked {
-webkit-mask-image: url(MDN.svg);
mask-image: url(MDN.svg);
-webkit-mask-size: 50%;
mask-size: 50%;
}
```
Try this simple example:
1. Use this page, or another site that has a prominent heading or other block-level element.
2. Right/Cmd + click on the element in question and choose Inspect/Inspect element (or whatever the option is in your browser) — this should open up the dev tools in your browser, with the element highlighted in the DOM inspector.
3. Look for a feature you can use to select that element. For example, at the time of writing, this page on MDN has a logo with an ID of `mdn-docs-logo`.
4. Store a reference to this element in a variable, for example:
```js
const test = document.getElementById("mdn-docs-logo");
```
5. Now try to set a new value for the CSS property you are interested in on that element; you can do this using the [style](/en-US/docs/Web/API/HTMLElement/style) property of the element, for example try typing these into the JavaScript console:
```js
test.style.transform = "rotate(90deg)";
```
As you start to type the property name representation after the second dot (note that in JavaScript, CSS property names are written in {{Glossary("camel_case", "lower camel case")}}, not {{Glossary("kebab_case", "kebab-case")}}), the JavaScript console should begin to autocomplete the names of the properties that exist in the browser and match what you've written so far. This is useful for finding out what properties are implemented in that browser.
If you do need to include modern features, test for feature support using [`@supports`](/en-US/docs/Web/CSS/@supports), which allows you to implement native feature detection tests, and nest the prefixed or new feature within the `@supports` block.
#### Responsive design problems
Responsive design is the practice of creating web layouts that change to suit different device form factors — for example, different screen widths, orientations (portrait or landscape), or resolutions. A desktop layout for example will look terrible when viewed on a mobile device, so you need to provide a suitable mobile layout using [media queries](/en-US/docs/Web/CSS/CSS_media_queries), and make sure it is applied correctly using [viewport](/en-US/docs/Web/HTML/Viewport_meta_tag). You can find a detailed account of such practices in [our guide to responsive design](/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design).
Resolution is a big issue too — for example, mobile devices are less likely to need big heavy images than desktop computers, and are more likely to have slower internet connections and possibly even expensive data plans that make wasted bandwidth more of a problem. In addition, different devices can have a range of different resolutions, meaning that smaller images could appear pixelated. There are a number of techniques that allow you to work around such problems, from [media queries](/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design#media_queries) to more complex [responsive image techniques](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#resolution_switching_different_sizes), including {{HTMLElement('picture')}} and the {{HTMLElement('image')}} element's [`srcset`](/en-US/docs/Web/HTML/Element/img#srcset) and [`sizes`](/en-US/docs/Web/HTML/Element/img#sizes) attributes.
## Finding help
There are many other issues you'll encounter with HTML and CSS, making knowledge of how to find answers online invaluable.
Among the best sources of support information are the Mozilla Developer Network (that's where you are now!), [stackoverflow.com](https://stackoverflow.com/), and [caniuse.com](https://caniuse.com/).
To use the Mozilla Developer Network (MDN), most people do a search engine search of the technology they are trying to find information on, plus the term "mdn", for example, "mdn HTML video". MDN contains several useful types of content:
- Reference material with browser support information for client-side web technologies, e.g. the [\<video> reference page](/en-US/docs/Web/HTML/Element/video).
- Other supporting reference material, e.g. the [Guide to media types and formats on the web](/en-US/docs/Web/Media/Formats),
- Useful tutorials that solve specific problems, for example, [Creating a cross-browser video player](/en-US/docs/Web/Media/Audio_and_video_delivery/cross_browser_video_player).
[caniuse.com](https://caniuse.com/) provides support information, along with a few useful external resource links. For example, see <https://caniuse.com/#search=video> (you just have to enter the feature you are searching for into the text box).
[stackoverflow.com](https://stackoverflow.com/) (SO) is a forum site where you can ask questions and have fellow developers share their solutions, look up previous posts, and help other developers. You are advised to look and see if there is an answer to your question already, before posting a new question. For example, we searched for "disabling autofocus on HTML dialog" on SO, and very quickly came up with [Disable showModal auto-focusing using HTML attributes](https://stackoverflow.com/questions/63267581/disable-showmodal-auto-focusing-using-html-attributes).
Aside from that, try searching your favorite search engine for an answer to your problem. It is often useful to search for specific error messages if you have them — other developers will be likely to have had the same problems as you.
## Summary
Now you should be familiar with the main types of cross browser HTML and CSS problems that you'll meet in web development, and how to go about fixing them.
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies","Learn/Tools_and_testing/Cross_browser_testing/JavaScript", "Learn/Tools_and_testing/Cross_browser_testing")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing | data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing/accessibility/index.md | ---
title: Handling common accessibility problems
slug: Learn/Tools_and_testing/Cross_browser_testing/Accessibility
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}
Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages; an idea
of the high level
<a
href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction"
>principles of cross browser testing</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To be able to diagnose common Accessibility problems, and use
appropriate tools and techniques to fix them.
</td>
</tr>
</tbody>
</table>
## What is accessibility?
When we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example:
- Visually impaired people using screen readers or magnification/zoom to access text
- People with motor function impairments using the keyboard (or other non-mouse features) to activate website functionality.
- People with hearing impairments relying on captions/subtitles or other text alternatives for audio/video content.
However, it is wrong to say that accessibility is just about disabilities. Really, the aim of accessibility is to make your websites/apps usable by as many people in as many contexts as possible, not just those users using high-powered desktop computers. Some examples might include:
- Users on mobile devices.
- Users on alternative browsing devices such as TVs, watches, etc.
- Users of older devices that might not have the latest browsers.
- Users of lower spec devices that might have slow processors.
In a way, this whole module is about accessibility — cross browser testing makes sure that your sites can be used by as many people as possible. [What is accessibility?](/en-US/docs/Learn/Accessibility/What_is_accessibility) defines accessibility more completely and thoroughly than this article does.
That said, this article will cover cross browser and testing issues surrounding people with disabilities, and how they use the Web. We've already talked about other spheres such as [responsive design](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS#responsive_design_problems) and [performance](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript#performance_issues) in other places in the module.
> **Note:** Like many things in web development, accessibility isn't about 100% success or not; 100% accessibility is pretty much impossible to achieve for all content, especially as sites get more complex. Instead, it is more about making a reasonable effort to make as much of your content accessible to as many people as possible via defensive coding and sticking to best practices.
## Common accessibility issues
In this section we'll detail some of the main issues that arise around web accessibility, connected with specific technologies, along with best practices to follow, and some quick tests you can do to see if your sites are going in the right direction.
> **Note:** Accessibility is morally the right thing to do, and good for business (numbers of disabled users, users on mobile devices, etc. present significant market segments), but it is also a legal requirement in many parts of the world to make web content accessible to people with disabilities. Read [Accessibility guidelines and the law](/en-US/docs/Learn/Accessibility/What_is_accessibility#accessibility_guidelines_and_the_law) for more information.
### HTML
Semantic HTML (where the elements are used for their correct purpose) is accessible right out of the box — such content is readable by sighted viewers (provided you don't do anything silly like make the text way too small or hide it using CSS), but will also be usable by assistive technologies like screen readers (apps that literally read out a web page to their user), and confer other advantages too.
#### Semantic structure
The most important quick win in semantic HTML is to use a structure of headings and paragraphs for your content; this is because screen reader users tend to use the headings of a document as signposts to find the content they need more quickly. If your content has no headings, all they will get is a huge wall of text with no signposts to find anything. Examples of bad and good HTML:
```html-nolint example-bad
<font size="7">My heading</font>
<br /><br />
This is the first section of my document.
<br /><br />
I'll add another paragraph here too.
<br /><br />
<font size="5">My subheading</font>
<br /><br />
This is the first subsection of my document. I'd love people to be able to find
this content!
<br /><br />
<font size="5">My 2nd subheading</font>
<br /><br />
This is the second subsection of my content. I think it is more interesting than
the last one.
```
```html example-good
<h1>My heading</h1>
<p>This is the first section of my document.</p>
<p>I'll add another paragraph here too.</p>
<h2>My subheading</h2>
<p>
This is the first subsection of my document. I'd love people to be able to
find this content!
</p>
<h2>My 2nd subheading</h2>
<p>
This is the second subsection of my content. I think it is more interesting
than the last one.
</p>
```
In addition, your content should make logical sense in its source order — you can always place it where you want using CSS later on, but you should get the source order right to start with.
As a test, you can turn off a site's CSS and see how understandable it is without it. You could do this manually by just removing the CSS from your code, but the easiest way is to use browser features, for example:
- Firefox: Select _View > Page Style > No Style_ from the main menu.
- Safari: Select _Develop > Disable Styles_ from the main menu (to enable the _Develop_ menu, choose _Safari > Preferences > Advanced > Show Develop menu in menu bar_).
- Chrome: Install the Web Developer Toolbar extension, then restart the browser. Click the gear icon that will appear, then select _CSS > Disable All Styles_.
- Edge: Select _View > Style > No Style_ from the main menu.
#### Using native keyboard accessibility
Certain HTML features can be selected using only the keyboard — this is default behavior, available since the early days of the web. The elements that have this capability are the common ones that allow user to interact with web pages, namely links, {{htmlelement("button")}}s, and form elements like {{htmlelement("input")}}.
You can try this out using our [native-keyboard-accessibility.html](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html) example (see the [source code](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html)) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused.

> **Note:** In Firefox, you can also enable an overlay that shows the page tabbing order. For more information see: [Accessibility Inspector > Show web page tabbing order](https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/index.html#show-web-page-tabbing-order).
You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the {{htmlelement("select")}} element can have its options displayed and cycled between using the up and down arrow keys).
Note that different browsers may have different keyboard control options available. Most modern browsers follow the tab pattern described above (you can also do Shift + Tab to move backwards through the focusable elements), but some browsers have their own idiosyncrasies:
- Firefox for the Mac doesn't do tabbing by default. To turn it on, you have to go to _Preferences > Advanced > General_, then uncheck "Always use the cursor keys to navigate within pages". Next, you have to open your Mac's System Preferences app, then go to _Keyboard > Shortcuts_, then select the _All Controls_ radio button.
- Safari doesn't allow you to tab through links by default; to enable this, you need to open Safari's _Preferences_, go to Advanced, and check the _Press Tab to highlight each item on a webpage_ checkbox.
> **Warning:** You should perform this kind of test/review on any new page you write — make sure that functionality can be accessed by the keyboard, and that the tab order provides a sensible navigation path through the document.
This example highlights the importance of using the correct semantic element for the correct job. It is possible to style _any_ element to look like a link or button with CSS, and to behave like a link or button with JavaScript, but they won't actually be links or buttons, and you'll lose a lot of the accessibility these elements give you for free. So don't do it if you can avoid it.
Another tip — as shown in our example, you can control how your focusable elements look when focused, using the [:focus](/en-US/docs/Web/CSS/:focus) pseudo-class. It is a good idea to double up focus and hover styles, so your users get that visual clue that a control will do something when activated, whether they are using mouse or keyboard:
```css
a:hover,
input:hover,
button:hover,
select:hover,
a:focus,
input:focus,
button:focus,
select:focus {
font-weight: bold;
}
```
> **Note:** If you do decide to remove the default focus styling using CSS, make sure you replace it with something else that fits in with your design better — it is a very valuable accessibility tool, and should not be removed.
#### Building in keyboard accessibility
Sometimes it is not possible to avoid losing keyboard accessibility. You might have inherited a site where the semantics are not very good (perhaps you've ended up with a horrible CMS that generates buttons made with `<div>`s), or you are using a complex control that does not have keyboard accessibility built in, like the HTML {{htmlelement("video")}} element (amazingly, Opera is the only browser that allows you to tab through the `<video>` element's default browser controls). You have a few options here:
1. Create custom controls using `<button>` elements (which we can tab to by default!) and JavaScript to wire up their functionality. See [Creating a cross-browser video player](/en-US/docs/Web/Media/Audio_and_video_delivery/cross_browser_video_player) for some good examples of this.
2. Create keyboard shortcuts via JavaScript, so functionality is activated when you press certain keys on the keyboard. See [Desktop mouse and keyboard controls](/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_mouse_and_keyboard) for some game-related examples that can be adapted for any purpose.
3. Use some interesting tactics to fake button behavior. Take for example our [fake-div-buttons.html](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/fake-div-buttons.html) example (see [source code](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/accessibility/fake-div-buttons.html)). Here we've given our fake `<div>` buttons the ability to be focused (including via tab) by giving each one the attribute `tabindex="0"` (see WebAIM's [tabindex article](https://webaim.org/techniques/keyboard/tabindex) for more really useful details). This allows us to tab to the buttons, but not to activate them via the Enter/Return key. To do that, we had to add the following bit of JavaScript trickery:
```js
document.onkeydown = (e) => {
if (e.keyCode === 13) {
// The Enter/Return key
document.activeElement.onclick(e);
}
};
```
Here we add a listener to the `document` object to detect when a button has been pressed on the keyboard. We check what button was pressed via the event object's [keyCode](/en-US/docs/Web/API/KeyboardEvent/keyCode) property; if it is the keycode that matches Return/Enter, we run the function stored in the button's `onclick` handler using `document.activeElement.onclick()`. [`activeElement`](/en-US/docs/Web/API/Document/activeElement) gives us the element that is currently focused on the page.
> **Note:** This technique will only work if you set your original event handlers via event handler properties (e.g. `onclick`). `addEventListener` won't work. This is a lot of extra hassle to build the functionality back in. And there's bound to be other problems with it. Better to just use the right element for the right job in the first place.
#### Text alternatives
Text alternatives are very important for accessibility — if a person has a visual or hearing impairment that stops them being able to see or hear some content, then this is a problem. The simplest text alternative available is the humble `alt` attribute, which we should include on all images that contain relevant content. This should contain a description of the image that successfully conveys its meaning and content on the page, to be picked up by a screen reader and read out to the user.
> **Note:** For more information, read [Text alternatives](/en-US/docs/Learn/Accessibility/HTML#text_alternatives).
Missing alt text can be tested for in a number of ways, for example using accessibility [Auditing tools](#auditing_tools).
Alt text is slightly more complex for video and audio content. There is a way to define text tracks (e.g. subtitles) and display them when video is being played, in the form of the {{htmlelement("track")}} element, and the [WebVTT](/en-US/docs/Web/API/WebVTT_API) format (see [Adding captions and subtitles to HTML video](/en-US/docs/Web/Media/Audio_and_video_delivery/Adding_captions_and_subtitles_to_HTML5_video) for a detailed tutorial). [Browser compatibility](/en-US/docs/Web/Media/Audio_and_video_delivery/Adding_captions_and_subtitles_to_HTML5_video#browser_compatibility) for these features is fairly good, but if you want to provide text alternatives for audio or support older browsers, a simple text transcript presented somewhere on the page or on a separate page might be a good idea.
#### Element relationships and context
There are certain features and best practices in HTML designed to provide context and relationships between elements where none otherwise exists. The three most common examples are links, form labels, and data tables.
The key to accessible link text is that people using screen readers will often use a common feature whereby they pull up a list of all the links on the page. In this case, the link text needs to make sense out of context. For example, a list of links labeled "click here", "click me", etc. is really bad for accessibility. It is better for link text to make sense in context and out of context.
Next on our list, the form {{htmlelement("label")}} element is one of the central features that allows us to make forms accessible. The trouble with forms is that you need labels to say what data should be entered into each form input. Each label needs to be included inside a {{htmlelement("label")}} to link it unambiguously to its partner form input (the `for` attribute value of each `<label>` needs to match the form element `id` value), and it will make sense even if the source order is not completely logical (which to be fair it should be).
> **Note:** For more information about link text and form labels, read [Meaningful text labels](/en-US/docs/Learn/Accessibility/HTML#meaningful_text_labels).
Finally, a quick word about data tables. A basic data table can be written with very simple markup (see `bad-table.html` [live](https://mdn.github.io/learning-area/accessibility/html/bad-table.html), and [source](https://github.com/mdn/learning-area/blob/main/accessibility/html/bad-table.html)), but this has problems — there is no way for a screen reader user to associate rows or columns together as groupings of data — to do this you need to know what the header rows are, and if they are heading up rows, columns, etc. This can only be done visually for such a table.
If you instead look at our `punk-bands-complete.html` example ([live](https://mdn.github.io/learning-area/css/styling-boxes/styling-tables/punk-bands-complete.html), [source](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/styling-tables/punk-bands-complete.html)), you can see a few accessibility aids at work here, such as table headers ({{htmlelement("th")}} and `scope` attributes), {{htmlelement("caption")}} element, etc.
> **Note:** For more information about accessible tables, read [Accessible data tables](/en-US/docs/Learn/Accessibility/HTML#accessible_data_tables).
### CSS
CSS tends to provide a lot fewer fundamental accessibility features than HTML, but it can still do just as much damage to accessibility if used incorrectly. We have already mentioned a couple of accessibility tips involving CSS:
- Use the correct semantic elements to mark up different content in HTML; if you want to create a different visual effect, use CSS — don't abuse an HTML element to get the look you want. For example, if you want bigger text, use {{cssxref("font-size")}}, not an {{htmlelement("Heading_Elements", "h1")}} element.
- Make sure your source order makes sense without CSS; you can always use CSS to style the page any way you want afterward.
- You should make sure interactive elements like buttons and links have appropriate focus/hover/active states set, to give the user visual clues as to their function. If you remove the defaults for stylistic reasons, make sure you include some replacement styles.
There are a few other considerations you should take into account.
#### Color and color contrast
When choosing a color scheme for your website, you should make sure that the text (foreground) color contrasts well with the background color. Your design might look cool, but it is no good if people with visual impairments like color blindness can't read your content. Use a tool like WebAIM's [Color Contrast Checker](https://webaim.org/resources/contrastchecker/) to check whether your scheme is contrasting enough.
Another tip is to not rely on color alone for signposts/information, as this will be no good for those who can't see the color. Instead of marking required form fields in red, for example, mark them with an asterisk and in red.
> **Note:** A high contrast ratio will also allow anyone using a smartphone or tablet with a glossy screen to better read pages when in a bright environment, such as sunlight.
#### Hiding content
There are many instances where a visual design will require that not all content is shown at once. For example, in our [Tabbed info box example](https://mdn.github.io/learning-area/css/css-layout/practical-positioning-examples/info-box.html) (see [source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/practical-positioning-examples/info-box.html)) we have three panels of information, but we are [positioning](/en-US/docs/Learn/CSS/CSS_layout/Positioning) them on top of one another and providing tabs that can be clicked to show each one (it is also keyboard accessible — you can alternatively use Tab and Enter/Return to select them).

Screen reader users don't care about any of this — they are happy with the content as long as the source order makes sense, and they can get to it all. Absolute positioning (as used in this example) is generally seen as one of the best mechanisms of hiding content for visual effect, because it doesn't stop screen readers from getting to it.
On the other hand, you shouldn't use {{cssxref("visibility")}}`:hidden` or {{cssxref("display")}}`:none`, because they do hide content from screen readers. Unless of course, there is a good reason why you want this content to be hidden from screen readers.
> **Note:** [Invisible Content Just for Screen Reader Users](https://webaim.org/techniques/css/invisiblecontent/) has a lot more useful detail surrounding this topic.
### JavaScript
JavaScript has the same kind of problems as CSS with respect to accessibility — it can be disastrous for accessibility if used badly, or overused. We've already hinted at some accessibility problems related to JavaScript, mainly in the area of semantic HTML — you should always use appropriate semantic HTML to implement functionality wherever it is available, for example use links and buttons as appropriate. Don't use `<div>` elements with JavaScript code to fake functionality if at all possible — it is error-prone, and more work than using the free functionality HTML gives you.
#### Simple functionality
Generally simple functionality should work with just the HTML in place — JavaScript should only be used to enhance functionality, not build it in entirely. Good uses of JavaScript include:
- Providing client-side form validation, which alerts users to problems with their form entries quickly, without having to wait for the server to check the data. If it isn't available, the form will still work, but validation might be slower.
- Providing custom controls for HTML `<video>`s that are accessible to keyboard-only users (as we said earlier, the default browser controls aren't keyboard-accessible in most browsers).
> **Note:** WebAIM's [Accessible JavaScript](https://webaim.org/techniques/javascript/) provides some useful further details about considerations for accessible JavaScript.
More complex JavaScript implementations can create issues with accessibility — you need to do what you can. For example, it would be unreasonable to expect you to make a complex 3D game written using [WebGL](/en-US/docs/Glossary/WebGL) 100% accessible to a blind person, but you could implement [keyboard controls](/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_mouse_and_keyboard) so it is usable by non-mouse users, and make the color scheme contrasting enough to be usable by those with color deficiencies.
#### Complex functionality
One of the main areas problematic for accessibility is complex apps that involve complicated form controls (such as date pickers) and dynamic content that is updated often and incrementally.
Non-native complicated form controls are problematic because they tend to involve a lot of nested `<div>`s, and the browser does not know what to do with them by default. If you are inventing them yourself, you need to make sure that they are keyboard accessible; if you are using some kind of third-party framework, carefully review the options available to see how accessible they are before diving in. [Bootstrap](https://getbootstrap.com/) looks to be fairly good for accessibility, for example, although [Making Bootstrap a Little More Accessible](https://www.sitepoint.com/making-bootstrap-accessible/) by Rhiana Heath explores some of its issues (mainly related to color contrast), and looks at some solutions.
Regularly updated dynamic content can be a problem because screen reader users might miss it, especially if it updates unexpectedly. If you have a single-page app with a main content panel that is regularly updated using [XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest) or [Fetch](/en-US/docs/Web/API/Fetch_API), a screen reader user might miss those updates.
#### WAI-ARIA
Do you need to use such complex functionality, or will plain old semantic HTML do instead? If you do need complexity, you should consider using [WAI-ARIA](https://www.w3.org/TR/wai-aria-1.1/) (Accessible Rich Internet Applications), a specification that provides semantics (in the form of new HTML attributes) for items such as complex form controls and updating panels that can be understood by most browsers and screen readers.
To deal with complex form widgets, you need to use ARIA attributes like `roles` to state what role different elements have in a widget (for example, are they a tab, or a tab panel?), `aria-disabled` to say whether a control is disabled or not, etc.
To deal with regularly updating regions of content, you can use the `aria-live` attribute, which identifies an updating region. Its value indicates how urgently the screen reader should read it out:
- `off:` The default. Updates should not be announced.
- `polite`: Updates should be announced only if the user is idle.
- `assertive`: Updates should be announced to the user as soon as possible.
- `rude`: Updates should be announced straight away, even if this interrupts the user.
Here's an example:
```html
<p><span id="LiveRegion1" aria-live="polite" aria-atomic="false"></span></p>
```
You can see an example in action at Freedom Scientific's [ARIA (Accessible Rich Internet Applications) Live Regions](https://www.freedomscientific.com/SurfsUp/AriaLiveRegions.htm) example — the highlighted paragraph should update its content every 10 seconds, and a screen reader should read this out to the user. [ARIA Live Regions - Atomic](https://www.freedomscientific.com/SurfsUp/AriaLiveRegionsAtomic.htm) provides another useful example.
We don't have space to cover WAI-ARIA in detail here, you can learn a lot more about it at [WAI-ARIA basics](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics).
## Accessibility tools
Now we've covered accessibility considerations for different web technologies, including a few testing techniques (like keyboard navigation and color contrast checkers), let's have a look at other tools you can make use of when doing accessibility testing.
### Auditing tools
There are a number of auditing tools available that you can feed your web pages into. They will look over them and return a list of accessibility issues present on the page. Examples include:
- [Wave](https://wave.webaim.org/): A rather nice online accessibility testing tool that accepts a web address and returns a useful annotated view of that page with accessibility problems highlighted.
- [Tenon](https://tenon.io): Another nice online tool that goes through the code at a provided URL and returns results on accessibility errors including metrics, specific errors along with the WCAG criteria they affect, and suggested fixes. It requires a free trial signup to view the results.
Let's look at an example, using Wave.
1. Go to the [Wave homepage](https://wave.webaim.org/).
2. Enter the URL of our [bad-semantics.html](https://mdn.github.io/learning-area/accessibility/html/bad-semantics.html) example into the text input box near the top of the page. Then press enter or click/tap the arrow at the far right edge of the input box.
3. The site should respond with a description of the accessibility problems. Click the icons displayed to see more information about each of the issues identified by Wave's evaluation.
> **Note:** Such tools aren't good enough to solve all your accessibility problems on their own. You'll need a combination of these, knowledge and experience, user testing, etc. to get a full picture.
### Automation tools
[Deque's aXe tool](https://www.deque.com/axe/) goes a bit further than the auditing tools we mentioned above. Like the others, it checks pages and returns accessibility errors. Its most immediately useful form is probably the browser extensions:
- [aXe for Chrome](https://chrome.google.com/webstore/detail/axe-devtools-web-accessib/lhdoppojpmngadmnindnejefpokejbdd)
- [aXe for Firefox](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/)
These add an accessibility tab to the browser developer tools. For example, we installed the Firefox version, then used it to audit our [bad-table.html](https://mdn.github.io/learning-area/accessibility/html/bad-table.html) example. We got the following results:

aXe is also installable using `npm`, and can be integrated with task runners like [Grunt](https://gruntjs.com/) and [Gulp](https://gulpjs.com/), automation frameworks like [Selenium](https://www.selenium.dev/) and [Cucumber](https://cucumber.io/), unit testing frameworks like [Jasmine](https://jasmine.github.io/), and more besides (again, see the [main aXe page](https://www.deque.com/axe/) for details).
### Screen readers
It is definitely worth testing with a screen reader to get used to how severely visually impaired people use the Web. There are a number of screen readers available:
- Some are paid-for commercial products, like [JAWS](https://www.freedomscientific.com/Products/software/JAWS/) (Windows) and [Window Eyes](http://www.gwmicro.com/) (Windows).
- Some are free products, like [NVDA](https://www.nvaccess.org/) (Windows), [ChromeVox](https://support.google.com/chromebook/answer/7031755) (Chrome, Windows, and macOS), and [Orca](https://wiki.gnome.org/Projects/Orca) (Linux).
- Some are built into the operating system, like [VoiceOver](https://www.apple.com/accessibility/vision/) (macOS and iOS), [ChromeVox](https://support.google.com/chromebook/answer/7031755) (on Chromebooks), and [TalkBack](https://play.google.com/store/apps/details?id=com.google.android.marvin.talkback) (Android).
Generally, screen readers are separate apps that run on the host operating system and can read not only web pages, but text in other apps as well. This is not always the case (ChromeVox is a browser extension), but usually, screen readers tend to act in slightly different ways and have different controls, so you'll have to consult the documentation for your chosen screen reader to get all the details — saying that, they all work in basically the same sort of way.
Let's go through some tests with a couple of different screen readers to give you a general idea of how they work and how to test with them.
> **Note:** WebAIM's [Designing for Screen Reader Compatibility](https://webaim.org/techniques/screenreader/) provides some useful information about screen reader usage and what works best for screen readers. Also see [Screen Reader User Survey #9 Results](https://webaim.org/projects/screenreadersurvey9/#used) for some interesting screen reader usage statistics.
#### VoiceOver
VoiceOver (VO) comes free with your Mac/iPhone/iPad, so it's useful for testing on desktop/mobile if you use Apple products. We'll be testing it on Mac OS X on a MacBook Pro.
To turn it on, press Cmd + F5. If you've not used VO before, you will be given a welcome screen where you can choose to start VO or not, and run through a rather useful tutorial to learn how to use it. To turn it off again, press Cmd + F5 again.
> **Note:** You should go through the tutorial at least once — it is a really useful way to learn VO.
When VO is on, the display will look mostly the same, but you'll see a black box at the bottom left of the screen that contains information on what VO currently has selected. The current selection will also be highlighted, with a black border — this highlight is known as the **VO cursor**.

To use VO, you will make a lot of use of the "VO modifier" — this is a key or key combination that you need to press in addition to the actual VO keyboard shortcuts to get them to work. Using a modifier like this is common with screen readers, to enable them to keep their commands from clashing with other commands. In the case of VO, the modifier can either be CapsLock, or Ctrl + Option.
VO has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "VO" means "the VoiceOver modifier".
<table class="standard-table no-markdown">
<caption>
Most common VoiceOver keyboard shortcuts
</caption>
<thead>
<tr>
<th scope="col">Keyboard shortcut</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>VO + Cursor keys</td>
<td>Move the VO cursor up, right, down, left.</td>
</tr>
<tr>
<td>VO + Spacebar</td>
<td>
Select/activate items highlighted by the VO cursor. This includes items
selected in the Rotor (see below).
</td>
</tr>
<tr>
<td>VO + Shift + down cursor</td>
<td>
Move into a group of items (such as an HTML table, or a form, etc.) Once
inside a group you can move around and select items inside that group
using the above commands as normal.
</td>
</tr>
<tr>
<td>VO + Shift + up cursor</td>
<td>Move out of a group.</td>
</tr>
<tr>
<td>VO + C</td>
<td>(when inside a table) Read the header of the current column.</td>
</tr>
<tr>
<td>VO + R</td>
<td>(when inside a table) Read the header of the current row.</td>
</tr>
<tr>
<td>VO + C + C (two Cs in succession)</td>
<td>
(when inside a table) Read the entire current column, including header.
</td>
</tr>
<tr>
<td>VO + R + R (two Rs in succession)</td>
<td>
(when inside a table) Read the entire current row, including the headers
that correspond to each cell.
</td>
</tr>
<tr>
<td>VO + left cursor, VO + right cursor</td>
<td>
(when inside some horizontal options, such as a date or time picker)
Move between options.
</td>
</tr>
<tr>
<td>VO + up cursor, VO + down cursor</td>
<td>
(when inside some horizontal options, such as a date or time picker)
Change the current option.
</td>
</tr>
<tr>
<td>VO + U</td>
<td>
Use the Rotor, which displays lists of headings, links, form controls,
etc. for easy navigation.
</td>
</tr>
<tr>
<td>VO + left cursor, VO + right cursor</td>
<td>
(when inside Rotor) Move between different lists available in the Rotor.
</td>
</tr>
<tr>
<td>VO + up cursor, VO + down cursor</td>
<td>
(when inside Rotor) Move between different items in the current Rotor
list.
</td>
</tr>
<tr>
<td>Esc</td>
<td>(when inside Rotor) Exit Rotor.</td>
</tr>
<tr>
<td>Ctrl</td>
<td>(when VO is speaking) Pause/Resume speech.</td>
</tr>
<tr>
<td>VO + Z</td>
<td>Restart the last bit of speech.</td>
</tr>
<tr>
<td>VO + D</td>
<td>Go into the Mac's Dock, so you can select apps to run inside it.</td>
</tr>
</tbody>
</table>
This seems like a lot of commands, but it isn't so bad when you get used to it, and VO regularly gives you reminders of what commands to use in certain places. Have a play with VO now; you can then go on to play with some of our examples in the [Screen reader testing](#screen_reader_testing) section.
#### NVDA
NVDA is Windows-only, and you'll need to install it.
1. Download it from [nvaccess.org](https://www.nvaccess.org/). You can choose whether to make a donation or download it for free; you'll also need to give them your email address before you can download it.
2. Once downloaded, install it — you double-click the installer, accept the license and follow the prompts.
3. To start NVDA, double-click on the program file/shortcut, or use the keyboard shortcut Ctrl + Alt + N. You'll see the NVDA welcome dialog when you start it. Here you can choose from a couple of options, then press the _OK_ button to get going.
NVDA will now be active on your computer.
To use NVDA, you will make a lot of use of the "NVDA modifier" — this is a key that you need to press in addition to the actual NVDA keyboard shortcuts to get them to work. Using a modifier like this is common with screen readers, to enable them to keep their commands from clashing with other commands. In the case of NVDA, the modifier can either be Insert (the default), or CapsLock (can be chosen by checking the first checkbox in the NVDA welcome dialog before pressing _OK_).
> **Note:** NVDA is more subtle than VoiceOver in terms of how it highlights where it is and what it is doing. When you are scrolling through headings, lists, etc., items you are selected on will generally be highlighted with a subtle outline, but this is not always the case for all things. If you get completely lost, you can press Ctrl + F5 to refresh the current page and begin from the top again.
NVDA has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "NVDA" means "the NVDA modifier".
<table class="standard-table no-markdown">
<caption>
Most common NVDA keyboard shortcuts
</caption>
<thead>
<tr>
<th scope="col">Keyboard shortcut</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>NVDA + Q</td>
<td>Turn NVDA off again after you've started it.</td>
</tr>
<tr>
<td>NVDA + up cursor</td>
<td>Read the current line.</td>
</tr>
<tr>
<td>NVDA + down cursor</td>
<td>Start reading at the current position.</td>
</tr>
<tr>
<td>Up cursor and down cursor, or Shift + Tab and Tab</td>
<td>Move to previous/next item on page and read it.</td>
</tr>
<tr>
<td>Left cursor and right cursor</td>
<td>Move to previous/next character in current item and read it.</td>
</tr>
<tr>
<td>Shift + H and H</td>
<td>Move to previous/next heading and read it.</td>
</tr>
<tr>
<td>Shift + K and K</td>
<td>Move to previous/next link and read it.</td>
</tr>
<tr>
<td>Shift + D and D</td>
<td>
Move to previous/next document landmark (e.g. <code><nav></code>)
and read it.
</td>
</tr>
<tr>
<td>Shift + 1–6 and 1–6</td>
<td>Move to previous/next heading (level 1–6) and read it.</td>
</tr>
<tr>
<td>Shift + F and F</td>
<td>Move to previous/next form input and focus on it.</td>
</tr>
<tr>
<td>Shift + T and T</td>
<td>Move to previous/next data table and focus on it.</td>
</tr>
<tr>
<td>Shift + B and B</td>
<td>Move to previous/next button and read its label.</td>
</tr>
<tr>
<td>Shift + L and L</td>
<td>Move to previous/next list and read its first list item.</td>
</tr>
<tr>
<td>Shift + I and I</td>
<td>Move to previous/next list item and read it.</td>
</tr>
<tr>
<td>Enter/Return</td>
<td>
(when link/button or other activatable item is selected) Activate item.
</td>
</tr>
<tr>
<td>NVDA + Space</td>
<td>
(when form is selected) Enter form so individual items can be selected,
or leave form if you are already in it.
</td>
</tr>
<tr>
<td>Shift Tab and Tab</td>
<td>(when inside form) Move between form inputs.</td>
</tr>
<tr>
<td>Up cursor and down cursor</td>
<td>
(when inside form) Change form input values (in the case of things like
select boxes).
</td>
</tr>
<tr>
<td>Spacebar</td>
<td>(when inside form) Select chosen value.</td>
</tr>
<tr>
<td>Ctrl + Alt + cursor keys</td>
<td>(when a table is selected) Move between table cells.</td>
</tr>
</tbody>
</table>
#### Screen reader testing
Now you've gotten used to using a screen reader, we'd like you to use it to do some quick accessibility tests, to get an idea of how screen readers deal with good and bad webpage features:
- Look at [good-semantics.html](https://mdn.github.io/learning-area/accessibility/html/good-semantics.html), and note how the headers are found by the screen reader and available to use for navigation. Now look at [bad-semantics.html](https://mdn.github.io/learning-area/accessibility/html/bad-semantics.html), and note how the screen reader gets none of this information. Imagine how annoying this would be when trying to navigate a really long page of text.
- Look at [good-links.html](https://mdn.github.io/learning-area/accessibility/html/good-links.html), and note how they make sense when viewed out of context. This is not the case with [bad-links.html](https://mdn.github.io/learning-area/accessibility/html/bad-links.html) — they are all just "click here".
- Look at [good-form.html](https://mdn.github.io/learning-area/accessibility/html/good-form.html), and note how the form inputs are described using their labels because we've used `<label>` elements properly. In [bad-form.html](https://mdn.github.io/learning-area/accessibility/html/bad-form.html), they get an unhelpful label along the lines of "blank".
- Look at our [punk-bands-complete.html](https://mdn.github.io/learning-area/css/styling-boxes/styling-tables/punk-bands-complete.html) example, and see how the screen reader is able to associate columns and rows of content and read them out all together because we've defined headers properly. In [bad-table.html](https://mdn.github.io/learning-area/accessibility/html/bad-table.html), none of the cells can be associated at all. Note that NVDA seems to behave slightly strangely when you've only got a single table on a page; you could try [WebAIM's table test page](https://webaim.org/articles/nvda/tables.htm) instead.
- Have a look at the [WAI-ARIA live regions example](https://www.freedomscientific.com/SurfsUp/AriaLiveRegions.htm) we saw earlier, and note how the screen reader will keep reading out the constantly updating section as it updates.
### User testing
As mentioned above, you can't rely on automated tools alone for determining accessibility problems on your site. It is recommended that when you draw up your testing plan, you should include some accessibility user groups if at all possible (see our [User Testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies#user_testing) section earlier on in the course for some more context). Try to get some screen reader users involved, some keyboard-only users, some non-hearing users, and perhaps other groups too, as suits your requirements.
## Accessibility testing checklist
The following list provides a checklist for you to follow to make sure you've carried out the recommended accessibility testing for your project:
1. Make sure your HTML is as semantically correct as possible. [Validating it](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS#validation) is a good start, as is using an [Auditing tool](#auditing_tools).
2. Check that your content makes sense when the CSS is turned off.
3. Make sure your functionality is [keyboard accessible](#using_native_keyboard_accessibility). Test using Tab, Return/Enter, etc.
4. Make sure your non-text content has [text alternatives](#text_alternatives). An [Auditing tool](#auditing_tools) is good for catching such problems.
5. Make sure your site's [color contrast](#color_and_color_contrast) is acceptable, using a suitable checking tool.
6. Make sure [hidden content](#hiding_content) is visible by screen readers.
7. Make sure that functionality is usable without JavaScript wherever possible.
8. Use ARIA to improve accessibility where appropriate.
9. Run your site through an [Auditing tool](#auditing_tools).
10. Test it with a screen reader.
11. Include an accessibility policy/statement somewhere findable on your site to say what you did.
## Finding help
There are many other issues you'll encounter with accessibility; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's [Finding help section](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS#finding_help) for some good pointers.
## Summary
Hopefully this article has given you a good grounding in the main accessibility problems you might encounter, and how to test and overcome them.
In the next article we'll look at feature detection in more detail.
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing | data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing/testing_strategies/index.md | ---
title: Strategies for carrying out testing
slug: Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/Introduction","Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS", "Learn/Tools_and_testing/Cross_browser_testing")}}
This article explains how to do cross-browser testing: how to choose which browsers and devices to test, how to actually test those browsers and devices, and how to test with user groups.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages; an idea
of the high-level
<a
href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction"
>principles of cross-browser testing</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To gain an understanding of the high-level concepts involved in
cross-browser testing.
</td>
</tr>
</tbody>
</table>
## Choosing which browsers and devices to test
Since you can't test every combination of browser and device, it's enough that you ensure your site works on the most important ones. In practical applications, "important" often means "commonly used among the target audience."
You can classify browsers and devices by the amount of support you intend to give. For example:
1. A-grade: Common/modern browsers — Known to be capable. Test thoroughly and provide full support.
2. B-grade: Older/less capable browsers — known not to be capable. Test, and provide a more basic experience that gives full access to core information and services.
3. C-grade: Rare/unknown browsers — don't test, but assume they are capable. Serve the full site, which should work, at least with the fallbacks provided by our defensive coding.
In the following sections, we'll build up a support chart in this format.
> **Note:** Yahoo first made this approach popular, with their [Graded browser Support](https://github.com/yui/yui3/wiki/Graded-Browser-Support) approach.
### Predict your audience's most commonly used browsers
This typically involves making educated guesses based on user demographics. For example, suppose your users are in North America and Western Europe:
A quick online search tells you that most people in North America and Western Europe use Windows or Mac desktops/laptops, where the main browsers are Chrome, Firefox, Safari, and Edge. You'd probably want to just test the latest versions of these browsers, as these browsers get regular updates. These should all go in the A-grade tier.
Most people in this demographic also use either iOS or Android phones, so you'd probably want to test the latest versions of iOS Safari, the last couple of versions of the old Android stock browser, and Chrome and Firefox for iOS and Android. You should ideally test these on both a phone and a tablet, to ensure responsive designs work.
Opera Mini [isn't very capable of running complex JavaScript](https://dev.opera.com/articles/opera-mini-and-javascript/), so we should put this into grade B as well.
Thus, we've based our choice of which browsers to test on the browsers that we expect our users to use.
This gives us the following support chart so far:
1. A-grade: Chrome and Firefox for Windows/Mac, Safari for Mac, Edge for Windows, iOS Safari for iPhone/iPad, Android stock browser (last two versions) on phone/tablet, Chrome, and Firefox for Android (last two versions) on phone/tablet
2. B-grade: Opera Mini
3. C-grade: n/a
If your target audience is mostly located somewhere else, then the most common browsers and OSs may differ from the above.
> **Note:** "The CEO of my company uses a Blackberry, so we'd better make sure it looks good on that" can also be something to consider.
### Browser statistics
Some websites show which browsers are popular in a given region. For example, [Statcounter](https://gs.statcounter.com/) gives an idea of trends in North America.
### Using analytics
A much more accurate source of data, if you can get it, is an analytics app like [Google Analytics](https://marketingplatform.google.com/about/analytics/), which tells you exactly what browsers people are using to browse your site. Of course, this relies on you already having a site to use it on, so it isn't good for completely new sites.
You may also consider using open-source and privacy-focused analytics platforms like [Open Web Analytics](https://www.openwebanalytics.com/) and [Matomo](https://matomo.org). They expect you to self-host the analytics platform.
#### Setting up Google analytics
1. First of all, you'll need a Google account. Use this account to sign into [Google Analytics](https://marketingplatform.google.com/about/analytics/).
2. Choose the [Google Analytics](https://analytics.google.com/analytics/web/) (web) option, and click the _Sign Up_ button.
3. Enter your website/app details into the signup page. This is fairly intuitive to set up; the most important field to get right is the website URL. This needs to be your site/app's root URL.
4. Once you've finished filling in everything, press the _Get Tracking ID_ button, then accept the terms of service that appear.
5. The next page provides you with some code snippets and other instructions. For a basic website, what you need to do is copy the _Website tracking_ code block and paste it into all the different pages you want to track using Google Analytics on your site. You could place the snippets below your closing `</body>` tag, or somewhere else appropriate that keeps it from getting muddled up with your application code.
6. Upload the changes to the development server, or wherever else you need your code.
That's it! Your site should now be ready to start reporting analytics data.
#### Studying analytics data
Now you should be able to go back to the [Analytics Web](https://analytics.google.com/analytics/web) homepage, and start looking at the data you've collected about your site (you need to leave a little bit of time for some data to actually be collected, of course.)
By default, you should see the reporting tab, like so:

There is a huge amount of data you could look at using Google Analytics — customized reports in different categories, etc. — and we haven't got time to discuss it all.
[Getting started with Analytics](https://support.google.com/analytics/answer/9306384?visit_id=637855964517698041-2103767437&rd=1) provides some useful guidance on reporting (and more) for beginners.
You can see what browsers and operating systems your users are using by selecting _Audience > Technology > Browser & OS_ from the left-hand menu.
> **Note:** When using Google analytics, you need to beware of misleading bias, e.g. "We have no Firefox Mobile users" might lead you to not bother supporting Firefox mobile. But you are not going to have any Firefox Mobile users if the site was broken on Firefox mobile in the first place.
### Other considerations
You should include accessibility as a grade A testing requirement (we'll cover exactly what you should test in our Handling common accessibility problems article).
Also, you should be aware of situation-specific needs. For example, if you are creating some kind of company intranet for delivering sales figures to managers, and all the managers have been provided with Windows phones, you will probably want to make mobile IE support a priority.
### Final support chart
So, our final support chart will end up looking like so:
1. A-grade: Chrome and Firefox for Windows/Mac, Safari for Mac, and Edge (last two versions of each), iOS Safari for iPhone/iPad, Android stock browser (last two versions) on phone/tablet, Chrome, and Firefox for Android (last two versions) on phone tablet. Accessibility passing common tests.
2. B-grade: Opera Mini.
3. C-grade: Opera, other niche modern browsers.
## What are you going to test?
When you've got a new addition to your codebase that needs testing, before you start testing you should write out a list of testing requirements that need to pass to be accepted. These requirements can be visual or functional — both combine to make a usable website feature.
Consider the following example (see the [source code](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/strategies/hidden-info-panel.html), and also the [example running live](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/strategies/hidden-info-panel.html)):

Test criteria for this feature could be written like so:
A and B grade:
- Button should be activatable by the user's primary control mechanism, whatever it is — this should include mouse, keyboard, and touch.
- Toggling the button should make the information box appear/disappear.
- The text should be readable.
- Visually impaired users using screen readers should be able to access the text.
A-grade:
- The information box should animate smoothly as it appears/disappears.
- The gradient and text shadow should appear to enhance the look of the box.
You may notice from the text in the example that it won't work in IE8 — this is a problem according to our support chart, which you'll have to work on, perhaps by using a feature detection library to implement the functionality in a different way if the browser doesn't support CSS transitions (see Implementing feature detection, later on in the course).
You might also notice that the button isn't usable using only the keyboard — this also needs to be remedied. Maybe we could use some JavaScript to implement a keyboard control for the toggle, or use some other method entirely?
These test criteria are useful, because:
- They give you a set of steps to follow when you are performing tests.
- They can be easily turned into sets of instructions for user groups to follow when carrying out tests (e.g. "try to activate the button using your mouse, and then the keyboard…") — see [User testing](#user_testing), below.
- They can also provide a basis for writing automated tests. It is easier to write such tests if you know exactly what you want to test, and what the success conditions are (see [Selenium](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment#selenium), later in the series).
## Putting together a testing lab
One option for carrying out browser tests is to do the testing yourself. To do this, you will probably use a combination of actual physical devices, and emulated environments (using either an emulator or a virtual machine).
### Physical devices
It is generally better to have a real device running the browser you want to test — this provides the greatest accuracy in terms of behavior and overall user experience. You'll probably want something like the following, for a reasonable low-level device lab:
- A Mac, with the browsers installed that you need to test — this can include Firefox, Chrome, Opera, and Safari.
- A Windows PC, with the browsers installed that you need to test — this can include Edge (or IE), Chrome, Firefox, and Opera.
- A higher-spec Android phone and tablet with the browser installed that you need to test — this can include Chrome, Firefox, and Opera Mini for Android, as well as the original Android stock browser.
- A higher-spec iOS phone and tablet with the browsers installed that you need to test — this can include iOS Safari and Chrome, Firefox, and Opera Mini for iOS.
The following are also good options, if you can get them:
- A Linux PC available, in case you need to test bugs specific to Linux versions of browsers. Linux users commonly use Firefox, Opera, and Chrome. If you only have one machine available, you could consider creating a dual boot machine running Linux and Windows on separate partitions. Ubuntu's installer makes this quite easy to set up; see [WindowsDualBoot](https://help.ubuntu.com/community/WindowsDualBoot) for help with this.
- A couple of lower-spec mobile devices, so you can test the performance of features like animations on less powerful processors.
Your main work machine can also be a place to install other tools for specific purposes, such as accessibility auditing tools, screen readers, and emulators/virtual machines.
Some larger companies have device labs that stock a very large selection of different devices, enabling developers to hunt down bugs on very specific browser/device combinations. Smaller companies and individuals are generally not able to afford such a sophisticated lab, so tend to make do with smaller labs, emulators, virtual machines, and commercial testing apps.
We will cover each of the other options below.
> **Note:** Some efforts have been made to create publicly accessible device labs — see [Open Device Labs](https://www.smashingmagazine.com/2016/11/worlds-best-open-device-labs/).
> **Note:** We also need to consider accessibility — there are a number of useful tools you can install on your machine to facilitate accessibility testing, but we'll cover those in the Handling common accessibility problems article, later in the course.
### Emulators
Emulators are basically programs that run inside your computer and emulate a device or particular device conditions of some kind, allowing you to do some of your testing more conveniently than having to find a particular combination of hardware/software to test.
An emulator might be as simple as testing a device condition. For example, if you want to do some quick and dirty testing of your width/height media queries for responsive design, you could use Firefox's [Responsive Design Mode](https://firefox-source-docs.mozilla.org/devtools-user/responsive_design_mode/index.html). Safari has a similar mode too, which can be enabled by going to _Safari > Preferences_, and checking _Show Develop menu_, then choosing _Develop > Enter Responsive Design Mode_. Chrome also has something similar: Device mode (see [Simulate Mobile Devices with Device Mode](https://developer.chrome.com/docs/devtools/device-mode/)).
More often than not though, you'll have to install some kind of emulator. The most common devices/browsers you'll want to test are as follows:
- The official [Android Studio IDE](https://developer.android.com/studio/) for developing Android apps is a bit heavy weight for just testing websites on Google Chrome or the old Stock Android browser, but it does come with a Robust [emulator](https://developer.android.com/studio/run/emulator.html). If you want something a bit more lightweight, [Andy](https://www.andyroid.net/) is a reasonable option that runs on both Windows and Mac.
- Apple provides an app called [Simulator](https://help.apple.com/simulator/mac/current/) that runs on top of the [XCode](https://developer.apple.com/xcode/) development environment, and emulates iPad/iPhone/Apple Watch/Apple TV. This includes the native iOS Safari browser. This unfortunately only runs on a Mac.
You can often find simulators for other mobile device environments too, for example:
- You can emulate [Opera Mini](https://dev.opera.com/articles/installing-opera-mini-on-your-computer/) on its own if you want to test it.
- There are emulators available for Windows Mobile OSes: see [Windows Phone Emulator for Windows Phone 8](<https://msdn.microsoft.com/library/windows/apps/ff402563(v=vs.105).aspx>) and [Test with the Microsoft Emulator for Windows 10 Mobile](https://docs.microsoft.com/windows/uwp/debug-test-perf/test-with-the-emulator) (these only run on Windows).
> **Note:** Many emulators actually require the use of a virtual machine (see below); when this is the case, instructions are often provided, and/or use of the virtual machine is incorporated into the installer of the emulator.
### Virtual machines
Virtual machines are applications that run on your desktop computer and allow you to run emulations of entire operating systems, each compartmentalized in its own virtual hard drive (often represented by a single large file existing on the host machine's hard drive). There are a number of popular virtual machine apps available, such as [Parallels](https://www.parallels.com/), [VMWare](https://www.vmware.com/), and [Virtual Box](https://www.virtualbox.org/wiki/Downloads); we personally like the latter, because it is free.
> **Note:** You need a lot of hard disk space available to run virtual machine emulations; each operating system you emulate can take up a lot of memory. You tend to choose the hard drive space you want for each install; you could get away with probably 10GB, but some sources recommend up to 50GB or more, so the operating system will run reliably. A good option provided by most virtual machine apps is to create a **dynamically allocated** hard drive that grows and shrinks as the need arises.
To use a Virtual Box, you need to:
1. Get hold of an installer disk or image (e.g. ISO file) for the operating system you want to emulate. Virtual Box is unable to provide these; most, like Windows OSes, are commercial products that can't be freely distributed.
2. [Download the appropriate installer](https://www.virtualbox.org/wiki/Downloads) for your operating system and install it.
3. Open the app; you'll be presented with a view like the following: 
4. To create a new virtual machine, press the _New_ button in the top left-hand corner.
5. Follow the instructions and fill in the following dialog boxes as appropriate. You'll:
1. Provide a name for the new virtual machine
2. Choose which operating system and version you are installing on it
3. Set how much RAM should be allocated (we'd recommend something like 2048MB, or 2GB)
4. Create a virtual hard disk (choose the default options across the three dialog boxes containing _Create a virtual hard disk now_, _VDI (virtual disk image)_, and _Dynamically allocated_).
5. Choose the file location and size for the virtual hard disk (choose a sensible name and location to keep it, and for the size specify around 50GB, or as much as you are comfortable with specifying).
Now the new virtual box should appear in the left-hand menu of the main Virtual Box UI window. At this point, you can double-click to open it — it will start to boot up the virtual machine, but it won't yet have the operating system (OS) installed. At this point you need to point the dialog box at the installer image/disk, and it will run through the steps to install the OS just like on a physical machine.

> **Warning:** You need to make sure you have the operating system image you want to install on the virtual machine available at this point, and install it right away. If you cancel the process at this point, it can render the virtual machine unusable, and make it so you need to delete it and create it again. This is not fatal, but it is annoying.
After the process has completed, you should have a virtual machine running an operating system inside a window on your host computer.

You need to treat this virtual operating system installation just like you would any real installation — for example, as well as installing the browsers you want to test, install an anti-virus program to protect it from viruses.
Having multiple virtual machines is very useful, particularly for Windows IE/Edge testing — on Windows, you are not able to have multiple versions of the default browser installed side by side, so you might want to build up a library of virtual machines to handle different tests as required, e.g.:
- Windows 10 with Edge 14
- Windows 10 with Edge 13
> **Note:** Another good thing about virtual machines is that the virtual disk images are fairly self-contained. If you are working on a team, you can create one virtual disk image, then copy it and pass it around. Just make sure you have the required licenses to run all those copies of Windows or whatever else you are running if it is a licensed product.
### Automation and commercial apps
As mentioned in the last chapter, you can take a lot of the pain out of browser testing by using some kind of automation system. You can set up your own testing automation system ([Selenium](https://www.selenium.dev/) being the popular app of choice), which does take some setup, but can be very rewarding when you get it worked out.
There are also commercial tools available such as [Sauce Labs](https://saucelabs.com/), [Browser Stack](https://www.browserstack.com/) and [LambdaTest](https://www.lambdatest.com/) that do this kind of thing for you, without you having to worry about the setup, if you wish to invest some money in your testing.
Another alternative is to use no-code test automation tools such as [Endtest](https://endtest.io).
We will look at how to use such tools later on in the module.
## User testing
Before we move on, we'll finish this article off by talking a bit about user testing — this can be a good option if you have a willing user group to test your new functionality on. Bear in mind that this can be as lo-fi or as sophisticated as you like — your user group could be a group of friends, a group of colleagues, or a group of unpaid or paid volunteers, depending on whether you have any money to spend on testing.
Generally, you'll get your users to look at the page or view containing the new functionality on some kind of a development server, so you are not putting the final site or change live until it is finished. You should get them to follow some steps and report the results they get. It is useful to provide a set of steps (sometimes called a script) so that you get more reliable results pertaining to what you were trying to test. We mentioned this in the [What are you going to test](#what_are_you_going_to_test) section above — it is easy to turn the test criteria detailed there into steps to follow. For example, the following would work for a sighted user:
- Click the question mark button using the mouse on your desktop computer a few times. Refresh the browser window.
- Select and activate the question mark button using the keyboard on your desktop computer a few times.
- Tap the question mark button a few times on your touch screen device.
- Toggling the button should make the information box appear/disappear. Does it do this, in each of the above three cases?
- Is the text readable?
- Does the information box animate smoothly as it appears/disappears?
When running tests, it can also be a good idea to:
- Set up a separate browser profile where possible, with browser extensions and other such things disabled, and run your tests in that profile (see [Use the Profile Manager to create and remove Firefox profiles](https://support.mozilla.org/en-US/kb/profile-manager-create-remove-switch-firefox-profiles) and [Share Chrome with others or add personas](https://support.google.com/chrome/answer/2364824), for example).
- Use browser's private mode functionality when running tests, where available (e.g. [Private Browsing](https://support.mozilla.org/en-US/kb/private-browsing-use-firefox-without-history) in Firefox, [Incognito Mode](https://support.google.com/chrome/answer/95464) in Chrome) so things like cookies and temp files are not saved.
These steps are designed to make sure that the browser you are testing in is as "pure" as possible, i.e. there is nothing installed that could affect the results of the tests.
> **Note:** Another useful lo-fi option, if you have the hardware available, is to test your sites on low-end phones/other devices — as sites get larger and feature more effects, there is a higher chance of the site slowing down, so you need to start giving performance more consideration. Trying to get your functionality working on a low end device will make it more likely that the experience will be good on higher-end devices.
> **Note:** Some server-side development environments provide useful mechanisms for rolling out site changes to only a subset of users, providing a useful mechanism for getting a feature tested by a subset of users without the need for a separate development server. An example is [Django Waffle Flags](https://github.com/django-waffle/django-waffle).
## Summary
After reading this article you should now have a good idea of what you can do to identify your target audience/target browser list, and then effectively carry out cross-browser testing on that list.
Next, we'll turn our attention to the actual code issues your testing might uncover, starting with HTML and CSS.
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/Introduction","Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS", "Learn/Tools_and_testing/Cross_browser_testing")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing | data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing/your_own_automation_environment/index.md | ---
title: Setting up your own test automation environment
slug: Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenu("Learn/Tools_and_testing/Cross_browser_testing/Automated_testing", "Learn/Tools_and_testing/Cross_browser_testing")}}
In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial tools like the ones discussed in the previous article.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages; an idea
of the high-level
<a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction">principles of cross browser testing</a>, and
<a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing">automated testing</a>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To show how to set up a Selenium testing environment locally and run tests with it, and how to integrate it with tools like LambdaTest, Sauce Labs, and BrowserStack.
</td>
</tr>
</tbody>
</table>
## Selenium
[Selenium](https://www.selenium.dev/) is the most popular browser automation tool. There are other ways, but the best way to use Selenium is via WebDriver, a powerful API that builds on top of Selenium and makes calls to a browser to automate it, carrying out actions such as "open this web page", "move over this element on the page", "click this link", "see whether the link opens this URL", etc. This is ideal for running automated tests.
How you install and use WebDriver depends on what programming environment you want to use to write and run your tests. Most popular environments have available a package or framework that will install WebDriver and the bindings required to communicate with WebDriver using this language, for example, Java, C#, Ruby, Python, JavaScript (Node), etc. See [Setting Up a Selenium-WebDriver Project](https://www.selenium.dev/documentation/webdriver/getting_started/) for more details of Selenium setups for different languages.
Different browsers require different drivers to allow WebDriver to communicate with and control them. See [Platforms Supported by Selenium](https://www.selenium.dev/downloads/) for more information on where to get browser drivers from, etc.
We will cover writing and running Selenium tests using Node.js, as it is quick and easy to get started, and a more familiar environment for front end devs.
> **Note:** If you want to find out how to use WebDriver with other server-side environments, also check out [Platforms Supported by Selenium](https://www.selenium.dev/downloads/) for some useful links.
### Setting up Selenium in Node
1. To start with, set up a new npm project, as discussed in [Setting up Node and npm](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing#setting_up_node_and_npm) in the last chapter. Call it something different, like `selenium-test`.
2. Next, we need to install a framework to allow us to work with Selenium from inside Node. We are going to choose selenium's official [selenium-webdriver](https://www.npmjs.com/package/selenium-webdriver), as the documentation seems fairly up-to-date and it is well-maintained. If you want different options, [webdriver.io](https://webdriver.io/) and [nightwatch.js](https://nightwatchjs.org/) are also good choices. To install selenium-webdriver, run the following command, making sure you are inside your project folder:
```bash
npm install selenium-webdriver
```
> **Note:** It is still a good idea to follow these steps even if you previously installed selenium-webdriver and downloaded the browser drivers. You should make sure that everything is up-to-date.
Next, you need to download the relevant drivers to allow WebDriver to control the browsers you want to test. You can find details of where to get them from on the [selenium-webdriver](https://www.npmjs.com/package/selenium-webdriver) page (see the table in the first section.) Obviously, some of the browsers are OS-specific, but we're going to stick with Firefox and Chrome, as they are available across all the main OSes.
1. Download the latest [GeckoDriver](https://github.com/mozilla/geckodriver/releases/) (for Firefox) and [ChromeDriver](https://chromedriver.chromium.org/downloads) drivers.
2. Unpack them into somewhere fairly easy to navigate to, like the root of your home user directory.
3. Add the `chromedriver` and `geckodriver` driver's location to your system `PATH` variable. This should be an absolute path from the root of your hard disk, to the directory containing the drivers. For example, if we were using a macOS machine, our user name was bob, and we put our drivers in the root of our home folder, the path would be `/Users/bob`.
> **Note:** Just to reiterate, the path you add to `PATH` needs to be the path to the directory containing the drivers, not the paths to the drivers themselves! This is a common mistake.
To set your `PATH` variable on a macOS system and on most Linux systems:
1. If you're not already using the `bash` shell (for example, on macOS systems, the default is the `zsh` shell, not `bash`), switch to the `bash` shell:
```bash
exec bash
```
2. Open your `.bash_profile` (or `.bashrc`) file (if you can't see hidden files, you'll need to display them, see [Show/Hide hidden files in macOS](https://ianlunn.co.uk/articles/quickly-showhide-hidden-files-mac-os-x-mavericks/) or [Show hidden folders in Ubuntu](https://askubuntu.com/questions/470837/how-to-show-hidden-folders-in-file-manager-nautilus-on-ubuntu)).
3. Paste the following into the bottom of your file (updating the path as it actually is on your machine):
```bash
#Add WebDriver browser drivers to PATH
export PATH=$PATH:/Users/bob
```
4. Save and close this file, then restart your Terminal/command prompt to reapply your Bash configuration.
5. Check that your new paths are in the `PATH` variable by entering the following into your terminal:
```bash
echo $PATH
```
6. You should see it printed out in the terminal.
To set your `PATH` variable on Windows, follow the instructions at [How can I add a new folder to my system path?](https://www.itprotoday.com/)
OK, let's try a quick test to make sure everything is working.
1. Create a new file inside your project directory called `google_test.js`:
2. Give it the following contents, then save it:
```js
const { Builder, Browser, By, Key, until } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
try {
await driver.get("https://www.google.com/ncr");
await driver.findElement(By.name("q")).sendKeys("webdriver", Key.RETURN);
await driver.wait(until.titleIs("webdriver - Google Search"), 1000);
} finally {
await driver.sleep(2000); // Delay long enough to see search page!
await driver.quit();
}
})();
```
> **Note:** This function is an {{glossary("IIFE")}} (Immediately Invoked Function Expression).
3. In terminal, make sure you are inside your project folder, then enter the following command:
```bash
node google_test
```
You should see an instance of Firefox automatically open up! Google should automatically be loaded in a tab, "webdriver" should be entered in the search box, and the search button will be clicked. WebDriver will then wait for 1 second; the document title is then accessed, and if it is "webdriver - Google Search", we will return a message to claim the test is passed.
We then wait four seconds, after which WebDriver will then close down the Firefox instance and stop.
## Testing in multiple browsers at once
There is also nothing to stop you running the test on multiple browsers simultaneously. Let's try this!
1. Create another new file inside your project directory called `google_test_multiple.js`. You can feel free to change the references to some of the other browsers we added, remove them, etc., depending on what browsers you have available to test on your operating system. You'll need to make sure you have the right browser drivers set up on your system. In terms of what string to use inside the `.forBrowser()` method for other browsers, see the [Browser enum](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_Browser.html) reference page.
2. Give it the following contents, then save it:
```js
const { Builder, Browser, By, Key } = require("selenium-webdriver");
const driver_fx = new Builder().forBrowser(Browser.FIREFOX).build();
const driver_chr = new Builder().forBrowser(Browser.CHROME).build();
async function searchTest(driver) {
try {
await driver.get("http://www.google.com");
await driver.findElement(By.name("q")).sendKeys("webdriver", Key.RETURN);
await driver.sleep(2000).then(async () => {
await driver.getTitle().then(async (title) => {
if (title === "webdriver - Google Search") {
console.log("Test passed");
} else {
console.log("Test failed");
}
});
});
} finally {
driver.quit();
}
}
searchTest(driver_fx);
searchTest(driver_chr);
```
3. In terminal, make sure you are inside your project folder, then enter the following command:
```bash
node google_test_multiple
```
4. If you are using a Mac and do decide to test Safari, you might get an error message along the lines of "Could not create a session: You must enable the 'Allow Remote Automation' option in Safari's Develop menu to control Safari via WebDriver." If you get this, follow the given instruction and try again.
So here we've done the test as before, except that this time we've wrapped it inside a function, `searchTest()`. We've created new browser instances for multiple browsers, then passed each one to the function so the test is performed on all three browsers!
Fun huh? Let's move on, look at the basics of WebDriver syntax, in a bit more detail.
## WebDriver syntax crash course
Let's have a look at a few key features of the webdriver syntax. For more complete details, you should consult the [selenium-webdriver JavaScript API reference](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/) for a detailed reference and the Selenium main documentation's [Selenium WebDriver](https://www.selenium.dev/documentation/webdriver/), which contain multiple examples to learn from written in different languages.
### Starting a new test
To start up a new test, you need to include the `selenium-webdriver` module, importing the `Builder` constructor and `Browser` interface:
```js
const { Builder, Browser } = require("selenium-webdriver");
```
You use the `Builder()` constructor to create a new instance of a driver, chaining the `forBrowser()` method to specify what browser you want to test with this builder.
The `build()` method is chained at the end to actually build the driver instance (see the [Builder class reference](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_Builder.html) for detailed information on these features).
```js
let driver = new Builder().forBrowser(Browser.FIREFOX).build();
```
Note that it is possible to set specific configuration options for browsers to be tested, for example you can set a specific version and OS to test in the `forBrowser()` method:
```js
let driver = new Builder().forBrowser(Browser.FIREFOX, "46", "MAC").build();
```
You could also set these options using an environment variable, for example:
```bash
SELENIUM_BROWSER=firefox:46:MAC
```
Let's create a new test to allow us to explore this code as we talk about it. Inside your selenium test project directory, create a new file called `quick_test.js`, and add the following code to it:
```js
const { Builder, Browser } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
})();
```
### Getting the document you want to test
To load the page you actually want to test, you use the `get()` method of the driver instance you created earlier, for example:
```js
driver.get("http://www.google.com");
```
> **Note:** See the [WebDriver class reference](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebDriver.html) for details of the features in this section and the ones below it.
You can use any URL to point to your resource, including a `file://` URL to test a local document:
```js
driver.get(
"file:///Users/chrismills/git/learning-area/tools-testing/cross-browser-testing/accessibility/fake-div-buttons.html",
);
```
or
```js
driver.get("http://localhost:8888/fake-div-buttons.html");
```
But it is better to use a remote server location so the code is more flexible — when you start using a remote server to run your tests (see later on), your code will break if you try to use local paths.
Update your `example()` function as follows:
```js
const { Builder, Browser } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
})();
```
### Interacting with the document
Now we've got a document to test, we need to interact with it in some way, which usually involves first selecting a specific element to test something about. You can [select UI elements in many ways](https://www.selenium.dev/documentation/webdriver/elements/) in WebDriver, including by ID, class, element name, etc. The actual selection is done by the `findElement()` method, which accepts as a parameter a selection method. For example, to select an element by ID:
```js
const element = driver.findElement(By.id("myElementId"));
```
One of the most useful ways to find an element by CSS — the `By.css()` method allows you to select an element using a CSS selector.
Update your `example()` function now as follows:
```js
const { Builder, Browser, By } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
const button = driver.findElement(By.css("button:nth-of-type(1)"));
})();
```
### Testing your element
There are many ways to interact with your web documents and elements on them. You can see useful common examples starting at [Getting text values](https://www.selenium.dev/documentation/webdriver/elements/information/#text-content) on the WebDriver docs.
If we wanted to get the text inside our button, we could do this:
```js
button.getText().then((text) => {
console.log(`Button text is '${text}'`);
});
```
Add this to the bottom of the `example()` function now as shown below:
```js
const { Builder, Browser, By } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
const button = driver.findElement(By.css("button:nth-of-type(1)"));
button.getText().then((text) => {
console.log(`Button text is '${text}'`);
});
})();
```
Making sure you are inside your project directory, try running the test:
```bash
node quick_test.js
```
You should see the button's text label reported inside the console.
Let's do something a bit more useful. Replace the previous code entry with this line of code, `button.click();` as shown below:
```js
const { Builder, Browser, By } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
const button = driver.findElement(By.css("button:nth-of-type(1)"));
button.click();
})();
```
Try running your test again; the button will be clicked, and the `alert()` popup should appear. At least we know the button is working!
You can interact with the popup too. Update the `example()` function as follows, and try testing it again:
```js
const { Builder, Browser, By, until } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
const button = driver.findElement(By.css("button:nth-of-type(1)"));
button.click();
await driver.wait(until.alertIsPresent());
const alert = driver.switchTo().alert();
alert.getText().then((text) => {
console.log(`Alert text is '${text}'`);
});
alert.accept();
})();
```
Next, let's try entering some text into one of the form elements. Update the `example()` function as follows and try running your test again:
```js
const { Builder, Browser, By, until } = require("selenium-webdriver");
(async function example() {
const driver = await new Builder().forBrowser(Browser.FIREFOX).build();
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
const input = driver.findElement(By.id("name"));
input.sendKeys("Filling in my form");
const button = driver.findElement(By.css("button:nth-of-type(1)"));
button.click();
await driver.wait(until.alertIsPresent());
const alert = driver.switchTo().alert();
alert.getText().then((text) => {
console.log(`Alert text is '${text}'`);
});
alert.accept();
})();
```
You can submit key presses that can't be represented by normal characters using properties of the `Key` object. For example, above we used this construct to tab out of the form input before submitting it:
```js
driver.sleep(1000).then(() => {
driver.findElement(By.name("q")).sendKeys(Key.TAB);
});
```
### Waiting for something to complete
There are times where you'll want to make WebDriver wait for something to complete before carrying on. For example if you load a new page, you'll want to wait for the page's DOM to finish loading before you try to interact with any of its elements, otherwise the test will likely fail.
In our `google_test.js` test for example, we included this block:
```js
driver.sleep(2000).then(() => {
driver.getTitle().then((title) => {
if (title === "webdriver - Google Search") {
console.log("Test passed");
} else {
console.log("Test failed");
}
});
});
```
The `sleep()` method accepts a value that specifies the time to wait in milliseconds — the method returns a promise that resolves at the end of that time, at which point the code inside the `then()` executes. In this case we get the title of the current page with the `getTitle()` method, then return a pass or fail message depending on what its value is.
We could add a `sleep()` method to our `quick_test.js` test too — try updating your `example()` function like this:
```js
const { Builder, Browser, By, until } = require("selenium-webdriver");
const driver = new Builder().forBrowser("firefox").build();
(async function example() {
try {
driver.get(
"https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html",
);
driver.sleep(2000).then(() => {
const input = driver.findElement(By.id("name"));
input.sendKeys("Filling in my form");
input.getAttribute("value").then((value) => {
if (value !== "") {
console.log("Form input editable");
}
});
});
const button = driver.findElement(By.css("button:nth-of-type(1)"));
button.click();
await driver.wait(until.alertIsPresent());
const alert = driver.switchTo().alert();
alert.getText().then((text) => {
console.log(`Alert text is '${text}'`);
});
alert.accept();
} finally {
await driver.sleep(4000); // Delay long enough to see search page!
driver.quit();
}
})();
```
WebDriver will now wait for 2 seconds before filling in the form field. We then test whether its value got filled in (i.e. is not empty) by using `getAttribute()` to retrieve it's `value` attribute value, and print a message to the console if it is not empty.
> **Note:** There is also a method called [`wait()`](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebDriver.html#wait), which repeatedly tests a condition for a certain length of time, and then carries on executing the code. This also makes use of the [util library](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/until.html), which defines common conditions to use along with `wait()`.
### Shutting down drivers after use
After you've finished running a test, you should shut down any driver instances you've opened, to make sure that you don't end up with loads of rogue browser instances open on your machine! This is done using the `quit()` method. Call this on your driver instance when you are finished with it. Add this line to the bottom of your `quick_test.js` test now:
```js
driver.quit();
```
When you run it, you should now see the test execute and the browser instance shut down again after the test is complete. This is useful for not cluttering up your computer with loads of browser instances, especially if you have so many that it is causing the computer to slow down.
## Test best practices
There has been a lot written about best practices for writing tests. You can find some good background information at [Test Practices](https://www.selenium.dev/documentation/test_practices/). In general, you should make sure that your tests are:
1. Using good locator strategies: When you are [Interacting with the document](#interacting_with_the_document), make sure that you use locators and page objects that are unlikely to change — if you have a testable element that you want to perform a test on, make sure that it has a stable ID, or position on the page that can be selected using a CSS selector, which isn't going to just change with the next site iteration. You want to make your tests as non-brittle as possible, i.e. they won't just break when something changes.
2. Write atomic tests: Each test should test one thing only, making it easy to keep track of what test file is testing which criterion. As an example, the `google_test.js` test we looked at above is pretty good, as it just tests a single thing — whether the title of a search results page is set correctly. We could work on giving it a better name so it is easier to work out what it does if we add more google tests. Perhaps `results_page_title_set_correctly.js` would be slightly better?
3. Write autonomous tests: Each test should work on it's own, and not depend on other tests to work.
In addition, we should mention test results/reporting — we've been reporting results in our above examples using simple `console.log()` statements, but this is all done in JavaScript, so you can use whatever test running and reporting system you want, be it [Mocha](https://mochajs.org/), [Chai](https://www.chaijs.com/), or some other tool.
1. For example, try making a local copy of our [`mocha_test.js`](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/selenium/mocha_test.js) example inside your project directory. Put it inside a subfolder called `test`. This example uses a long chain of promises to run all the steps required in our test — the promise-based methods WebDriver uses need to resolve for it to work properly.
2. Install the mocha test harness by running the following command inside your project directory:
```bash
npm install --save-dev mocha
```
3. You can now run the test (and any others you put inside your `test` directory) using the following command:
```bash
npx mocha --no-timeouts
```
4. You should include the `--no-timeouts` flag to make sure your tests don't end up failing because of Mocha's arbitrary timeout (which is 3 seconds).
> **Note:** [saucelabs-sample-test-frameworks](https://github.com/saucelabs-sample-test-frameworks) contains several useful examples showing how to set up different combinations of test/assertion tools.
## Running remote tests
It turns out that running tests on remote servers isn't that much more difficult than running them locally. You just need to create your driver instance, but with a few more features specified, including the capabilities of the browser you want to test on, the address of the server, and the user credentials you need (if any) to access it.
### LambdaTest
Getting Selenium tests to run remotely on LambdaTest is very simple. The code you need should follow the pattern seen below.
Let's write an example:
1. Inside your project directory, create a new file called `lambdatest_google_test.js`
2. Give it the following contents:
```js
const { By, Builder } = require("selenium-webdriver");
// username: Username can be found at automation dashboard
const USERNAME = "{username}";
// AccessKey: AccessKey can be generated from automation dashboard or profile section
const KEY = "{accessKey}";
// gridUrl: gridUrl can be found at automation dashboard
const GRID_HOST = "hub.lambdatest.com/wd/hub";
function searchTextOnGoogle() {
// Setup Input capabilities
const capabilities = {
platform: "windows 10",
browserName: "chrome",
version: "67.0",
resolution: "1280x800",
network: true,
visual: true,
console: true,
video: true,
name: "Test 1", // name of the test
build: "NodeJS build", // name of the build
};
// URL: https://{username}:{accessToken}@hub.lambdatest.com/wd/hub
const gridUrl = `https://${USERNAME}:${KEY}@${GRID_HOST}`;
// setup and build selenium driver object
const driver = new Builder()
.usingServer(gridUrl)
.withCapabilities(capabilities)
.build();
// navigate to a URL, search for a text and get title of page
driver.get("https://www.google.com/ncr").then(function () {
driver
.findElement(By.name("q"))
.sendKeys("LambdaTest\n")
.then(function () {
driver.getTitle().then((title) => {
setTimeout(() => {
if (title === "LambdaTest - Google Search") {
driver.executeScript("lambda-status=passed");
} else {
driver.executeScript("lambda-status=failed");
}
driver.quit();
}, 5000);
});
});
});
}
searchTextOnGoogle();
```
3. Visit your [LambdaTest automation dashboard](https://www.lambdatest.com/selenium-automation), to fetch your LambdaTest's username and access key by clicking on the **key** icon on the top-right(see _Username and Access Keys_). Replace the `{username}` and `{accessKey}` placeholders in the code with your actual user name and access key values (and make sure you keep them secure).
4. Run the below command in your terminal to execute your test:
```bash
node lambdatest_google_test
```
The test will be sent to LambdaTest, and the output of your test will be reflected on your LambdaTest console.
If you wish to extract these results for reporting purpose from LambdaTest platform then you can do so by using [LambdaTest restful API](https://www.lambdatest.com/blog/lambdatest-launches-api-for-selenium-automation/).
5. Now if you go to your [LambdaTest Automation dashboard](https://accounts.lambdatest.com/dashboard), you'll see your test listed; from here you'll be able to see videos, screenshots, and other such data.
You will also see a status of **passed** or **failed** instead of **completed**, because of the `if` or `else` blocks of code.
[](https://www.lambdatest.com/blog/wp-content/uploads/2019/02/Automation-logs-1.jpg)
You can retrieve network, command, exception, and Selenium logs for every test within your test build. You will also find a video recording of your Selenium script execution.
> **Note:** The _HELP_ button on LambdaTest Automation Dashboard will provide you with an ample amount of information to help you get started with LambdaTest automation. You can also follow our documentation about [running first Selenium script in Node JS](https://www.lambdatest.com/support/docs/quick-guide-to-run-node-js-tests-on-lambdatest-selenium-grid/).
> **Note:** If you don't want to write out the capabilities objects for your tests by hand, you can generate them using the [Selenium Desired Capabilities Generator](https://www.lambdatest.com/capabilities-generator/).
### BrowserStack
Getting Selenium tests to run remotely on BrowserStack is easy. The code you need should follow the pattern seen below.
Let's write an example:
1. Inside your project directory, create a new file called `bstack_google_test.js`.
2. Give it the following contents:
```js
const { Builder, By, Key } = require("selenium-webdriver");
const request = require("request");
// Input capabilities
const capabilities = {
"bstack:options": {
os: "OS X",
osVersion: "Sonoma",
browserVersion: "17.0",
local: "false",
seleniumVersion: "3.14.0",
userName: "YOUR-USER-NAME",
accessKey: "YOUR-ACCESS-KEY",
},
browserName: "Safari",
};
const driver = new Builder()
.usingServer("http://hub-cloud.browserstack.com/wd/hub")
.withCapabilities(capabilities)
.build();
(async function bStackGoogleTest() {
try {
await driver.get("https://www.google.com/");
await driver.findElement(By.name("q")).sendKeys("webdriver", Key.RETURN);
await driver.sleep(2000);
const title = await driver.getTitle();
if (title === "webdriver - Google Search") {
console.log("Test passed");
} else {
console.log("Test failed");
}
} finally {
await driver.sleep(4000); // Delay long enough to see search page!
await driver.quit();
}
})();
```
3. From your [BrowserStack Account - Summary](https://www.browserstack.com/accounts/profile/details), get your user name and access key (see _Username and Access Keys_). Replace the `YOUR-USER-NAME` and `YOUR-ACCESS-KEY` placeholders in the code with your actual user name and access key values (and make sure you keep them secure).
4. Run your test with the following command:
```bash
node bstack_google_test
```
The test will be sent to BrowserStack, and the test result will be returned to your console. This shows the importance of including some kind of result reporting mechanism!
5. Now if you go back to the [BrowserStack automation dashboard](https://www.browserstack.com/automate) page, you'll see your test listed:

If you click on the link for your test, you'll get to a new screen where you will be able to see a video recording of the test, and multiple detailed logs of information pertaining to it.
> **Note:** The _Resources_ menu option on the Browserstack automation dashboard contains a wealth of useful information on using it to run automated tests. See [Node JS Documentation for writing automate test scripts in Node JS](https://www.browserstack.com/docs/automate/selenium/getting-started/nodejs) for the node-specific information. Explore the docs to find out all the useful things BrowserStack can do.
> **Note:** If you don't want to write out the capabilities objects for your tests by hand, you can generate them using the generators embedded in the docs. See [Run your first test](https://www.browserstack.com/docs/automate/selenium/getting-started/nodejs#run-your-first-test).
#### Filling in BrowserStack test details programmatically
You can use the BrowserStack REST API and some other capabilities to annotate your test with more details, such as whether it passed, why it passed, what project the test is part of, etc. BrowserStack doesn't know these details by default!
Let's update our `bstack_google_test.js` demo, to show how these features work:
1. Install the request module by running the following command inside your project directory:
```js
npm install request
```
2. Then, we'll need to import the node request module, so we can use it to send requests to the REST API. Add the following line at the very top of your code:
```js
const request = require("request");
```
3. Now we'll update our `capabilities` object to include a project name — add the following line before the closing curly brace, remembering to add a comma at the end of the previous line (you can vary the build and project names to organize the tests in different windows in the BrowserStack automation dashboard):
```js
'project' : 'Google test 2'
```
4. Next we need to access the `sessionId` of the current session, so we know where to send the request (the ID is included in the request URL, as you'll see later). Include the following lines just below the block that creates the `driver` object (`let driver …`) :
```js
let sessionId;
driver.session_.then((sessionData) => {
sessionId = sessionData.id_;
});
```
5. Finally, update the `driver.sleep(2000)` block near the bottom of the code to add REST API calls (again, replace the `YOUR-USER-NAME` and `YOUR-ACCESS-KEY` placeholders in the code with your actual user name and access key values):
```js
driver.sleep(2000).then(() => {
driver.getTitle().then((title) => {
if (title === "webdriver - Google Search") {
console.log("Test passed");
request({
uri: `https://YOUR-USER-NAME:[email protected]/automate/sessions/${sessionId}.json`,
method: "PUT",
form: {
status: "passed",
reason: "Google results showed correct title",
},
});
} else {
console.log("Test failed");
request({
uri: `https://YOUR-USER-NAME:[email protected]/automate/sessions/${sessionId}.json`,
method: "PUT",
form: {
status: "failed",
reason: "Google results showed wrong title",
},
});
}
});
});
```
These are fairly intuitive — once the test completes, we send an API call to BrowserStack to update the test with a passed or failed status, and a reason for the result.
If you now go back to your [BrowserStack automation dashboard](https://live.browserstack.com/dashboard) page, you should see your test session available, as before, but with the updated data attached to it:

### Sauce Labs
Getting Selenium tests to run remotely on Sauce Labs is also very simple, and very similar to BrowserStack albeit with a few syntactic differences. The code you need should follow the pattern seen below.
Let's write an example:
1. Inside your project directory, create a new file called `sauce_google_test.js`.
2. Give it the following contents:
```js
const { Builder, By, Key } = require("selenium-webdriver");
const username = "YOUR-USER-NAME";
const accessKey = "YOUR-ACCESS-KEY";
const driver = new Builder()
.withCapabilities({
browserName: "chrome",
platform: "Windows XP",
version: "43.0",
username,
accessKey,
})
.usingServer(
`https://${username}:${accessKey}@ondemand.saucelabs.com:443/wd/hub`,
)
.build();
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("webdriver");
driver.sleep(1000).then(() => {
driver.findElement(By.name("q")).sendKeys(Key.TAB);
});
driver.findElement(By.name("btnK")).click();
driver.sleep(2000).then(() => {
driver.getTitle().then((title) => {
if (title === "webdriver - Google Search") {
console.log("Test passed");
} else {
console.log("Test failed");
}
});
});
driver.quit();
```
3. From your [Sauce Labs user settings](https://app.saucelabs.com/user-settings), get your user name and access key. Replace the `YOUR-USER-NAME` and `YOUR-ACCESS-KEY` placeholders in the code with your actual user name and access key values (and make sure you keep them secure).
4. Run your test with the following command:
```bash
node sauce_google_test
```
The test will be sent to Sauce Labs, and the test result will be returned to your console. This shows the importance of including some kind of result reporting mechanism!
5. Now if you go to your [Sauce Labs Automated Test dashboard](https://app.saucelabs.com/dashboard/tests) page, you'll see your test listed; from here you'll be able to see videos, screenshots, and other such data.

> **Note:** Sauce Labs' [Platform Configurator](https://saucelabs.com/platform/platform-configurator#/) is a useful tool for generating capability objects to feed to your driver instances, based on what browser/OS you want to test on.
> **Note:** for more useful details on testing with Sauce Labs and Selenium, check out [Getting Started with Selenium for Automated Website Testing](https://docs.saucelabs.com/web-apps/automated-testing/selenium/), and [Instant Selenium Node.js Tests](https://docs.saucelabs.com/web-apps/automated-testing/selenium/sample-scripts/#nodejs).
#### Filling in Sauce Labs test details programmatically
You can use the Sauce Labs API to annotate your test with more details, such as whether it passed, the name of the test, etc. Sauce Labs doesn't know these details by default!
To do this, you need to:
1. Install the Node Sauce Labs wrapper using the following command (if you've not already done it for this project):
```bash
npm install saucelabs --save-dev
```
2. Require saucelabs — put this at the top of your `sauce_google_test.js` file, just below the previous variable declarations:
```js
const SauceLabs = require("saucelabs");
```
3. Create a new instance of SauceLabs, by adding the following just below that:
```js
const saucelabs = new SauceLabs({
username: "YOUR-USER-NAME",
password: "YOUR-ACCESS-KEY",
});
```
Again, replace the `YOUR-USER-NAME` and `YOUR-ACCESS-KEY` placeholders in the code with your actual user name and access key values (note that the saucelabs npm package rather confusingly uses `password`, not `accessKey`). Since you are using these twice now, you may want to create a couple of helper variables to store them in.
4. Below the block where you define the `driver` variable (just below the `build()` line), add the following block — this gets the correct driver `sessionID` that we need to write data to the job (you can see it action in the next code block):
```js
driver.getSession().then((sessionid) => {
driver.sessionID = sessionid.id_;
});
```
5. Finally, replace the `driver.sleep(2000)` block near the bottom of the code with the following:
```js
driver.sleep(2000).then(() => {
driver.getTitle().then((title) => {
let testPassed = false;
if (title === "webdriver - Google Search") {
console.log("Test passed");
testPassed = true;
} else {
console.error("Test failed");
}
saucelabs.updateJob(driver.sessionID, {
name: "Google search results page title test",
passed: testPassed,
});
});
});
```
Here we've set a `testPassed` variable to `true` or `false` depending on whether the test passed or fails, then we've used the `saucelabs.updateJob()` method to update the details.
If you now go back to your [Sauce Labs Automated Test dashboard](https://app.saucelabs.com/dashboard/tests) page, you should see your new job now has the updated data attached to it:

### Your own remote server
If you don't want to use a service like Sauce Labs or BrowserStack, you can always set up your own remote testing server. Let's look at how to do this.
1. The Selenium remote server requires Java to run. Download the latest JDK for your platform from the [Java SE downloads page](https://www.oracle.com/java/technologies/downloads/). Install it when it is downloaded.
2. Next, download the latest [Selenium standalone server](https://selenium-release.storage.googleapis.com/index.html) — this acts as a proxy between your script and the browser drivers. Choose the latest stable version number (i.e. not a beta), and from the list choose a file starting with "selenium-server-standalone". When this has downloaded, put it in a sensible place, like in your home directory. If you've not already added the location to your `PATH`, do so now (see the [Setting up Selenium in Node](#setting_up_selenium_in_node) section).
3. Run the standalone server by entering the following into a terminal on your server computer
```bash
java -jar selenium-server-standalone-3.0.0.jar
```
(update the `.jar` filename) so it matches exactly what file you've got.
4. The server will run on `http://localhost:4444/wd/hub` — try going there now to see what you get.
Now we've got the server running, let's create a demo test that will run on the remote selenium server.
1. Create a copy of your `google_test.js` file, and call it `google_test_remote.js`; put it in your project directory.
2. Update the line of code (which starts with `const driver = …`) like so
```js
const driver = new Builder()
.forBrowser(Browser.FIREFOX)
.usingServer("http://localhost:4444/wd/hub")
.build();
```
3. Run your test, and you should see it run as expected; this time however you will be running it on the standalone server:
```bash
node google_test_remote.js
```
So this is pretty cool. We have tested this locally, but you could set this up on just about any server along with the relevant browser drivers, and then connect your scripts to it using the URL you choose to expose it at.
## Integrating Selenium with CI tools
As another point, it is also possible to integrate Selenium and related tools like LambdaTest, and Sauce Labs with continuous integration (CI) tools — this is useful, as it means you can run your tests via a CI tool, and only commit new changes to your code repository if the tests pass.
It is out of scope to look at this area in detail in this article, but we'd suggest getting started with Travis CI — this is probably the easiest CI tool to get started with and has good integration with web tools like GitHub and Node.
To get started, see for example:
- [Travis CI for complete beginners](https://docs.travis-ci.com/user/for-beginners)
- [Building a Node.js project](https://docs.travis-ci.com/user/languages/javascript-with-nodejs/) (with Travis)
- [Using LambdaTest with Travis CI](https://www.lambdatest.com/support/docs/travis-ci-with-lambdatest/)
- [Using LambdaTest with CircleCI](https://www.lambdatest.com/support/docs/circleci-integration-with-lambdatest/)
- [Using LambdaTest with Jenkins](https://www.lambdatest.com/support/docs/jenkins-with-lambdatest/)
- [Using Sauce Labs with Travis CI](https://docs.travis-ci.com/user/sauce-connect/)
> **Note:** If you wish to perform continuous testing with **codeless automation** then you can use [Endtest](https://endtest.io) or [TestingBot](https://testingbot.com).
## Summary
This module should have proven fun, and should have given you enough of an insight into writing and running automated tests for you to get going with writing your own automated tests.
{{PreviousMenu("Learn/Tools_and_testing/Cross_browser_testing/Automated_testing", "Learn/Tools_and_testing/Cross_browser_testing")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing | data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing/automated_testing/index.md | ---
title: Introduction to automated testing
slug: Learn/Tools_and_testing/Cross_browser_testing/Automated_testing
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment", "Learn/Tools_and_testing/Cross_browser_testing")}}
Manually running tests on several browsers and devices, several times per day, can get tedious, and time-consuming. To handle this efficiently, you should become familiar with automation tools. In this article, we look at what is available, how to use task runners, and how to use the basics of commercial browser test automation apps such as LambdaTest, Sauce Labs, BrowserStack, and TestingBot.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>, <a href="/en-US/docs/Learn/CSS">CSS</a>, and <a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages;
an idea of the high level <a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction">principles of cross-browser testing</a>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To provide an understanding of what automated testing entails, how it can make your life easier, and how to make use of some of the commercial products that make things easier.
</td>
</tr>
</tbody>
</table>
## Automation makes things easy
Throughout this module we have detailed loads of different ways in which you can test your websites and apps, and explained the sort of scope your cross-browser testing efforts should have in terms of what browsers to test, accessibility considerations, and more. Sounds like a lot of work, doesn't it?
We agree — testing all the things we've looked at in previous articles manually can be a real pain. Fortunately, there are tools to help us automate some of this pain away. There are two main ways in which we can automate the tests we've been talking about in this module:
1. Use a task runner such as [Grunt](https://gruntjs.com/) or [Gulp](https://gulpjs.com/), or [npm scripts](https://docs.npmjs.com/misc/scripts/) to run tests and clean up code during your build process. This is a great way to perform tasks like linting and minifying code, adding in CSS prefixes or transpiling nascent JavaScript features for maximum cross-browser reach, and so on.
2. Use a browser automation system like [Selenium](https://www.selenium.dev/) to run specific tests on installed browsers and return results, alerting you to failures in browsers as they crop up. Commercial cross-browser testing apps like [Sauce Labs](https://saucelabs.com/) and [BrowserStack](https://www.browserstack.com/) are based on Selenium, but allow you to access their set up remotely using a simple interface, saving you the hassle of setting up your own testing system.
We will look at how to set up your own Selenium-based testing system in the next article. In this article, we'll look at how to set up a task runner, and use the basic functionality of commercial systems like the ones mentioned above.
> **Note:** the above two categories are not mutually exclusive. It is possible to set up a task runner to access a service like Sauce Labs, or LambdaTest via an API, run cross browser tests, and return results. We will look at this below as well.
## Using a task runner to automate testing tools
As we said above, you can drastically speed up common tasks such as linting and minifying code by using a task runner to run everything you need to run automatically at a certain point in your build process. For example, this could be every time you save a file, or at some other point. Inside this section we'll look at how to automate task running with Node and Gulp, a beginner-friendly option.
### Setting up Node and npm
Most tools these days are based on {{Glossary("Node.js")}}, so you'll need to install it from [nodejs.org](https://nodejs.org/):
1. Download the installer for your system from the above site. (If you already have Node and npm installed, jump to point 4)
2. Install it like you would any other program. Note that Node comes with [Node Package Manager](https://www.npmjs.com/) (npm), which allows you to easily install packages, share your own packages with others, and run useful scripts on your projects.
3. Once the install completes, test that node is installed by typing the following into the terminal, which returns the installed versions of Node and npm:
```bash
node -v
npm -v
```
4. If you've got Node/npm already installed, you should update them to their latest versions. To update Node, the most reliable way is to download and install an updated installer package from their website (see link above). To update npm, use the following command in your terminal:
```bash
npm install npm@latest -g
```
> **Note:** If the above command fails with permissions errors, [Fixing npm permissions](https://docs.npmjs.com/getting-started/fixing-npm-permissions/) should sort you out.
To start using Node/npm-based packages on your projects, you need to set up your project directories as npm projects. This is easy to do.
For example, let's first create a test directory to allow us to play without fear of breaking anything.
1. Create a new directory somewhere sensible using your file manager UI, or, on a command line, by navigating to the location you want and running the following command:
```bash
mkdir node-test
```
2. To make this directory an npm project, you just need to go inside your test directory and initialize it, with the following:
```bash
cd node-test
npm init
```
3. This second command will ask you many questions to find out the information required to set up the project; you can just select the defaults for now.
4. Once all the questions have been asked, it will ask you if the information entered is OK. Type `yes` and press Enter/Return and npm will generate a `package.json` file in your directory.
This file is basically a config file for the project. You can customize it later, but for now it'll look something like this:
```json
{
"name": "node-test",
"version": "1.0.0",
"description": "Test for npm projects",
"main": "index.js",
"scripts": {
"test": "test"
},
"author": "Chris Mills",
"license": "MIT"
}
```
With this, you are ready to move on.
### Setting up Gulp automation
Let's look at setting up Gulp and using it to automate some testing tools.
1. To begin with, create a test npm project using the procedure detailed at the bottom of the previous section.
Also, update the `package.json` file with the line: `"type": "module"` so that it'll look something like this:
```json
{
"name": "node-test",
"version": "1.0.0",
"description": "Test for npm projects",
"main": "index.js",
"scripts": {
"test": "test"
},
"author": "Chris Mills",
"license": "MIT",
"type": "module"
}
```
2. Next, you'll need some sample HTML, CSS and JavaScript content to test your system on — make copies of our sample [index.html](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/automation/index.html), [main.js](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/automation/main.js), and [style.css](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/automation/style.css) files in a subfolder with the name `src` inside your project folder.
You can try your own test content if you like, but bear in mind that such tools won't work on internal JS/CSS — you need external files.
3. First, install gulp globally (meaning, it will be available across all projects) using the following command:
```bash
npm install --global gulp-cli
```
4. Next, run the following command inside your npm project directory root to set up gulp as a dependency of your project:
```bash
npm install --save-dev gulp
```
5. Now create a new file inside your project directory called `gulpfile.mjs`. This is the file that will run all our tasks. Inside this file, put the following:
```js
import gulp from "gulp";
export default function (cb) {
console.log("Gulp running");
cb();
}
```
This requires the `gulp` module we installed earlier, and then exports a default task that does nothing except for printing a message to the terminal — this is useful for letting us know that Gulp is working. Each gulp task is exported in the same basic format — `exports.taskName = taskFunction`. Each function takes one parameter — a callback to run when the task is completed.
6. You can run your gulp's default task with the following command — try this now:
```bash
gulp
```
### Adding some real tasks to Gulp
To add some real tasks to Gulp, we need to think about what we want to do. A reasonable set of basic functionalities to run on our project is as follows:
- html-tidy, css-lint, and js-hint to lint and report/fix common HTML/CSS/JS errors (see [gulp-htmltidy](https://www.npmjs.com/package/gulp-htmltidy), [gulp-csslint](https://www.npmjs.com/package/gulp-csslint), [gulp-jshint](https://www.npmjs.com/package/gulp-jshint)).
- Autoprefixer to scan our CSS and add vendor prefixes only where needed (see [gulp-autoprefixer](https://www.npmjs.com/package/gulp-autoprefixer)).
- babel to transpile any new JavaScript syntax features to traditional syntax that works in older browsers (see [gulp-babel](https://www.npmjs.com/package/gulp-babel)).
See the links above for full instructions on the different gulp packages we are using.
To use each plugin, you need to first install it via npm, then require any dependencies at the top of the `gulpfile.js` file, then add your test(s) to the bottom of it, and finally export the name of your task to be available via gulp's command.
#### html-tidy
1. Install using the following line:
```bash
npm install --save-dev gulp-htmltidy
```
> **Note:** `--save-dev` adds the package as a dependency to your project. If you look in your project's `package.json` file, you'll see an entry for it in the `devDependencies` property.
2. Add the following dependency to `gulpfile.js`:
```js
import htmltidy from "gulp-htmltidy";
```
3. Add the following test to the bottom of `gulpfile.js`:
```js
export function html() {
return gulp
.src("src/index.html")
.pipe(htmltidy())
.pipe(gulp.dest("build"));
}
```
4. Change the default export to:
```js
export default html;
```
Here we are grabbing our development `index.html` file with `gulp.src()`, which allows us to grab a source file to do something with.
We next use the `pipe()` function to pass that source to another command to do something else with. We can chain as many of these together as we want. We first run `htmltidy()` on the source, which goes through and fixes errors in our file. The second `pipe()` function writes the output HTML file to the `build` directory.
In the input version of the file, you may have noticed that we put an empty {{htmlelement("p")}} element; htmltidy has removed this by the time the output file has been created.
#### Autoprefixer and css-lint
1. Install using the following lines:
```bash
npm install --save-dev gulp-autoprefixer
npm install --save-dev gulp-csslint
```
2. Add the following dependencies to `gulpfile.js`:
```js
import autoprefixer from "gulp-autoprefixer";
import csslint from "gulp-csslint";
```
3. Add the following test to the bottom of `gulpfile.js`:
```js
export function css() {
return gulp
.src("src/style.css")
.pipe(csslint())
.pipe(csslint.formatter("compact"))
.pipe(
autoprefixer({
cascade: false,
}),
)
.pipe(gulp.dest("build"));
}
```
4. Add the following property to `package.json`:
```json
"browserslist": [
"last 5 versions"
]
```
5. Change the default task to:
```js
export default gulp.series(html, css);
```
Here we grab our `style.css` file, run csslint on it (which outputs a list of any errors in your CSS to the terminal), then runs it through autoprefixer to add any prefixes needed to make nascent CSS features run in older browsers. At the end of the pipe chain, we output our modified prefixed CSS to the `build` directory. Note that this only works if csslint doesn't find any errors — try removing a curly brace from your CSS file and re-running gulp to see what output you get!
#### js-hint and babel
1. Install using the following lines:
```bash
npm install --save-dev gulp-babel @babel/preset-env
npm install --save-dev @babel/core
npm install jshint gulp-jshint --save-dev
```
2. Add the following dependencies to `gulpfile.js`:
```js
import babel from "gulp-babel";
import jshint from "gulp-jshint";
```
3. Add the following test to the bottom of `gulpfile.js`:
```js
export function js() {
return gulp
.src("src/main.js")
.pipe(jshint())
.pipe(jshint.reporter("default"))
.pipe(
babel({
presets: ["@babel/env"],
}),
)
.pipe(gulp.dest("build"));
}
```
4. Change the default task to:
```js
export default gulp.series(html, css, js);
```
Here we grab our `main.js` file, run `jshint` on it and output the results to the terminal using `jshint.reporter`; we then pass the file to babel, which converts it to old style syntax and outputs the result into the `build` directory. Our original code included a [fat arrow function](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), which babel has modified into an old style function.
#### Further ideas
Once this is all set up, you can run the `gulp` command inside your project directory, and you should get an output like this:

You can then try out the files output by your automated tasks by looking at them inside the `build` directory, and loading `build/index.html` in your web browser.
If you get errors, check that you've added all the dependencies and the tests as shown above; also try commenting out the HTML/CSS/JavaScript code sections and then rerunning gulp to see if you can isolate what the problem is.
Gulp comes with a `watch()` function that you can use to watch your files and run tests whenever you save a file. For example, try adding the following to the bottom of your `gulpfile.js`:
```js
export function watch() {
gulp.watch("src/*.html", html);
gulp.watch("src/*.css", css);
gulp.watch("src/*.js", js);
}
```
Now try entering the `gulp watch` command into your terminal. Gulp will now watch your directory, and run the appropriate tasks whenever you save a change to an HTML, CSS, or JavaScript file.
> **Note:** The `*` character is a wildcard character — here we're saying "run these tasks when any files of these types are saved. You could also use wildcards in your main tasks, for example `gulp.src('src/*.css')` would grab all your CSS files and then run piped tasks on them.
There's a lot more you can do with Gulp. The [Gulp plugin directory](https://gulpjs.com/plugins/) has literally thousands of plugins to search through.
### Other task runners
There are many other task runners available. We certainly aren't trying to say that Gulp is the best solution out there, but it works for us and it is fairly accessible to beginners. You could also try using other solutions:
- Grunt works in a very similar way to Gulp, except that it relies on tasks specified in a config file, rather than using written JavaScript. See [Getting started with Grunt for more details.](https://gruntjs.com/getting-started)
- You can also run tasks directly using npm scripts located inside your `package.json` file, without needing to install any kind of extra task runner system. This works on the premise that things like Gulp plugins are basically wrappers around command line tools. So, if you can work out how to run the tools using the command line, you can then run them using npm scripts. It is a bit trickier to work with, but can be rewarding for those who are strong with their command line skills. [Why npm scripts?](https://css-tricks.com/why-npm-scripts/) provides a good introduction with a good deal of further information.
## Using commercial testing services to speed up browser testing
Now let's look at commercial third-party browser testing services and what they can do for us.
The basic premise with such applications is that the company that runs each one has a huge server farm that can run many different tests. When you use this service, you provide a URL of the page you want to test along with information, such as what browsers you want it tested in. The app then configures a new VM with the OS and browser you specified, and returns the test results in the form of screenshots, videos, log files, text, etc.
You can then step up a gear, using an API to access functionality programmatically, which means that such apps can be combined with task runners, such as your own local Selenium environments and others, to create automated tests.
> **Note:** There are other commercial browser testing systems available but in this article, we'll focus on LambdaTest, Sauce Labs, and BrowserStack. We're not saying that these are necessarily the best tools available, but they are good ones that are simple for beginners to get up and running with.
### LambdaTest
#### Getting started with LambdaTest
1. Let's get started by [signing up on LambdaTest](https://accounts.lambdatest.com/register) for free.
2. Sign in. This should happen automatically after you verify your email address.
> **Note:** Unlike other cloud-based cross browser testing service providers, LambdaTest offers a freemium account where you get lifetime access to their platform. The only difference between their premium and their freemium plan is on the amount of consumption. For automation testing through their Selenium Grid, LambdaTest offers 60 minutes per month of free testing.
#### The basics: Manual tests
Once you sign in to LambdaTest, you will be routed to the LambdaTest Dashboard. The dashboard will provide you details related to how many minutes you have consumed, how many concurrent sessions are running, your total number of tests to date, and more.
1. To start off with manual testing you need to select the **"Real Time Testing"** tab from the left navigation menu.

2. As you click on the **Real Time Testing** you will be directed to a screen where you can choose the browser configuration, browser version, OS, and screen resolution with which you want to test your website.

3. As you click on the Start button, a loading screen will appear, providing you with a VM (Virtual Machine) based on your configurations. Once loaded, you can perform live, interactive cross-browser testing with a website.
[](https://web.archive.org/web/20210608014707if_/https://www.lambdatest.com/support/docs/wp-content/uploads/2019/03/mark-as-bug-2.png)
If you notice an issue with the UI, then you can share it with your colleagues by capturing a screenshot of your VM with the screenshot button. You can also record a video of your test session by hitting the recorder button in your test session.
4. With the in-built image editor, highlight your screenshot before you push it to your colleagues.
5. Using the mark as bug button you can push bugs to numerous third-party tools such as Jira, Asana, Trello, and more. That way you can log a bug directly from your test session on LambdaTest to your project management instance. Check out all the [third-party LambdaTest integrations](https://www.lambdatest.com/integrations).
> **Note:** All the videos and images captured inside a test session are captured inside the gallery, test logs, and issue tracker at LambdaTest.
### Sauce Labs
#### Getting started with Sauce Labs
Let's get started with a Sauce Labs Trial.
1. Create a Sauce Labs trial account.
2. Sign in. This should happen automatically after you verify your email address.
#### The basics: Manual tests
The [Sauce Labs dashboard](https://app.saucelabs.com/dashboard/manual) has a lot of options available on it. For now, make sure you are on the _Manual Tests_ tab.
1. Click _Start a new manual session_.
2. In the next screen, type in the URL of a page you want to test (use <https://mdn.github.io/learning-area/javascript/building-blocks/events/show-video-box-fixed.html>, for example), then choose a browser/OS combination you want to test by using the different buttons and lists. There is a lot of choice, as you'll see!
3. When you click Start session, a loading screen will then appear, which spins up a virtual machine running the combination you chose.
4. When loading has finished, you can then start to remotely test the website running in the chosen browser.
5. From here you can see the layout as it would look in the browser you are testing, move the mouse around and try clicking buttons, etc. The top menu allows you to:
- Stop the session
- Give someone else a URL so they can observe the test remotely.
- Copy text/notes to a remote clipboard.
- Take a screenshot.
- Test in full screen mode.
Once you stop the session, you'll return to the Manual Tests tab, where you'll see an entry for each of the previous manual sessions you started. Clicking on one of these entries shows more data for the session. In here you can download any screenshots you took, watch a video of the session, view data logs, and more.
> **Note:** This is already very useful, and way more convenient than having to set up all these emulators and virtual machines by yourself.
#### Advanced: The Sauce Labs API
Sauce Labs has a [restful API](https://docs.saucelabs.com/dev/api/) that allows you to programmatically retrieve details of your account and existing tests, and annotate tests with further details, such as their pass/fail state which isn't recordable by manual testing alone. For example, you might want to run one of your own Selenium tests remotely using Sauce Labs to test a certain browser/OS combination, and then pass the test results back to Sauce Labs.
It has several clients available to allow you to make calls to the API using your favorite environment, be it PHP, Java, Node.js, etc.
Let's have a brief look at how we'd access the API using Node.js and [node-saucelabs](https://github.com/saucelabs/node-saucelabs).
1. First, set up a new npm project to test this out, as detailed in [Setting up Node and npm](#setting_up_node_and_npm). Use a different directory name than before, like `sauce-test` for example.
2. Install the Node Sauce Labs wrapper using the following command:
```bash
npm install saucelabs
```
3. Create a new file inside your project root called `call_sauce.js`. give it the following contents:
```js
const SauceLabs = require("saucelabs").default;
(async () => {
const myAccount = new SauceLabs({
username: "your-sauce-username",
password: "your-sauce-api-key",
});
// Get full WebDriver URL from the client depending on region:
console.log(myAccount.webdriverEndpoint);
// Get job details of last run job
const jobs = await myAccount.listJobs("your-sauce-username", {
limit: 1,
full: true,
});
console.log(jobs);
})();
```
4. You'll need to fill in your Sauce Labs username and API key in the indicated places. These can be retrieved from your [User Settings](https://app.saucelabs.com/user-settings) page. Fill these in now.
5. Make sure everything is saved, and run your file like so:
```bash
node call_sauce
```
#### Advanced: Automated tests
We'll cover actually running automated Sauce Lab tests in the next article.
### BrowserStack
#### Getting started with BrowserStack
Let's get started with a BrowserStack Trial.
1. Create a [BrowserStack trial account](https://www.browserstack.com/users/sign_up).
2. Sign in. This should happen automatically after you verify your email address.
3. When you first sign in, you should be on the Live testing page; if not, click the _Live_ link in the top nav menu.
4. If you are on Firefox or Chrome, you'll be prompted to Install a browser extension in a dialog titled "Enable Local Testing" — click the _Install_ button to proceed. On other browsers you'll still be able to use some of the features (generally via Flash), but you might not get the full experience.
#### The basics: Manual tests
The BrowserStack Live dashboard allows you to choose what device and browser you want to test on — Platforms in the left column, devices on the right. When you mouse over or click on each device, you get a choice of browsers available on that device.

Clicking on one of those browser icons will load up your choice of platform/device/browser — choose one now, and give it a try.

> **Note:** The blue device icon next to some of the mobile device choices signals that you will be testing on a real device; choices without that icon will be run on an emulator.
You'll find that you can enter URLs into the address bar, and use the other controls like you'd expect on a real device. You can even do things like copy and paste from the device to your clipboard, scroll up and down by dragging with the mouse, or use appropriate gestures (e.g. pinch/zoom, two fingers to scroll) on the touchpads of supporting devices (e.g. MacBook). Note that not all features are available on all devices.
You'll also see a menu that allows you to control the session.

The features here are as follows:
- _Switch_ — Change to another platform/device/browser combination.
- Orientation (looks like a Reload icon) — Switch orientation between portrait and landscape.
- Fit to screen (looks like a full screen icon) — Fill the testing areas as much as possible with the device.
- Capture a bug (looks like a camera) — Takes a screenshot, then allows you to annotate and save it.
- Issue tracker (looks like a deck of cards) — View previously captured bugs/screenshots.
- Settings (cog icon) — Allows you to alter general settings for the session.
- Help (question mark) — Accesses help/support functions.
- _Devtools_ — Allows you to use your browser's devtools to directly debug or manipulate the page being shown in the test browser. This currently only works when testing the Safari browser on iOS devices.
- _Device info_ — Displays information about the testing device.
- _Features_ — Shows you what features the current configuration supports, e.g. copy to clipboard, gesture support, etc.
- _Stop_ — Ends the session.
> **Note:** This is already very useful, and way more convenient than having to set up all these emulators and virtual machines by yourself.
#### Other basic features
If you go back to the main BrowserStack page, you'll find a couple of other useful basic features under the _More_ menu option:
- _Responsive_: Enter a URL and press _Generate_, and BrowserStack will load that URL on multiple devices with different viewport sizes. Within each device you can further adjust settings like monitor size, to get a good idea of how your site's layout works across different form factors.
- _Screenshots_: Enter a URL, choose the browsers/devices/platforms you are interested in, then press _Generate screenshots_ — BrowserStack will take screenshots of your site in all those different browsers then make them available to you to view and download.
#### Advanced: The BrowserStack API
BrowserStack also has a [restful API](https://www.browserstack.com/docs/automate/api-reference/selenium/introduction) that allows you to programmatically retrieve details of your account plan, sessions, builds, etc.
It has several clients available to allow you to make calls to the API using your favorite environment, be it PHP, Java, Node.js, etc.
Let's have a brief look at how we'd access the API using Node.js.
1. First, set up a new npm project to test this out, as detailed in [Setting up Node and npm](#setting_up_node_and_npm). Use a different directory name than before, like `bstack-test` for example.
2. Create a new file inside your project root called `call_bstack.js`. give it the following contents:
```js
const request = require("request");
const bsUser = "BROWSERSTACK_USERNAME";
const bsKey = "BROWSERSTACK_ACCESS_KEY";
const baseUrl = `https://${bsUser}:${bsKey}@www.browserstack.com/automate/`;
function getPlanDetails() {
request({ uri: `${baseUrl}plan.json` }, (err, res, body) => {
console.log(JSON.parse(body));
});
/* Response:
{
automate_plan: <string>,
parallel_sessions_running: <int>,
team_parallel_sessions_max_allowed: <int>,
parallel_sessions_max_allowed: <int>,
queued_sessions: <int>,
queued_sessions_max_allowed: <int>
}
*/
}
getPlanDetails();
```
3. You'll need to fill in your BrowserStack username and API key in the indicated places. These can be retrieved from your [BrowserStack Account & Profile Details](https://www.browserstack.com/accounts/profile/details), under the Authentication & Security section. Fill these in now.
4. Make sure everything is saved, and run your file like so:
```bash
node call_bstack
```
Below we've also provided some other ready-made functions you might find useful when working with the BrowserStack restful API.
```js
function getBuilds() {
request({ uri: `${baseUrl}builds.json` }, (err, res, body) => {
console.log(JSON.parse(body));
});
/* Response:
[
{
automation_build: {
name: <string>,
duration: <int>,
status: <string>,
hashed_id: <string>
}
},
{
automation_build: {
name: <string>,
duration: <int>,
status: <string>,
hashed_id: <string>
}
},
// …
]
*/
}
function getSessionsInBuild(build) {
const buildId = build.automation_build.hashed_id;
request(
{ uri: `${baseUrl}builds/${buildId}/sessions.json` },
(err, res, body) => {
console.log(JSON.parse(body));
},
);
/* Response:
[
{
automation_session: {
name: <string>,
duration: <int>,
os: <string>,
os_version: <string>,
browser_version: <string>,
browser: <string>,
device: <string>,
status: <string>,
hashed_id: <string>,
reason: <string>,
build_name: <string>,
project_name: <string>,
logs: <string>,
browser_url: <string>,
public_url: <string>,
video_url: <string>,
browser_console_logs_url: <string>,
har_logs_url: <string>
}
},
{
automation_session: {
name: <string>,
duration: <int>,
os: <string>,
os_version: <string>,
browser_version: <string>,
browser: <string>,
device: <string>,
status: <string>,
hashed_id: <string>,
reason: <string>,
build_name: <string>,
project_name: <string>,
logs: <string>,
browser_url: <string>,
public_url: <string>,
video_url: <string>,
browser_console_logs_url: <string>,
har_logs_url: <string>
}
},
// …
]
*/
}
function getSessionDetails(session) {
const sessionId = session.automation_session.hashed_id;
request({ uri: `${baseUrl}sessions/${sessionId}.json` }, (err, res, body) => {
console.log(JSON.parse(body));
});
/* Response:
{
automation_session: {
name: <string>,
duration: <int>,
os: <string>,
os_version: <string>,
browser_version: <string>,
browser: <string>,
device: <string>,
status: <string>,
hashed_id: <string>,
reason: <string>,
build_name: <string>,
project_name: <string>,
logs: <string>,
browser_url: <string>,
public_url: <string>,
video_url: <string>,
browser_console_logs_url: <string>,
har_logs_url: <string>
}
}
*/
}
```
#### Advanced: Automated tests
We'll cover actually running automated BrowserStack tests in the next article.
### TestingBot
#### Getting started with TestingBot
Let's get started with a TestingBot Trial.
1. Create a [TestingBot trial account](https://testingbot.com/users/sign_up).
2. Sign in. This should happen automatically after you verify your email address.
#### The basics: Manual tests
The [TestingBot dashboard](https://testingbot.com/members) lists the various options you can choose from. For now, make sure you are on the _Live Web Testing_ tab.
1. Enter the URL of the page you want to test.
2. Choose the browser/OS combination you want to test by selecting the combination in the grid.

3. When you click _Start Browser_, a loading screen will then appear, which spins up a virtual machine running the combination you chose.
4. When loading has finished, you can then start to remotely test the website running in the chosen browser.
5. From here you can see the layout as it would look in the browser you are testing, move the mouse around and try clicking buttons, etc. The side menu allows you to:
- Stop the session
- Change the screen resolution
- Copy text/notes to a remote clipboard
- Take, edit, and download screenshots
- Test in full screen mode.
Once you stop the session, you'll return to the _Live Web Testing_ page, where you'll see an entry for each of the previous manual sessions you started. Clicking on one of these entries shows more data for the session. Here you can download any screenshots you took, watch a video of the test, and view logs for the session.
#### Advanced: The TestingBot API
TestingBot has a [restful API](https://testingbot.com/support/api) that allows you to programmatically retrieve details of your account and existing tests, and annotate tests with further details, such as their pass/fail state which isn't recordable by manual testing alone.
TestingBot has several API clients you can use to interact with the API, including clients for NodeJS, Python, Ruby, Java and PHP.
Below is an example on how to interact with the TestingBot API with the NodeJS client [testingbot-api](https://www.npmjs.com/package/testingbot-api).
1. First, set up a new npm project to test this out, as detailed in [Setting up Node and npm](#setting_up_node_and_npm). Use a different directory name than before, like `tb-test` for example.
2. Install the Node TestingBot wrapper using the following command:
```bash
npm install testingbot-api
```
3. Create a new file inside your project root called `tb.js`. give it the following contents:
```js
const TestingBot = require("testingbot-api");
let tb = new TestingBot({
api_key: "your-tb-key",
api_secret: "your-tb-secret",
});
tb.getTests(function (err, tests) {
console.log(tests);
});
```
4. You'll need to fill in your TestingBot Key and Secret in the indicated places. You can find these in the [TestingBot dashboard](https://testingbot.com/members/user/edit).
5. Make sure everything is saved, and run the file:
```bash
node tb.js
```
#### Advanced: Automated tests
We'll cover actually running automated TestingBot tests in the next article.
## Summary
This was quite a ride, but I'm sure you can start to see the benefits of using automation tools to do some of the heavy lifting in terms of testing.
In the next article, we'll look at setting up our own local automation system using Selenium, and how to combine that with services such as Sauce Labs, BrowserStack and TestingBot.
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment", "Learn/Tools_and_testing/Cross_browser_testing")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing | data/mdn-content/files/en-us/learn/tools_and_testing/cross_browser_testing/introduction/index.md | ---
title: Introduction to cross-browser testing
slug: Learn/Tools_and_testing/Cross_browser_testing/Introduction
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies", "Learn/Tools_and_testing/Cross_browser_testing")}}
This article gives an overview of cross-browser testing: what cross-browser testing is, some common problems, and some approaches for debugging/troubleshooting.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To gain an understanding of the high-level concepts involved in cross-browser testing.
</td>
</tr>
</tbody>
</table>
## What is cross-browser testing?
Cross-browser testing is the practice of ensuring that a website works across various browsers and devices. Web developers should consider:
- Different browsers, including slightly older ones that don't support all the latest JS/CSS features.
- Different devices, from desktops and laptops to tablets and smartphones, to smart TVs, with varying hardware capabilities.
- People with disabilities, who may rely on assistive technologies like screen readers, or use only a keyboard.
Remember that you are not your users — just because your site works on your MacBook Pro or high-end Galaxy Nexus, doesn't mean it will work for all your users!
> **Note:** [Make the web work for everyone](https://hacks.mozilla.org/2016/07/make-the-web-work-for-everyone/) discusses the different browsers, their market share, and related cross-browser compatibility issues.
Websites should be accessible across different browsers and devices, and to people with disabilities (e.g. screen-reader-friendly). A site doesn't need to deliver the exact same experience on all browsers and devices, as long as the core functionality is accessible in some way. For example, a modern browser might have something animated, 3D and shiny, while older browsers might just show a flat graphic with the same information.
Also, it's just about impossible for a website to work on ALL browsers and devices, so a web developer should come to an agreement with the site owner on the range of browsers and devices where the code will work.
## Why do cross-browser issues occur?
There are many different reasons why cross-browser issues occur, and note that here we are talking about issues where things behave differently across different browsers/devices/browsing preferences. Before you even get to cross-browser issues, you should have already fixed bugs in your code (see [Debugging HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML), [Debugging CSS](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS), and [What went wrong? Troubleshooting JavaScript](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong) from previous topics to refresh your memory if needed).
Cross-browser issues commonly occur because:
- sometimes browsers have bugs, or implement features differently. This situation is a lot less bad than it used to be; back when IE4 and Netscape 4 were competing to be the dominant browser in the 1990s, browser companies deliberately implemented things differently from each other to try to gain a competitive advantage, which made life hell for developers. Browsers are much better at following standards these days, but differences and bugs still creep through sometimes.
- some browsers may have different levels of support for technology features than others. This is inevitable when you are dealing with bleeding edge features that browsers are just getting around to implementing, or if you have to support very old browsers that are no longer being developed, which may have been frozen (i.e. no more new work done on them) a long time before a new feature was even invented. As an example, if you want to use cutting-edge JavaScript features in your site, they might not work in older browsers. If you need to support older browsers, you might have to not use those, or convert your code to old-fashioned syntax using some kind of cross-compiler where needed.
- some devices may have constraints that cause a website to run slowly, or display badly. For example, if a site has been designed to look nice on a desktop PC, it will probably look tiny and be hard to read on a mobile device. If your site includes a load of big animations, it might be OK on a high-spec tablet but might be sluggish or jerky on a low-end device.
…and more reasons besides.
In later articles, we'll explore common cross-browser problems, and look at solutions to those.
## Workflows for cross-browser testing
All of this cross-browser testing business may sound time-consuming and scary, but it needn't be — you just need to plan carefully for it, and make sure you do enough testing in the right places to make sure you don't run into unexpected problems. If you are working on a large project, you should be testing it regularly, to make sure that new features work for your target audience, and that new additions to the code don't break old features that were previously working.
If you leave all the testing to the end of a project, any bugs you uncover will be a lot more expensive and time-consuming to fix than if you uncover them and fix them as you go along.
The workflow for testing and bug fixes on a project can be broken down into roughly the following four phases (this is only very rough — different people may do things quite differently to this):
**Initial planning** > **Development** > **Testing/discovery** > **Fixes/iteration**
Steps 2–4 will tend to be repeated as many times as necessary to get all of the implementation done. We will look at the different parts of the testing process in much greater detail in subsequent articles, but for now, let's just summarize what may occur in each step.
### Initial planning
In the initial planning phase, you will probably have several planning meetings with the site owner/client (this might be your boss, or someone from an external company you are building a website for), in which you determine exactly what the website should be — what content and functionality should it have, what should it look like, etc. At this point, you'll also want to know how much time you have to develop the site — what is their deadline, and how much are they going to pay you for your work? We won't go into much detail about this, but cross-browser issues can have a serious effect on such planning.
Once you've got an idea of the required feature set, and what technologies you will likely build these features with, you should start exploring the target audience — what browsers, devices, etc. will the target audience for this site be using? The client might already have data about this from previous research they've done, e.g. from other websites they own, or from previous versions of the website you are now working on. If not, you will be able to get a good idea by looking at other sources, such as usage stats for competitors, or countries the site will be serving. You can also use a bit of intuition.
So for example, you might be building an e-commerce site that serves customers in North America. The site should work entirely in the last few versions of the most popular desktop and mobile (iOS, Android, Windows phone) browsers — this should include Chrome (and Opera as it is based on the same rendering engine as Chrome), Firefox, Edge, and Safari.
It should also be accessible with WCAG AA compliance.
Now you know your target testing platforms, you should go back and review the required feature set and what technologies you are going to use.
For example, if the e-commerce site owner wants a WebGL-powered 3D tour of each product built into the product pages, they will need to accept that this just won't work all legacy browser version.
You should compile a list of the potential problem areas.
> **Note:** You can find browser support information for technologies by looking up the different features on MDN — the site you're on! You should also consult [caniuse.com](https://caniuse.com/), for some further useful details.
Once you've agreed on these details, you can go ahead and start developing the site.
### Development
Now on to the development of the site. You should split the different parts of the development into modules, for example you might split the different site areas up — home page, product page, shopping cart, payment workflow, etc. You might then further subdivide these — implement a common site header and footer, implement product page detail view, implement persistent shopping cart widget, etc.
There are multiple general strategies to cross-browser development, for example:
- Get all the functionality working as closely as possible in all target browsers. This may involve writing different code paths that reproduce functionality in different ways aimed at different browsers, or using a {{glossary("Polyfill")}} to mimic any missing support using JavaScript or other technologies, or using a library that allows you to write a single bit of code and then does different things in the background depending on what the browser supports.
- Accept that some things aren't going to work the same on all browsers, and provide different (acceptable) solutions in browsers that don't support the full functionality. Sometimes this is inevitable due to device constraints — a cinema widescreen isn't going to give the same visual experience as a 4" mobile screen, regardless of how you program your site.
- Accept that your site just isn't going to work in some older browsers, and move on. This is OK, provided your client/userbase is OK with it.
Normally your development will involve a combination of the above three approaches. The most important thing is that you test each small part before committing it — don't leave all the testing till the end!
### Testing/discovery
After each implementation phase, you will need to test the new functionality. To start with, you should make sure there are no general issues with your code that are stopping your feature from working:
1. Test it in a couple of stable browsers on your system, like Firefox, Safari, Chrome, or Edge.
2. Do some lo-fi accessibility testing, such as trying to use your site with only the keyboard, or using your site via a screen reader to see if it is navigable.
3. Test on a mobile platform, such as Android or iOS.
At this point, fix any problems you find with your new code.
Next, you should try expanding your list of test browsers to a full list of target audience browsers and start concentrating on weeding out cross-browser issues (see the next article for more information on [determining your target browsers](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies#gotta_test_em_all)). For example:
- Try to test the latest change on all the modern desktop browsers you can — including Firefox, Chrome, Opera, Edge, and Safari on desktop (Mac, Windows, and Linux, ideally).
- Test it in common phone and tablet browsers (e.g. iOS Safari on iPhone/iPad, Chrome and Firefox on iPhone/iPad/Android),
- Also do tests in any other browsers you have included inside your target list.
The most lo-fi option is to just do all the testing you can by yourself (pulling in teammates to help out if you are working in a team). You should try to test it on real physical devices where possible.
If you haven't got the means to test all those different browsers, operating systems, and device combinations on physical hardware, you can also make use of emulators (emulate a device using software on your desktop computer) and virtual machines (software that allows you to emulate multiple operating system/software combinations on your desktop computer). This is a very popular choice, especially in some circumstances — for example, Windows doesn't let you have multiple versions of Windows installed simultaneously on the same machine, so using multiple virtual machines is often the only option here.
Another option is user groups — using a group of people outside your development team to test your site. This could be a group of friends or family, a group of other employees, a class at a local university, or a professional user testing setup, where people are paid to test out your site and provide results.
Finally, you can get smarter with your testing using auditing or automation tools; this is a sensible choice as your projects get bigger, as doing all this testing by hand can start to take a really long time. You can set up your own testing automation system ([Selenium](https://www.selenium.dev/) being the popular app of choice) that could for example load your site in a number of different browsers, and:
- see if a button click causes something to happen successfully (like for example, a map displaying), displaying the results once the tests are completed
- take a screenshot of each, allowing you to see if a layout is consistent across the different browsers.
If you wish to invest money in testing, there are also commercial tools that can automate much of the setup and testing for you (such as [Sauce Labs](https://saucelabs.com/) and [Browser Stack](https://www.browserstack.com/)). These kinds of tools usually enable a continuous integration workflow, where code changes are automatically tested before they are allowed to be submitted into your code repository.
#### Testing on prerelease browsers
It is often a good idea to test on prerelease versions of browsers; see the following links:
- [Firefox Developer Edition](https://www.mozilla.org/en-US/firefox/developer/)
- [Microsoft Edge Insider](https://www.microsoftedgeinsider.com/)
- [Safari Technology Preview](https://developer.apple.com/safari/technology-preview/)
- [Chrome Canary](https://www.google.com/chrome/canary/)
- [Opera Developer](https://www.opera.com/computer/beta)
This is especially prevalent if you are using very new technologies in your site, and you want to test against the latest implementations, or if you are coming across a bug in the latest release version of a browser, and you want to see if the browser's developers have fixed the bug in a newer version.
### Fixes/iteration
Once you've discovered a bug, you need to try to fix it.
The first thing to do is to narrow down where the bug occurs as much as possible. Get as much information as you can from the person reporting the bug — what platform(s), device(s), browser version(s), etc. Try it on similar configurations (e.g. the same browser version on different desktop platforms, or a few different versions of the same browser on the same platform) to see how widely the bug persists.
It might not be your fault — if a bug exists in a browser, then hopefully the vendor will rapidly fix it. It might have already been fixed — for example if a bug is present in Firefox release 49, but it is no longer there in Firefox Nightly (version 52), then they have fixed it. If it is not fixed, then you may want to file a bug (see [Reporting bugs](#reporting_bugs), below).
If it is your fault, you need to fix it! Finding out the cause of the bug involves the same strategy as any web development bug (again, see [Debugging HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML), [Debugging CSS](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS), and [What went wrong? Troubleshooting JavaScript](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong)). Once you've discovered what is causing your bug, you need to decide how to work around it in the particular browser it is causing problems in — you can't just change the problem code outright, as this may break the code in other browsers. The general approach is usually to fork the code in some way, for example use JavaScript feature detection code to detect situations in which a problem feature doesn't work, and run some different code in those cases that does work.
Once a fix has been made, you'll want to repeat your testing process to make sure your fix is working OK, and hasn't caused the site to break in other places or other browsers.
## Reporting bugs
Just to reiterate on what was said above, if you discover bugs in browsers, you should report them:
- [Firefox Bugzilla](https://bugzilla.mozilla.org/)
- [EdgeHTML issue tracker](https://developer.microsoft.com/en-us/microsoft-edge/)
- [Safari](https://bugs.webkit.org/)
- [Chrome](https://bugs.chromium.org/p/chromium/issues/list)
- [Opera](https://opera.atlassian.net/servicedesk/customer/portal/9)
## Summary
This article should have given you a high-level understanding of the most important concepts you need to know about cross browser testing. Armed with this knowledge, you are now ready to move on and start learning about Cross-browser testing strategies.
{{NextMenu("Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies", "Learn/Tools_and_testing/Cross_browser_testing")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing | data/mdn-content/files/en-us/learn/tools_and_testing/github/index.md | ---
title: Git and GitHub
slug: Learn/Tools_and_testing/GitHub
page-type: learn-module
---
{{LearnSidebar}}
All developers will use some kind of **version control system** (**VCS**), a tool to allow them to collaborate with other developers on a project without the danger of them overwriting each other's work, and roll back to previous versions of the code base if a problem is discovered later on. The most popular VCS (at least among web developers) is **Git**, along with **GitHub**, a site that provides hosting for your repositories and several tools for working with them. This module aims to teach you what you need to know about both of them.
## Overview
VCSes are essential for software development:
- It is rare that you will work on a project completely on your own, and as soon as you start working with other people you start to run the risk of conflicting with each other's work — this is when both of you try to update the same piece of code at the same time. You need to have some kind of mechanism in place to manage the occurrences, and help avoid loss of work as a result.
- When working on a project on your own or with others, you'll want to be able to back up the code in a central place, so it is not lost if your computer breaks.
- You will also want to be able to roll back to earlier versions if a problem is later discovered. You might have started doing this in your own work by creating different versions of the same file, e.g. `myCode.js`, `myCode_v2.js`, `myCode_v3.js`, `myCode_final.js`, `myCode_really_really_final.js`, etc., but this is really error-prone and unreliable.
- Different team members will commonly want to create their own separate versions of the code (called **branches** in Git), work on a new feature in that version, and then get it merged in a controlled manner (in GitHub we use **pull requests**) with the master version when they are done with it.
VCSes provide tools to meet the above needs. [Git](https://git-scm.com/) is an example of a VCS, and [GitHub](https://github.com/) is a website + infrastructure that provides a Git server plus a number of really useful tools for working with git repositories individually or in teams, such as reporting issues with the code, reviewing tools, project management features such as assigning tasks and task statuses, and more.
> **Note:** Git is actually a _distributed_ version control system, meaning that a complete copy of the repository containing the codebase is made on your computer (and everyone else's). You make changes to your own copy and then push those changes back up to the server, where an administrator will decide whether to merge your changes with the master copy.
> **Callout:**
>
> #### Looking to become a front-end web developer?
>
> We have put together a course that includes all the essential information you need to
> work towards your goal.
>
> [**Get started**](/en-US/docs/Learn/Front-end_web_developer)
## Prerequisites
To use Git and GitHub, you need:
- A desktop computer with Git installed on it (see the [Git downloads page](https://git-scm.com/downloads)).
- A tool to use Git. Depending on how you like to work, you could use a [Git GUI client](https://git-scm.com/downloads/guis/) (we'd recommend GitHub Desktop, SourceTree or Git Kraken) or just stick to using a terminal window. In fact, it is probably useful for you to get to know at least the basics of git terminal commands, even if you intend to use a GUI.
- A [GitHub account](https://github.com/join). If you haven't already got one, sign up now using the provided link.
In terms of prerequisite knowledge, you don't need to know anything about web development, Git/GitHub, or VCSes to start this module. However, it is recommended that you know some coding so that you have reasonable computer literacy, and some code to store in your repositories!
It is also preferable that you have some basic terminal knowledge, so for example moving between directories, creating files, and modifying the system `PATH`.
> **Note:** GitHub is not the only site/toolset you can use with Git. There are other alternatives such as [GitLab](https://about.gitlab.com/) that you could try, and you could also try setting your own Git server up and using it instead of GitHub. We've only stuck with GitHub in this course to provide a single way that works.
## Guides
Note that the links below take you to resources on external sites. Eventually, we are aiming to have our own dedicated Git/GitHub course, but for now, these will help you get to grips with the subject at hand.
- [Hello, World (from GitHub)](https://docs.github.com/en/get-started/quickstart/hello-world)
- : This is a good place to start — this practical guide gets you to jump right into using GitHub, learning the basics of Git such as creating repositories and branches, making commits, and opening and merging pull requests.
- [Git Handbook (from GitHub)](https://docs.github.com/en/get-started/using-git/about-git)
- : This Git Handbook goes into a little more depth, explaining what a VCS is, what a repository is, how the basic GitHub model works, Git commands and examples, and more.
- [Forking Projects (from GitHub)](https://docs.github.com/en/get-started/quickstart/contributing-to-projects)
- : Forking projects is essential when you want to contribute to someone else's code. This guide explains how.
- [About Pull Requests (from GitHub)](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests)
- : A useful guide to managing pull requests, the way that your suggested code changes are delivered to people's repositories for consideration.
- [Mastering issues (from GitHub)](https://docs.github.com/en/issues/tracking-your-work-with-issues/about-issues)
- : Issues are like a forum for your GitHub project, where people can ask questions and report problems, and you can manage updates (for example assigning people to fix issues, clarifying the issue, letting people know things are fixed). This article tells you what you need to know about issues.
> **Note:** There is **a lot more** that you can do with Git and GitHub, but we feel that the above represents the minimum you need to know to start using Git effectively. As you get deeper into Git, you'll start to realize that it is easy to go wrong when you start using more complicated commands. Don't worry, even professional web developers find Git confusing sometimes, and often solve problems by searching for solutions on the web, or consulting sites like [Flight rules for Git](https://github.com/k88hudson/git-flight-rules) and [Dangit, git!](https://dangitgit.com/)
## See also
- [Understanding the GitHub flow](https://docs.github.com/en/get-started/quickstart/github-flow)
- [Git command list](https://git-scm.com/docs)
- [Mastering markdown](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) (the text format you write in on PR, issue comments, and `.md` files).
- [Getting Started with GitHub Pages](https://docs.github.com/en/pages/quickstart) (how to publish demos and websites on GitHub).
- [Learn Git branching](https://learngitbranching.js.org/)
- [Flight rules for Git](https://github.com/k88hudson/git-flight-rules) (a very useful compendium of ways to achieve specific things in Git, including how to correct things when you went wrong).
- [Dangit, git!](https://dangitgit.com/) (another useful compendium, specifically of ways to correct things when you went wrong).
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/index.md | ---
title: Understanding client-side JavaScript frameworks
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks
page-type: learn-module
---
{{LearnSidebar}}
JavaScript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications. Many modern companies use frameworks as a standard part of their tooling, so many front-end development jobs now require framework experience. In this set of articles, we are aiming to give you a comfortable starting point to help you begin learning frameworks.
As an aspiring front-end developer, it can be hard to work out where to begin when learning frameworks — there are so many frameworks to choose from, new ones appear all the time, they mostly work in a similar way but do some things differently, and there are some specific things to be careful about when using frameworks.
We are not aiming to exhaustively teach you everything you need to know about React/ReactDOM, or Vue, or some other specific framework; the framework teams' own docs (and other resources) do that job already. Instead, we want to back up and first answer more fundamental questions such as:
- Why should I use a framework? What problems do they solve for me?
- What questions should I ask when trying to choose a framework? Do I even need to use a framework?
- What features do frameworks have? How do they work in general, and how do frameworks' implementations of these features differ?
- How do they relate to "vanilla" JavaScript or HTML?
After that, we'll provide some tutorials covering the essentials of some of the different framework choices, to provide you with enough context and familiarity to start going into greater depth yourself. We want you to go forward and learn about frameworks in a pragmatic way that doesn't forget about web platform fundamental best practices such as accessibility.
**[Get started now, with "Introduction to client-side frameworks"](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction)**
## Prerequisites
You should really learn the basics of the core web languages first before attempting to move on to learning client-side frameworks — [HTML](/en-US/docs/Learn/HTML), [CSS](/en-US/docs/Learn/CSS), and especially [JavaScript](/en-US/docs/Learn/JavaScript).
Your code will be richer and more professional as a result, and you'll be able to troubleshoot problems with more confidence if you understand the fundamental web platform features that the frameworks are building on top of.
> **Callout:**
>
> #### Looking to become a front-end web developer?
>
> We have put together a course that includes all the essential information you need to
> work towards your goal.
>
> [**Get started**](/en-US/docs/Learn/Front-end_web_developer)
## Introductory guides
- [1. Introduction to client-side frameworks](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction)
- : We begin our look at frameworks with a general overview of the area, looking at a brief history of JavaScript and frameworks, why frameworks exist and what they give us, how to start thinking about choosing a framework to learn, and what alternatives there are to client-side frameworks.
- [2. Framework main features](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features)
- : Each major JavaScript framework has a different approach to updating the DOM, handling browser events, and providing an enjoyable developer experience. This article will explore the main features of "the big 4" frameworks, looking at how frameworks tend to work from a high level and the differences between them.
## React tutorials
> **Note:** React tutorials last tested in January 2023, with React/ReactDOM 18.2.0 and create-react-app 5.0.1.
>
> If you need to check your code against our version, you can find a finished version of the sample React app code in our [todo-react repository](https://github.com/mdn/todo-react). For a running live version, see <https://mdn.github.io/todo-react/>.
- [1. Getting started with React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started)
- : In this article we will say hello to React. We'll discover a little bit of detail about its background and use cases, set up a basic React toolchain on our local computer, and create and play with a simple starter app, learning a bit about how React works in the process.
- [2. Beginning our React todo list](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning)
- : Let's say that we've been tasked with creating a proof-of-concept in React – an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them. This article will walk you through putting the basic `App` component structure and styling in place, ready for individual component definition and interactivity, which we'll add later.
- [3. Componentizing our React app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components)
- : At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn't have any hard rules for what is and isn't a component – that's up to you! In this article, we will show you a sensible way to break our app up into components.
- [4. React interactivity: Events and state](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state)
- : With our component plan worked out, it's now time to start updating our app from a completely static UI to one that actually allows us to interact and change things. In this article we'll do this, digging into events and state along the way.
- [5. React interactivity: Editing, filtering, conditional rendering](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering)
- : As we near the end of our React journey (for now at least), we'll add the finishing touches to the main areas of functionality in our Todo list app. This includes allowing you to edit existing tasks and filtering the list of tasks between all, completed, and incomplete tasks. We'll look at conditional UI rendering along the way.
- [6. Accessibility in React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility)
- : In our final tutorial article, we'll focus on (pun intended) accessibility, including focus management in React, which can improve usability and reduce confusion for both keyboard-only and screen reader users.
- [7. React resources](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources)
- : Our final article provides you with a list of React resources that you can use to go further in your learning.
## Ember tutorials
> **Note:** Ember tutorials last tested in May 2020, with Ember/Ember CLI version 3.18.0.
>
> If you need to check your code against our version, you can find a finished version of the sample Ember app code in the [ember-todomvc-tutorial repository](https://github.com/NullVoxPopuli/ember-todomvc-tutorial/tree/master/steps/00-finished-todomvc/todomvc). For a running live version, see <https://nullvoxpopuli.github.io/ember-todomvc-tutorial/> (this also includes a few additional features not covered in the tutorial).
- [1. Getting started with Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started)
- : In our first Ember article we will look at how Ember works and what it's useful for, install the Ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.
- [2. Ember app structure and componentization](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization)
- : In this article we'll get right on with planning out the structure of our TodoMVC Ember app, adding in the HTML for it, and then breaking that HTML structure into components.
- [3. Ember interactivity: Events, classes and state](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state)
- : At this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items. Along the way, we'll look at using events in Ember, creating component classes to contain JavaScript code to control interactive features, and setting up a service to keep track of the data state of our app.
- [4. Ember Interactivity: Footer functionality, conditional rendering](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer)
- : Now it's time to start tackling the footer functionality in our app. Here we'll get the todo counter to update to show the correct number of todos still to complete, and correctly apply styling to completed todos (i.e. where the checkbox has been checked). We'll also wire up our "Clear completed" button. Along the way, we'll learn about using conditional rendering in our templates.
- [5. Routing in Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing)
- : In this article we learn about routing or URL-based filtering as it is sometimes referred to. We'll use it to provide a unique URL for each of the three todo views — "All", "Active", and "Completed".
- [6. Ember resources and troubleshooting](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources)
- : Our final Ember article provides you with a list of resources that you can use to go further in your learning, plus some useful troubleshooting and other information.
## Vue tutorials
> **Note:** Vue tutorial last tested in January 2023, with Vue 3.2.45.
>
> If you need to check your code against our version, you can find a finished version of the sample Vue app code in our [todo-vue repository](https://github.com/mdn/todo-vue). For a running live version, see <https://mdn.github.io/todo-vue/>.
- [1. Getting started with Vue](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started)
- : Now let's introduce Vue, the third of our frameworks. In this article, we'll look at a little bit of Vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example.
- [2. Creating our first Vue component](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component)
- : Now it's time to dive deeper into Vue, and create our own custom component — we'll start by creating a component to represent each item in the todo list. Along the way, we'll learn about a few important concepts such as calling components inside other components, passing data to them via props and saving data state.
- [3. Rendering a list of Vue components](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists)
- : At this point we've got a fully working component; we're now ready to add multiple `ToDoItem` components to our app. In this article we'll look at adding a set of todo item data to our `App.vue` component, which we'll then loop through and display inside `ToDoItem` components using the `v-for` directive.
- [4. Adding a new todo form: Vue events, methods, and models](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models)
- : We now have sample data in place and a loop that takes each bit of data and renders it inside a `ToDoItem` in our app. What we really need next is the ability to allow our users to enter their own todo items into the app, and for that, we'll need a text `<input>`, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. This is what we'll cover in this article.
- [5. Styling Vue components with CSS](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling)
- : The time has finally come to make our app look a bit nicer. In this article, we'll explore the different ways of styling Vue components with CSS.
- [6. Using Vue computed properties](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties)
- : In this article we'll add a counter that displays the number of completed todo items, using a feature of Vue called computed properties. These work similarly to methods but only re-run when one of their dependencies changes.
- [7. Vue conditional rendering: editing existing todos](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering)
- : Now it is time to add one of the major parts of functionality that we're still missing — the ability to edit existing todo items. To do this, we will take advantage of Vue's conditional rendering capabilities — namely `v-if` and `v-else` — to allow us to toggle between the existing todo item view and an edit view where you can update todo item labels. We'll also look at adding functionality to delete todo items.
- [8. Vue refs and lifecycle methods for focus management](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management)
- : We are nearly done with Vue. The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility. We'll look at using Vue refs to handle this — an advanced feature that allows you to have direct access to the underlying DOM nodes below the virtual DOM, or direct access from one component to the internal DOM structure of a child component.
- [9. Vue resources](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources)
- : Now we'll round off our study of Vue by giving you a list of resources that you can use to go further in your learning, plus some other useful tips.
## Svelte tutorials
> **Note:** Svelte tutorials last tested in August 2020, with Svelte 3.24.1.
>
> If you need to check your code against our version, you can find a finished version of the sample Svelte app code as it should be after each article, in our [mdn-svelte-tutorial](https://github.com/opensas/mdn-svelte-tutorial) repo. For a running live version, see our Svelte REPL at <https://svelte.dev/repl/378dd79e0dfe4486a8f10823f3813190?version=3.23.2>.
- [1. Getting started with Svelte](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started)
- : In this article we'll provide a quick introduction to the [Svelte framework](https://svelte.dev/). We will see how Svelte works and what sets it apart from the rest of the frameworks and tools we've seen so far. Then we will learn how to set up our development environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production.
- [2. Starting our Svelte Todo list app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning)
- : Now that we have a basic understanding of how things work in Svelte, we can start building our example app: a todo list. In this article we will first have a look at the desired functionality of our app, then we'll create a `Todos.svelte` component and put static markup and styles in place, leaving everything ready to start developing our To-Do list app features, which we'll go on to in subsequent articles.
- [3. Dynamic behavior in Svelte: working with variables and props](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props)
- : Now that we have our markup and styles ready we can start developing the required features for our Svelte To-Do list app. In this article we'll be using variables and props to make our app dynamic, allowing us to add and delete todos, mark them as complete, and filter them by status.
- [4. Componentizing our Svelte app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components)
- : The central objective of this article is to look at how to break our app into manageable components and share information between them. We'll componentize our app, then add more functionality to allow users to update existing components.
- [5. Advanced Svelte: Reactivity, lifecycle, accessibility](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility)
- : In this article we will add the app's final features and further componentize our app. We will learn how to deal with reactivity issues related to updating objects and arrays. To avoid common pitfalls, we'll have to dig a little deeper into Svelte's reactivity system. We'll also look at solving some accessibility focus issues, and more besides.
- [6. Working with Svelte stores](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores)
- : In this article we will show another way to handle state management in Svelte — [Stores](https://learn.svelte.dev/tutorial/writable-stores). Stores are global data repositories that hold values. Components can subscribe to stores and receive notifications when their values change.
- [7. TypeScript support in Svelte](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript)
- : We will now learn how to use TypeScript in Svelte applications. First we'll learn what TypeScript is and what benefits it can bring us. Then we'll see how to configure our project to work with TypeScript files. Finally we will go over our app and see what modifications we have to make to fully take advantage of TypeScript features.
- [8. Deployment and next steps](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next)
- : In this final article we will look at how to deploy your application and get it online, and also share some of the resources that you should go on to, to continue your Svelte learning journey.
## Angular tutorials
> **Note:** Angular tutorials last tested in April 2021, with Angular CLI (NG) 11.2.5.
- [1. Getting started with Angular](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_getting_started)
- : In this article we look at what Angular has to offer, install the prerequisites and set up a sample app, and look at Angular's basic architecture.
- [2. Beginning our Angular todo list app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_todo_list_beginning)
- : At this point, we are ready to start creating our to-do list application using Angular. The finished application will display a list of to-do items and includes editing, deleting, and adding features. In this article you will get to know your application structure, and work up to displaying a basic list of to-do items.
- [3. Styling our Angular app](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_styling)
- : Now that we've got our basic application structure set up and started displaying something useful, let's switch gears and spend an article looking at how Angular handles styling of applications.
- [4. Creating an item component](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_item_component)
- : Components provide a way for you to organize your application. This article walks you through creating a component to handle the individual items in the list, and adding check, edit, and delete functionality. The Angular event model is covered here.
- [5. Filtering our to-do items](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_filtering)
- : Now let's move on to adding functionality to allow users to filter their to-do items, so they can view active, completed, or all items.
- [6. Building Angular applications and further resources](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_building)
- : This final Angular article covers how to build an app ready for production, and provides further resources for you to continue your learning journey.
## Which frameworks did we choose?
We are publishing our initial set of articles with guides focusing on five frameworks. Four of them are very popular and well-established — React/ReactDOM, Ember, Vue, and Angular — whereas Svelte is a comparative newcomer that shows a lot of promise and has gained a lot of recent popularity.
There is a variety of reasons for this:
- They are popular choices that will be around for a while — like with any software tool, it is good to stick with actively-developed choices that are likely to not be discontinued next week, and which will be desirable additions to your skill set when looking for a job.
- They have strong communities and good documentation. It is very important to be able to get help with learning a complex subject, especially when you are just starting out.
- We don't have the resources to cover _all_ modern frameworks. That list would be very difficult to keep up-to-date anyway, as new ones appear all the time.
- As a beginner, trying to choose what to focus on out of the huge number of choices available is a very real problem. Keeping the list short is therefore helpful.
We want to say this upfront — we've **not** chosen the frameworks we are focusing on because we think they are the best, or because we endorse them in any way. We just think they score highly on the above criteria.
Note that we were hoping to have more frameworks included upon initial publication, but we decided to release the content and then add more framework guides later, rather than delay it longer. If your favorite framework is not represented in this content and you'd like to help change that, feel free to [discuss it with us](/en-US/docs/MDN/Community/Communication_channels)!
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/ember_routing/index.md | ---
title: Routing in Ember
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In this article we learn about **routing**, or URL-based filtering as it is sometimes referred to. We'll use it to provide a unique URL for each of the three todo views — "All", "Active", and "Completed".
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn about implementing routing in Ember.</td>
</tr>
</tbody>
</table>
## URL-based filtering
Ember comes with a routing system that has a tight integration with the browser URL. Typically, when writing web applications, you want the page to be represented by the URL so that if (for any reason), the page needs to refresh, the user isn't surprised by the state of the web app — they can link directly to significant views of the app.
At the moment, we already have the "All" page, as we are currently not doing any filtering in the page that we've been working with, but we will need to reorganize it a bit to handle a different view for the "Active" and "Completed" todos.
An Ember application has a default "application" route, which is tied to the `app/templates/application.hbs` template. Because that application template is the entry point to our todo app, we'll need to make some changes to allow for routing.
## Creating the routes
Let's start by creating three new routes: "Index", "Active" and "Completed". To do this you'll need to enter the following commands into your terminal, inside the root directory of your app:
```bash
ember generate route index
ember generate route completed
ember generate route active
```
The second and third commands should have not only generated new files, but also updated an existing file, `app/router.js`. It contains the following contents:
```js
import EmberRouter from "@ember/routing/router";
import config from "./config/environment";
export default class Router extends EmberRouter {
location = config.locationType;
rootURL = config.rootURL;
}
Router.map(function () {
this.route("completed");
this.route("active");
});
```
The highlighted lines were added when the 2nd and 3rd commands above were run.
`router.js` behaves as a "sitemap" for developers to be able to quickly see how the entire app is structured. It also tells Ember how to interact with your route, such as when loading arbitrary data, handling errors while loading that data, or interpreting dynamic segments of the URL. Since our data is static, we won't get to any of those fancy features, but we'll still make sure that the route provides the minimally required data to view a page.
Creating the "Index" route did not add a route definition line to `router.js`, because like with URL navigation and JavaScript module loading, "Index" is a special word that indicates the default route to render, load, etc.
To adjust our old way of rendering the TodoList app, we'll first need to replace the TodoList component invocation from the application template with an `\{{outlet}}` call, which means "any sub-route will be rendered in place here".
Go to the `todomvc/app/templates/application.hbs` file and replace
```hbs
<TodoList />
```
With
```hbs
\{{outlet}}
```
Next, in our `index.hbs`, `completed.hbs`, and `active.hbs` templates (also found in the templates directory) we can for now just enter the TodoList component invocation.
In each case, replace
```hbs
\{{outlet}}
```
with
```hbs
<TodoList />
```
So at this point, if you try the app again and visit any of the three routes
`localhost:4200 localhost:4200/active localhost:4200/completed`
you'll see exactly the same thing. At each URL, the template that corresponds to the specific path ("Active", "Completed", or "Index"), will render the `<TodoList />` component. The location in the page where `<TodoList />` is rendered is determined by the `\{{ outlet }}` inside the parent route, which in this case is `application.hbs`. So we have our routes in place. Great!
But now we need a way to differentiate between each of these routes, so that they show what they are supposed to show.
First of all, return once more to our `todo-data.js` file. It already contains a getter that returns all todos, and a getter that returns incomplete todos. The getter we are missing is one to return just the completed todos. Add the following below the existing getters:
```js
get completed() {
return this.todos.filter((todo) => todo.isCompleted);
}
```
## Models
Now we need to add models to our route JavaScript files to allow us to easily return specific data sets to display in those models. `model` is a data loading lifecycle hook. For TodoMVC, the capabilities of model aren't that important to us; you can find more information in the [Ember model guide](https://guides.emberjs.com/release/routing/specifying-a-routes-model/) if you want to dig deeper. We also provide access to the service, like we did for the components.
### The index route model
First of all, update `todomvc/app/routes/index.js` so it looks as follows:
```js
import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";
export default class IndexRoute extends Route {
@service("todo-data") todos;
model() {
let todos = this.todos;
return {
get allTodos() {
return todos.all;
},
};
}
}
```
We can now update the `todomvc/app/templates/index.hbs` file so that when it includes the `<TodoList />` component, it does so explicitly with the available model, calling its `allTodos()` getter to make sure all of the todos are shown.
In this file, change
```hbs
<TodoList />
```
To
```hbs-nolint
<TodoList @todos=\{{ @model.allTodos }} />
```
### The completed route model
Now update `todomvc/app/routes/completed.js` so it looks as follows:
```js
import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";
export default class CompletedRoute extends Route {
@service("todo-data") todos;
model() {
let todos = this.todos;
return {
get completedTodos() {
return todos.completed;
},
};
}
}
```
We can now update the `todomvc/app/templates/completed.hbs` file so that when it includes the `<TodoList />` component, it does so explicitly with the available model, calling its `completedTodos()` getter to make sure only the completed todos are shown.
In this file, change
```hbs
<TodoList />
```
To
```hbs-nolint
<TodoList @todos=\{{ @model.completedTodos }} />
```
### The active route model
Finally for the routes, let's sort out our active route. Start by updating `todomvc/app/routes/active.js` so it looks as follows:
```js
import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";
export default class ActiveRoute extends Route {
@service("todo-data") todos;
model() {
let todos = this.todos;
return {
get activeTodos() {
return todos.incomplete;
},
};
}
}
```
We can now update the `todomvc/app/templates/active.hbs` file so that when it includes the `<TodoList />` component, it does so explicitly with the available model, calling its `activeTodos()` getter to make sure only the active (incomplete) todos are shown.
In this file, change
```hbs
<TodoList />
```
To
```hbs-nolint
<TodoList @todos=\{{ @model.activeTodos }} />
```
Note that, in each of the route model hooks, we are returning an object with a getter instead of a static object, or more just the static list of todos (for example, `this.todos.completed`). The reason for this is that we want the template to have a dynamic reference to the todo list, and if we returned the list directly, the data would never re-compute, which would result in the navigations appearing to fail / not actually filter. By having a getter defined in the return object from the model data, the todos are re-looked-up so that our changes to the todo list are represented in the rendered list.
## Getting the footer links working
So our route functionality is now all in place, but we can't access them from our app. Let's get the footer links active so that clicking on them goes to the desired routes.
Go back to `todomvc/app/components/footer.hbs`, and find the following bit of markup:
```hbs
<a href="#">All</a>
<a href="#">Active</a>
<a href="#">Completed</a>
```
Update it to
```hbs
<LinkTo @route="index">All</LinkTo>
<LinkTo @route="active">Active</LinkTo>
<LinkTo @route="completed">Completed</LinkTo>
```
`<LinkTo>` is a built-in Ember component that handles all the state changes when navigating routes, as well as setting an "active" class on any link that matches the URL, in case there is a desire to style it differently from inactive links.
## Updating the todos display inside TodoList
One small final thing that we need to fix is that previously, inside `todomvc/app/components/todo-list.hbs`, we were accessing the todo-data service directly and looping over all todos, as shown here:
```hbs
\{{#each this.todos.all as |todo| }}
```
Since we now want to have our TodoList component show a filtered list, we'll want to pass an argument to the TodoList component representing the "current list of todos", as shown here:
```hbs
\{{#each @todos as |todo| }}
```
And that's it for this tutorial! Your app should now have fully working links in the footer that display the "Index"/default, "Active", and "Completed" routes.

## Summary
Congratulations! You've finished this tutorial!
There is a lot more to be implemented before what we've covered here has parity with the original [TodoMVC app](https://todomvc.com), such as editing, deleting, and persisting todos across page reloads.
To see our finished Ember implementation, checkout the finished app folder in the repository for [the code of this tutorial](https://github.com/NullVoxPopuli/ember-todomvc-tutorial/tree/master/steps/00-finished-todomvc/todomvc) or see the [live deployed version](https://nullvoxpopuli.github.io/ember-todomvc-tutorial/) here. Study the code to learn more about Ember, and also check out the next article, which provides links to more resources and some troubleshooting advice.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/react_components/index.md | ---
title: Componentizing our React app
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn't have any hard rules for what is and isn't a component – that's up to you! In this article we will show you a sensible way to break our app up into components.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To show a sensible way of breaking our todo list app into components.
</td>
</tr>
</tbody>
</table>
## Defining our first component
Defining a component can seem tricky until you have some practice, but the gist is:
- If it represents an obvious "chunk" of your app, it's probably a component
- If it gets reused often, it's probably a component.
That second bullet is especially valuable: making a component out of common UI elements allows you to change your code in one place and see those changes everywhere that component is used. You don't have to break everything out into components right away, either. Let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the UI: a todo list item.
## Make a `<Todo />`
Before we can make a component, we should create a new file for it. In fact, we should make a directory just for our components. Make sure you're in the root of your app before you run these commands!
```bash
# create a `components` directory
mkdir src/components
# within `components`, create a file called `Todo.jsx`
touch src/components/Todo.jsx
```
Don't forget to restart your development server if you stopped it to run the previous commands!
Let's add a `Todo()` function in `Todo.jsx`. Here, we define a function and export it:
```jsx
function Todo() {}
export default Todo;
```
This is OK so far, but our component should return something useful! Go back to `src/App.jsx`, copy the first [`<li>`](/en-US/docs/Web/HTML/Element/li) from inside the unordered list, and paste it into `Todo.jsx` so that it reads like this:
```jsx
function Todo() {
return (
<li className="todo stack-small">
<div className="c-cb">
<input id="todo-0" type="checkbox" defaultChecked />
<label className="todo-label" htmlFor="todo-0">
Eat
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">Eat</span>
</button>
<button type="button" className="btn btn__danger">
Delete <span className="visually-hidden">Eat</span>
</button>
</div>
</li>
);
}
export default Todo;
```
Now we have something we can use. In `App.jsx`, add the following line at the top of the file to import `Todo`:
```jsx
import Todo from "./components/Todo";
```
With this component imported, you can replace all of the `<li>` elements in `App.jsx` with `<Todo />` component calls. Your `<ul>` should read like this:
```jsx
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
<Todo />
<Todo />
<Todo />
</ul>
```
When you return to your app, you'll notice something unfortunate: your list now repeats the first task three times!

We don't only want to eat; we have other things to — well — to do. Next we'll look at how we can make different component calls render unique content.
## Make a unique `<Todo />`
Components are powerful because they let us re-use pieces of our UI, and refer to one place for the source of that UI. The problem is, we don't typically want to reuse all of each component; we want to reuse most parts, and change small pieces. This is where props come in.
### What's in a `name`?
In order to track the names of tasks we want to complete, we should ensure that each `<Todo />` component renders a unique name.
In `App.jsx`, give each `<Todo />` a name prop. Let's use the names of our tasks that we had before:
```jsx
<Todo name="Eat" />
<Todo name="Sleep" />
<Todo name="Repeat" />
```
When your browser refreshes, you will see… the exact same thing as before. We gave our `<Todo />` some props, but we aren't using them yet. Let's go back to `Todo.jsx` and remedy that.
First modify your `Todo()` function definition so that it takes `props` as a parameter. You can `console.log()` your props if you'd like to check that they are being received by the component correctly.
Once you're confident that your component is getting its props, you can replace every occurrence of `Eat` with your `name` prop by reading `props.name`. Remember: `props.name` is a JSX expression, so you'll need to wrap it in curly braces.
Putting all that together, your `Todo()` function should read like this:
```jsx
function Todo(props) {
return (
<li className="todo stack-small">
<div className="c-cb">
<input id="todo-0" type="checkbox" defaultChecked={true} />
<label className="todo-label" htmlFor="todo-0">
{props.name}
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">{props.name}</span>
</button>
<button type="button" className="btn btn__danger">
Delete <span className="visually-hidden">{props.name}</span>
</button>
</div>
</li>
);
}
export default Todo;
```
_Now_ your browser should show three unique tasks. Another problem remains though: they're all still checked by default.

### Is it `completed`?
In our original static list, only `Eat` was checked. Once again, we want to reuse _most_ of the UI that makes up a `<Todo />` component, but change one thing. That's a good job for another prop! Give your first `<Todo />` call a boolean prop of `completed`, and leave the other two as they are.
```jsx
<Todo name="Eat" completed />
<Todo name="Sleep" />
<Todo name="Repeat" />
```
As before, we must go back to `Todo.jsx` to actually use these props. Change the `defaultChecked` attribute on the `<input />` so that its value is equal to the `completed` prop. Once you're done, the Todo component's `<input />` element will read like this:
```jsx
<input id="todo-0" type="checkbox" defaultChecked={props.completed} />
```
And your browser should update to show only `Eat` being checked:

If you change each `<Todo />` component's `completed` prop, your browser will check or uncheck the equivalent rendered checkboxes accordingly.
### Gimme some `id`, please
We have still _another_ problem: our `<Todo />` component gives every task an `id` attribute of `todo-0`. This is bad for a couple of reasons:
- [`id` attributes](/en-US/docs/Web/HTML/Global_attributes/id) must be unique (they are used as unique identifiers for document fragments, by CSS, JavaScript, etc.).
- When `id`s are not unique, the functionality of [label elements](/en-US/docs/Web/HTML/Element/label) can break.
The second problem is affecting our app right now. If you click on the word "Sleep" next to the second checkbox, you'll notice the "Eat" checkbox toggles instead of the "Sleep" checkbox. This is because every checkbox's `<label>` element has an `htmlFor` attribute of `todo-0`. The `<label>`s only acknowledge the first element with a given `id` attribute, which causes the problem you see when clicking on the other labels.
We had unique `id` attributes before we created the `<Todo />` component. Let's bring them back, following the format of `todo-i`, where `i` gets larger by one every time. Update the `Todo` component instances inside `App.jsx` to add in `id` props, as follows:
```jsx
<Todo name="Eat" id="todo-0" completed />
<Todo name="Sleep" id="todo-1" />
<Todo name="Repeat" id="todo-2" />
```
> **Note:** The `completed` prop is last here because it is a boolean with no assignment. This is purely a stylistic convention. The order of props does not matter because props are JavaScript objects, and JavaScript objects are unordered.
Now go back to `Todo.jsx` and make use of the `id` prop. It needs to replace the `<input />` element's `id` attribute value, as well as its `<label>`'s `htmlFor` attribute value:
```jsx
<div className="c-cb">
<input id={props.id} type="checkbox" defaultChecked={props.completed} />
<label className="todo-label" htmlFor={props.id}>
{props.name}
</label>
</div>
```
With these fixes in place, clicking on the labels next to each checkbox will do what we expect – check and uncheck the checkboxes next to those labels.
## So far, so good?
We're making good use of React so far, but we could do better! Our code is repetitive. The three lines that render our `<Todo />` component are almost identical, with only one difference: the value of each prop.
We can clean up our code with one of JavaScript's core abilities: iteration. To use iteration, we should first re-think our tasks.
## Tasks as data
Each of our tasks currently contains three pieces of information: its name, whether it has been checked, and its unique ID. This data translates nicely to an object. Since we have more than one task, an array of objects would work well in representing this data.
In `src/main.jsx`, declare a new `const` beneath the final import, but above `ReactDOM.createRoot()`:
```jsx
const DATA = [
{ id: "todo-0", name: "Eat", completed: true },
{ id: "todo-1", name: "Sleep", completed: false },
{ id: "todo-2", name: "Repeat", completed: false },
];
```
> **Note:** If your text editor has an [ESLint](https://eslint.org/) plugin, you may see a warning on this `DATA` const. This warning comes from the ESLint configuration supplied by the Vite template we used, and it doesn't apply to this code. You can safely suppress the warning by adding `// eslint-disable-next-line` to the line above the `DATA` const.
Next, we'll pass `DATA` to `<App />` as a prop, called `tasks`. Update your `<App />` component call inside `src/main.jsx` to read like this:
```jsx
<App tasks={DATA} />
```
The `DATA` array is now available inside the App component as `props.tasks`. You can `console.log()` it to check, if you'd like.
> **Note:** `ALL_CAPS` constant names have no special meaning in JavaScript; they're a convention that tells other developers "this data will never change after being defined here".
## Rendering with iteration
To render our array of objects, we have to turn each object into a `<Todo />` component. JavaScript gives us an array method for transforming items into something else: [`Array.prototype.map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).
Inside `App.jsx`, create a new `const` above the `App()` function's `return` statement called `taskList`. Let's start by transforming each task in the `props.tasks` array into its `name`. The `?.` operator lets us perform [optional chaining](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) to check if `props.tasks` is `undefined` or `null` before attempting to create a new array of task names:
```jsx
const taskList = props.tasks?.map((task) => task.name);
```
Let's try replacing all the children of the `<ul>` with `taskList`:
```jsx
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
{taskList}
</ul>
```
This gets us some of the way towards showing all the components again, but we've got more work to do: the browser currently renders each task's name as plain text. We're missing our HTML structure — the `<li>` and its checkboxes and buttons!

To fix this, we need to return a `<Todo />` component from our `map()` function — remember that JSX is JavaScript, so we can use it alongside any other, more familiar JavaScript syntax. Let's try the following instead of what we have already:
```jsx
const taskList = props.tasks?.map((task) => <Todo />);
```
Look again at your app; now our tasks look more like they used to, but they're missing the names of the tasks themselves. Remember that each task we map over contains the `id`, `name`, and `completed` properties we want to pass into our `<Todo />` component. If we put that knowledge together, we get code like this:
```jsx
const taskList = props.tasks?.map((task) => (
<Todo id={task.id} name={task.name} completed={task.completed} />
));
```
Now the app looks like it did before, and our code is less repetitive.
## Unique keys
Now that React is rendering our tasks out of an array, it has to keep track of which one is which in order to render them properly. React tries to do its own guesswork to keep track of things, but we can help it out by passing a `key` prop to our `<Todo />` components. `key` is a special prop that's managed by React – you cannot use the word `key` for any other purpose.
Because keys should be unique, we're going to re-use the `id` of each task object as its key. Update your `taskList` constant like so:
```jsx
const taskList = props.tasks?.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
/>
));
```
**You should always pass a unique key to anything you render with iteration.** Nothing obvious will change in your browser, but if you do not use unique keys, React will log warnings to your console and your app may behave strangely!
## Componentizing the rest of the app
Now that we've got our most important component sorted out, we can turn the rest of our app into components. Remembering that components are either obvious pieces of UI, reused pieces of UI, or both, we can make two more components:
- `<Form />`
- `<FilterButton />`
Since we know we need both, we can batch some of the file creation work together in one terminal command. Run this command in your terminal, taking care that you're in the root directory of your app:
```bash
touch src/components/{Form,FilterButton}.jsx
```
### The `<Form />`
Open `components/Form.jsx` and do the following:
- Declare a `Form()` function and export it at the end of the file.
- Copy the `<form>` tags and everything between them from inside `App.jsx`, and paste them inside `Form()`'s `return` statement.
Your `Form.jsx` file should read like this:
```jsx
function Form() {
return (
<form>
<h2 className="label-wrapper">
<label htmlFor="new-todo-input" className="label__lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
className="input input__lg"
name="text"
autoComplete="off"
/>
<button type="submit" className="btn btn__primary btn__lg">
Add
</button>
</form>
);
}
export default Form;
```
### The `<FilterButton />`
Do the same things you did to create `Form.jsx` inside `FilterButton.jsx`, but call the component `FilterButton()` and copy the HTML for the first button inside `<div className="filters btn-group stack-exception">` from `App.jsx` into the `return` statement.
The file should read like this:
```jsx
function FilterButton() {
return (
<button type="button" className="btn toggle-btn" aria-pressed="true">
<span className="visually-hidden">Show </span>
<span>all </span>
<span className="visually-hidden"> tasks</span>
</button>
);
}
export default FilterButton;
```
> **Note:** You might notice that we are making the same mistake here as we first made for the `<Todo />` component, in that each button will be the same. That's fine! We're going to fix up this component later on, in [Back to the filter buttons](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering#back_to_the_filter_buttons).
## Importing all our components
Let's make use of our new components. Add some more `import` statements to the top of `App.jsx` and reference the components we've just made. Then, update the `return` statement of `App()` so that it renders our components.
When you're done, `App.jsx` will read like this:
```jsx
import Form from "./components/Form";
import FilterButton from "./components/FilterButton";
import Todo from "./components/Todo";
function App(props) {
const taskList = props.tasks?.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
/>
));
return (
<div className="todoapp stack-large">
<h1>TodoMatic</h1>
<Form />
<div className="filters btn-group stack-exception">
<FilterButton />
<FilterButton />
<FilterButton />
</div>
<h2 id="list-heading">3 tasks remaining</h2>
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
{taskList}
</ul>
</div>
);
}
export default App;
```
With this in place, your React app should render basically the same as it did before, but using your shiny new components.
## Summary
And that's it for this article — we've gone into depth on how to break up your app nicely into components and render them efficiently. Next we'll look at handling events in React, and start adding some interactivity.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/svelte_components/index.md | ---
title: Componentizing our Svelte app
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In the last article we started developing our to-do list app. The central objective of this article is to look at how to break our app into manageable components and share information between them. We'll componentize our app, then add more functionality to allow users to update existing components.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
You'll need a terminal with node and npm installed to compile and build
your app.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to break our app into components and share information
among them.
</td>
</tr>
</tbody>
</table>
## Code along with us
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/04-componentizing-our-app
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/04-componentizing-our-app
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
<https://svelte.dev/repl/99b9eb228b404a2f8c8959b22c0a40d3?version=3.23.2>
## Breaking the app into components
In Svelte, an application is composed from one or more components. A component is a reusable, self-contained block of code that encapsulates HTML, CSS, and JavaScript that belong together, written into a `.svelte` file. Components can be big or small, but they are usually clearly defined: the most effective components serve a single, obvious purpose.
The benefits of defining components are comparable to the more general best practice of organizing your code into manageable pieces. It will help you understand how they relate to each other, it will promote reuse, and it will make your code easier to reason about, maintain, and extend.
But how do you know what should be split into its own component?
There are no hard rules for this. Some people prefer an intuitive approach and start looking at the markup and drawing boxes around every component and subcomponent that seems to have its own logic.
Other people apply the same techniques used for deciding if you should create a new function or object. One such technique is the single responsibility principle — that is, a component should ideally only do one thing. If it ends up growing, it should be split into smaller subcomponents.
Both approaches should complement each other, and help you decide how to better organize your components.
Eventually, we will split up our app into the following components:
- `Alert.svelte`: A general notification box for communicating actions that have occurred.
- `NewTodo.svelte`: The text input and button that allow you to enter a new to-do item.
- `FilterButton.svelte`: The _All_, _Active_, and _Completed_ buttons that allow you to apply filters to the displayed to-do items.
- `TodosStatus.svelte`: The "x out of y items completed" heading.
- `Todo.svelte`: An individual to-do item. Each visible to-do item will be displayed in a separate copy of this component.
- `MoreActions.svelte`: The _Check All_ and _Remove Completed_ buttons at the bottom of the UI that allow you to perform mass actions on the to-do items.

In this article we will concentrate on creating the `FilterButton` and `Todo` components; we'll get to the others in future articles.
Let's get started.
> **Note:** In the process of creating our first couple of components, we will also learn different techniques to communicate between components, and the pros and cons of each.
## Extracting our filter component
We'll begin by creating our `FilterButton.svelte`.
1. First of all, create a new file, `components/FilterButton.svelte`.
2. Inside this file we will declare a `filter` prop, and then copy the relevant markup over to it from `Todos.svelte`. Add the following content into the file:
```svelte
<script>
export let filter = 'all'
</script>
<div class="filters btn-group stack-exception">
<button class="btn toggle-btn" class:btn__primary={filter === 'all'} aria-pressed={filter === 'all'} on:click={() => filter = 'all'} >
<span class="visually-hidden">Show</span>
<span>All</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn__primary={filter === 'active'} aria-pressed={filter === 'active'} on:click={() => filter = 'active'} >
<span class="visually-hidden">Show</span>
<span>Active</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn__primary={filter === 'completed'} aria-pressed={filter === 'completed'} on:click={() => filter = 'completed'} >
<span class="visually-hidden">Show</span>
<span>Completed</span>
<span class="visually-hidden">tasks</span>
</button>
</div>
```
3. Back in our `Todos.svelte` component, we want to make use of our `FilterButton` component. First of all, we need to import it. Add the following line at the top of the `Todos.svelte <script>` section:
```js
import FilterButton from "./FilterButton.svelte";
```
4. Now replace the `<div class="filters...` element with a call to the `FilterButton` component, which takes the current filter as a prop. The below line is all you need:
```svelte
<FilterButton {filter} />
```
> **Note:** Remember that when the HTML attribute name and variable match, they can be replaced with `{variable}`. That's why we could replace `<FilterButton filter={filter} />` with `<FilterButton {filter} />`.
So far so good! Let's try out the app now. You'll notice that when you click on the filter buttons, they are selected and the style updates appropriately. But we have a problem: the to-dos aren't filtered. That's because the `filter` variable flows down from the `Todos` component to the `FilterButton` component through the prop, but changes occurring in the `FilterButton` component don't flow back up to its parent — the data binding is one-way by default. Let's look at a way to solve this.
## Sharing data between components: passing a handler as a prop
One way to let child components notify their parents of any changes is to pass a handler as a prop. The child component will execute the handler, passing the needed information as a parameter, and the handler will modify the parent's state.
In our case, the `FilterButton` component will receive an `onclick` handler from its parent. Whenever the user clicks on any filter button, the child will call the `onclick` handler, passing the selected filter as a parameter back up to its parent.
We will just declare the `onclick` prop assigning a dummy handler to prevent errors, like this:
```js
export let onclick = (clicked) => {};
```
And we'll declare the reactive statement `$: onclick(filter)` to call the `onclick` handler whenever the `filter` variable is updated.
1. The `<script>` section of our `FilterButton` component should end up looking like this. Update it now:
```js
export let filter = "all";
export let onclick = (clicked) => {};
$: onclick(filter);
```
2. Now when we call `FilterButton` inside `Todos.svelte`, we'll need to specify the handler. Update it like this:
```svelte
<FilterButton {filter} onclick={ (clicked) => filter = clicked }/>
```
When any filter button is clicked, we just update the filter variable with the new filter. Now our `FilterButton` component will work again.
## Easier two-way data binding with the bind directive
In the previous example we realized that our `FilterButton` component wasn't working because our application state was flowing down from parent to child through the `filter` prop, but it wasn't going back up. So we added an `onclick` prop to let the child component communicate the new `filter` value to its parent.
It works OK, but Svelte provides us with an easier and more straightforward way to achieve two-way data binding. Data ordinarily flows down from parent to child using props. If we want it to also flow the other way, from child to parent, we can use [the `bind:` directive](https://svelte.dev/docs/element-directives#bind-property).
Using `bind`, we will tell Svelte that any changes made to the `filter` prop in the `FilterButton` component should propagate back up to the parent component, `Todos`. That is, we will bind the `filter` variable's value in the parent to its value in the child.
1. In `Todos.svelte`, update the call to the `FilterButton` component as follows:
```svelte
<FilterButton bind:filter={filter} />
```
As usual, Svelte provides us with a nice shorthand: `bind:value={value}` is equivalent to `bind:value`. So in the above example you could just write `<FilterButton bind:filter />`.
2. The child component can now modify the value of the parent's filter variable, so we no longer need the `onclick` prop. Modify the `<script>` element of your `FilterButton` like this:
```svelte
<script>
export let filter = "all";
</script>
```
3. Try your app again, and you should still see your filters working correctly.
## Creating our Todo component
Now we will create a `Todo` component to encapsulate each individual to-do, including the checkbox and some editing logic so you can change an existing to-do.
Our `Todo` component will receive a single `todo` object as a prop. Let's declare the `todo` prop and move the code from the `Todos` component. Just for now, we'll replace the call to `removeTodo` with an alert. We'll add that functionality back in later on.
1. Create a new component file, `components/Todo.svelte`.
2. Put the following contents inside this file:
```svelte
<script>
export let todo
</script>
<div class="stack-small">
<div class="c-cb">
<input type="checkbox" id="todo-{todo.id}"
on:click={() => todo.completed = !todo.completed}
checked={todo.completed}
/>
<label for="todo-{todo.id}" class="todo-label">{todo.name}</label>
</div>
<div class="btn-group">
<button type="button" class="btn">
Edit <span class="visually-hidden">{todo.name}</span>
</button>
<button type="button" class="btn btn__danger" on:click={() => alert('not implemented')}>
Delete <span class="visually-hidden">{todo.name}</span>
</button>
</div>
</div>
```
3. Now we need to import our `Todo` component into `Todos.svelte`. Go to this file now, and add the following `import` statement below your previous one:
```js
import Todo from "./Todo.svelte";
```
4. Next we need to update our `{#each}` block to include a `<Todo>` component for each to-do, rather than the code that has been moved out to `Todo.svelte`. We are also passing the current `todo` object into the component as a prop.
Update the `{#each}` block inside `Todos.svelte` like so:
```svelte
<ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
{#each filterTodos(filter, todos) as todo (todo.id)}
<li class="todo">
<Todo {todo} />
</li>
{:else}
<li>Nothing to do here!</li>
{/each}
</ul>
```
The list of to-dos is displayed on the page, and the checkboxes should work (try checking/unchecking a couple, and then observing that the filters still work as expected), but our "x out of y items completed" status heading will no longer update accordingly. That's because our `Todo` component is receiving the to-do via the prop, but it's not sending any information back to its parent. We'll fix this later on.
## Sharing data between components: props-down, events-up pattern
The `bind` directive is pretty straightforward and allows you to share data between a parent and child component with minimal fuss. However, when your application grows larger and more complex, it can easily get difficult to keep track of all your bound values. A different approach is the "props-down, events-up" communication pattern.
Basically, this pattern relies on child components receiving data from their parents via props and parent components updating their state by handling events emitted from child components. So props _flow down_ from parent to child and events _bubble up_ from child to parent. This pattern establishes a two-way flow of information, which is predictable and easier to reason about.
Let's look at how to emit our own events to re-implement the missing _Delete_ button functionality.
To create custom events, we'll use the `createEventDispatcher` utility. This will return a `dispatch()` function that will allow us to emit custom events. When you dispatch an event, you have to pass the name of the event and, optionally, an object with additional information that you want to pass to every listener. This additional data will be available on the `detail` property of the event object.
> **Note:** Custom events in Svelte share the same API as regular DOM events. Moreover, you can bubble up an event to your parent component by specifying `on:event` without any handler.
We'll edit our `Todo` component to emit a `remove` event, passing the to-do being removed as additional information.
1. First of all, add the following lines to the top of the `Todo` component's `<script>` section:
```js
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
```
2. Now update the _Delete_ button in the markup section of the same file to look like so:
```svelte
<button type="button" class="btn btn__danger" on:click={() => dispatch('remove', todo)}>
Delete <span class="visually-hidden">{todo.name}</span>
</button>
```
With `dispatch('remove', todo)` we are emitting a `remove` event, and passing as additional data the `todo` being deleted. The handler will be called with an event object available, with the additional data available in the `event.detail` property.
3. Now we have to listen to that event from inside `Todos.svelte` and act accordingly. Go back to this file and update your `<Todo>` component call like so:
```svelte
<Todo {todo} on:remove={(e) => removeTodo(e.detail)} />
```
Our handler receives the `e` parameter (the event object), which as described before holds the to-do being deleted in the `detail` property.
4. At this point, if you try out your app again, you should see that the _Delete_ functionality now works again. So our custom event has worked as we hoped. In addition, the `remove` event listener is sending the data change back up to the parent, so our "x out of y items completed" status heading will now update appropriately when to-dos are deleted.
Now we'll take care of the `update` event, so that our parent component can get notified of any modified to-do.
## Updating to-dos
We still have to implement functionality to allow us to edit existing to-dos. We'll have to include an editing mode in the `Todo` component. When entering editing mode, we'll show an `<input>` field to allow us to edit the current to-do name, with two buttons to confirm or cancel our changes.
### Handling the events
1. We'll need one variable to track whether we are in editing mode and another to store the name of the task being updated. Add the following variable definitions at the bottom of the `<script>` section of the `Todo` component:
```js
let editing = false; // track editing mode
let name = todo.name; // hold the name of the to-do being edited
```
2. We have to decide what events our `Todo` component will emit:
- We could emit different events for the status toggle and editing of the name (for example, `updateTodoStatus` and `updateTodoName`).
- Or we could take a more generic approach and emit a single `update` event for both operations.
We will take the second approach so that we can demonstrate a different technique. The advantage of this approach is that later we can add more fields to the to-dos and still handle all updates with the same event.
Let's create an `update()` function that will receive the changes and will emit an update event with the modified to-do. Add the following, again to the bottom of the `<script>` section:
```js
function update(updatedTodo) {
todo = { ...todo, ...updatedTodo }; // applies modifications to todo
dispatch("update", todo); // emit update event
}
```
Here we are using the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) to return the original to-do with the modifications applied to it.
3. Next we'll create different functions to handle each user action. When the to-do is in editing mode, the user can save or cancel the changes. When it's not in editing mode, the user can delete the to-do, edit it, or toggle its status between completed and active.
Add the following set of functions below your previous function to handle these actions:
```js
function onCancel() {
name = todo.name; // restores name to its initial value and
editing = false; // and exit editing mode
}
function onSave() {
update({ name }); // updates todo name
editing = false; // and exit editing mode
}
function onRemove() {
dispatch("remove", todo); // emit remove event
}
function onEdit() {
editing = true; // enter editing mode
}
function onToggle() {
update({ completed: !todo.completed }); // updates todo status
}
```
### Updating the markup
Now we need to update our `Todo` component's markup to call the above functions when the appropriate actions are taken.
To handle the editing mode, we are using the `editing` variable, which is a boolean. When it's `true`, it should display the `<input>` field for editing the to-do name, and the _Cancel_ and _Save_ buttons. When it's not in editing mode, it will display the checkbox, the to-do name, and the buttons to edit and delete the to-do.
To achieve this we will use an [`if` block](https://svelte.dev/docs/logic-blocks#if). The `if` block conditionally renders some markup. Take into account that it won't just show or hide the markup based on the condition — it will dynamically add and remove the elements from the DOM, depending on the condition.
When `editing` is `true`, for example, Svelte will show the update form; when it's `false`, it will remove it from the DOM and add in the checkbox. Thanks to Svelte reactivity, assigning the value of the editing variable will be enough to display the correct HTML elements.
The following gives you an idea of what the basic `if` block structure looks like:
```svelte
<div class="stack-small">
{#if editing}
<!-- markup for editing to-do: label, input text, Cancel and Save Button -->
{:else}
<!-- markup for displaying to-do: checkbox, label, Edit and Delete Button -->
{/if}
</div>
```
The non-editing section — that is, the `{:else}` part (lower half) of the `if` block — will be very similar to the one we had in our `Todos` component. The only difference is that we are calling `onToggle()`, `onEdit()`, and `onRemove()`, depending on the user action.
```svelte
{:else}
<div class="c-cb">
<input type="checkbox" id="todo-{todo.id}"
on:click={onToggle} checked={todo.completed}
>
<label for="todo-{todo.id}" class="todo-label">{todo.name}</label>
</div>
<div class="btn-group">
<button type="button" class="btn" on:click={onEdit}>
Edit<span class="visually-hidden"> {todo.name}</span>
</button>
<button type="button" class="btn btn__danger" on:click={onRemove}>
Delete<span class="visually-hidden"> {todo.name}</span>
</button>
</div>
{/if}
</div>
```
It is worth noting that:
- When the user presses the _Edit_ button, we execute `onEdit()`, which just sets the `editing` variable to `true`.
- When the user clicks on the checkbox, we call the `onToggle()` function, which executes `update()`, passing an object with the new `completed` value as a parameter.
- The `update()` function emits the `update` event, passing as additional information a copy of the original to-do with the changes applied.
- Finally, the `onRemove()` function emits the `remove` event, passing the `todo` to be deleted as additional data.
The editing UI (the upper half) will contain an `<input>` field and two buttons to cancel or save the changes:
```svelte
<div class="stack-small">
{#if editing}
<form on:submit|preventDefault={onSave} class="stack-small" on:keydown={(e) => e.key === 'Escape' && onCancel()}>
<div class="form-group">
<label for="todo-{todo.id}" class="todo-label">New name for '{todo.name}'</label>
<input bind:value={name} type="text" id="todo-{todo.id}" autoComplete="off" class="todo-text" />
</div>
<div class="btn-group">
<button class="btn todo-cancel" on:click={onCancel} type="button">
Cancel<span class="visually-hidden">renaming {todo.name}</span>
</button>
<button class="btn btn__primary todo-edit" type="submit" disabled={!name}>
Save<span class="visually-hidden">new name for {todo.name}</span>
</button>
</div>
</form>
{:else}
[...]
```
When the user presses the _Edit_ button, the `editing` variable will be set to `true`, and Svelte will remove the markup in the `{:else}` part of the DOM and replace it with the markup in the `{#if}` section.
The `<input>`'s `value` property will be bound to the `name` variable, and the buttons to cancel and save the changes call `onCancel()` and `onSave()` respectively (we added those functions earlier):
- When `onCancel()` is invoked, `name` is restored to its original value (when passed in as a prop) and we exit editing mode (by setting `editing` to `false`).
- When `onSave()` in invoked, we run the `update()` function — passing it the modified `name` — and exit editing mode.
We also disable the _Save_ button when the `<input>` is empty, using the `disabled={!name}` attribute, and allow the user to cancel the edit using the <kbd>Escape</kbd> key, like this:
```plain
on:keydown={(e) => e.key === 'Escape' && onCancel()}
```
We also use `todo.id` to create unique ids for the new input controls and labels.
1. The complete updated markup of our `Todo` component looks like the following. Update yours now:
```svelte
<div class="stack-small">
{#if editing}
<!-- markup for editing todo: label, input text, Cancel and Save Button -->
<form on:submit|preventDefault={onSave} class="stack-small" on:keydown={(e) => e.key === 'Escape' && onCancel()}>
<div class="form-group">
<label for="todo-{todo.id}" class="todo-label">New name for '{todo.name}'</label>
<input bind:value={name} type="text" id="todo-{todo.id}" autoComplete="off" class="todo-text" />
</div>
<div class="btn-group">
<button class="btn todo-cancel" on:click={onCancel} type="button">
Cancel<span class="visually-hidden">renaming {todo.name}</span>
</button>
<button class="btn btn__primary todo-edit" type="submit" disabled={!name}>
Save<span class="visually-hidden">new name for {todo.name}</span>
</button>
</div>
</form>
{:else}
<!-- markup for displaying todo: checkbox, label, Edit and Delete Button -->
<div class="c-cb">
<input type="checkbox" id="todo-{todo.id}"
on:click={onToggle} checked={todo.completed}
>
<label for="todo-{todo.id}" class="todo-label">{todo.name}</label>
</div>
<div class="btn-group">
<button type="button" class="btn" on:click={onEdit}>
Edit<span class="visually-hidden"> {todo.name}</span>
</button>
<button type="button" class="btn btn__danger" on:click={onRemove}>
Delete<span class="visually-hidden"> {todo.name}</span>
</button>
</div>
{/if}
</div>
```
> **Note:** We could further split this into two different components, one for editing the to-do and the other for displaying it. In the end, it boils down to how comfortable you feel dealing with this level of complexity in a single component. You should also consider whether splitting it further would enable reusing this component in a different context.
2. To get the update functionality working, we have to handle the `update` event from the `Todos` component. In its `<script>` section, add this handler:
```js
function updateTodo(todo) {
const i = todos.findIndex((t) => t.id === todo.id);
todos[i] = { ...todos[i], ...todo };
}
```
We find the `todo` by `id` in our `todos` array, and update its content using spread syntax. In this case we could have also just used `todos[i] = todo`, but this implementation is more bullet-proof, allowing the `Todo` component to return only the updated parts of the to-do.
3. Next we have to listen for the `update` event on our `<Todo>` component call, and run our `updateTodo()` function when this occurs to change the `name` and `completed` status. Update your \<Todo> call like this:
```svelte
{#each filterTodos(filter, todos) as todo (todo.id)}
<li class="todo">
<Todo {todo} on:update={(e) => updateTodo(e.detail)} on:remove={(e) =>
removeTodo(e.detail)} />
</li>
```
4. Try your app again, and you should see that you can delete, add, edit, cancel editing of, and toggle completion status of to-dos. And our "x out of y items completed" status heading will now update appropriately when to-dos are completed.
As you can see, it's easy to implement the "props-down, events-up" pattern in Svelte. Nevertheless, for simple components `bind` can be a good choice; Svelte will let you choose.
> **Note:** Svelte provides more advanced mechanisms to share information among components: the [Context API](https://svelte.dev/docs/svelte#setcontext) and [Stores](https://svelte.dev/docs/svelte-store). The Context API provides a mechanism for components and their descendants to "talk" to each other without passing around data and functions as props, or dispatching lots of events. Stores allows you to share reactive data among components that are not hierarchically related. We will look at Stores later on in the series.
## The code so far
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/05-advanced-concepts
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/05-advanced-concepts
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To see the current state of the code in a REPL, visit:
<https://svelte.dev/repl/76cc90c43a37452e8c7f70521f88b698?version=3.23.2>
## Summary
Now we have all of our app's required functionality in place. We can display, add, edit, and delete to-dos, mark them as completed, and filter by status.
In this article, we covered the following topics:
- Extracting functionality to a new component
- Passing information from child to parent using a handler received as a prop
- Passing information from child to parent using the `bind` directive
- Conditionally rendering blocks of markup using the `if` block
- Implementing the "props-down, events-up" communication pattern
- Creating and listening to custom events
In the next article we will continue componentizing our app and look at some advanced techniques for working with the DOM.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/angular_styling/index.md | ---
title: Styling our Angular app
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_styling
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_item_component", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Now that we've got our basic application structure set up and started displaying something useful, let's switch gears and spend an article looking at how Angular handles styling of applications.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn how to style an Angular app.</td>
</tr>
</tbody>
</table>
## Adding some style to Angular
The Angular CLI generates two types of style files:
- Component styles: The Angular CLI gives each component its own file for styles.
The styles in this file apply only to its component.
- `styles.css`: In the `src` directory, the styles in this file apply to your entire application unless you specify styles at the component level.
Depending on whether you are using a CSS preprocessor, the extension on your CSS files can vary.
Angular supports plain CSS, SCSS, Sass, Less, and Stylus.
In `src/styles.css`, paste the following styles:
```css
body {
font-family: Helvetica, Arial, sans-serif;
}
.btn-wrapper {
/* flexbox */
display: flex;
flex-wrap: nowrap;
justify-content: space-between;
}
.btn {
color: #000;
background-color: #fff;
border: 2px solid #cecece;
padding: 0.35rem 1rem 0.25rem 1rem;
font-size: 1rem;
}
.btn:hover {
background-color: #ecf2fd;
}
.btn:active {
background-color: #d1e0fe;
}
.btn:focus {
outline: none;
border: black solid 2px;
}
.btn-primary {
color: #fff;
background-color: #000;
width: 100%;
padding: 0.75rem;
font-size: 1.3rem;
border: black solid 2px;
margin: 1rem 0;
}
.btn-primary:hover {
background-color: #444242;
}
.btn-primary:focus {
color: #000;
outline: none;
border: #000 solid 2px;
background-color: #d7ecff;
}
.btn-primary:active {
background-color: #212020;
}
```
The CSS in `src/styles.css` apply to the entire application, however, these styles don't affect everything on the page.
The next step is to add styles that apply specifically to the `AppComponent`.
In `app.component.css`, add the following styles:
```css
.main {
max-width: 500px;
width: 85%;
margin: 2rem auto;
padding: 1rem;
text-align: center;
box-shadow:
0 2px 4px 0 rgb(0 0 0 / 20%),
0 2.5rem 5rem 0 rgb(0 0 0 / 10%);
}
@media screen and (min-width: 600px) {
.main {
width: 70%;
}
}
label {
font-size: 1.5rem;
font-weight: bold;
display: block;
padding-bottom: 1rem;
}
.lg-text-input {
width: 100%;
padding: 1rem;
border: 2px solid #000;
display: block;
box-sizing: border-box;
font-size: 1rem;
}
.btn-wrapper {
margin-bottom: 2rem;
}
.btn-menu {
flex-basis: 32%;
}
.active {
color: green;
}
ul {
padding-inline-start: 0;
}
ul li {
list-style: none;
}
```
The last step is to revisit your browser and look at how the styling has updated. Things now make a bit more sense.
## Summary
Now that our brief tour of styling in Angular is done with, let's return to creating our app functionality. In the next article we will create a proper component for to-do items, and make it so that you can check, edit, and delete to-do items.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_item_component", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/svelte_typescript/index.md | ---
title: TypeScript support in Svelte
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In the last article we learned about Svelte stores and even implemented our own custom store to persist the app's information to Web Storage. We also had a look at using the transition directive to implement animations on DOM elements in Svelte.
We will now learn how to use TypeScript in Svelte applications. First we'll learn what TypeScript is and what benefits it can bring us. Then we'll see how to configure our project to work with TypeScript files. Finally we will go over our app and see what modifications we have to make to fully take advantage of TypeScript features.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
You'll need a terminal with node and npm installed to compile and build
your app.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
Learn how to configure and use TypeScript when developing Svelte
applications.
</td>
</tr>
</tbody>
</table>
Note that our application is fully functional, and porting it to TypeScript is completely optional. There are different opinions about it, and in this chapter we will talk briefly about the pros and cons of using TypeScript. Even if you are not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. If you are not interested at all in TypeScript, you can skip to the next chapter, where we will look at different options for deploying our Svelte applications, further resources, and more.
## Code along with us
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/07-typescript-support
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/07-typescript-support
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
Unfortunately, [TypeScript support is not yet available in the REPL](https://github.com/sveltejs/sites/issues/156).
## TypeScript: optional static typing for JavaScript
[TypeScript](https://www.typescriptlang.org/) is a superset of JavaScript that provides features such as optional static typing, classes, interfaces, and generics. The goal of TypeScript is to help catch mistakes early through its type system and make JavaScript development more efficient. One of the big benefits is enabling IDEs to provide a richer environment for spotting common errors as you type the code.
Best of all, JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript. You can rename most of your `.js` files to `.ts` files and they will just work.
Our TypeScript code will be able to run everywhere JavaScript can run. How is that possible? TypeScript "transpiles" our code to vanilla JavaScript. That means that it parses TypeScript code and produces the equivalent vanilla JavaScript code for browsers to run.
> **Note:** If you are curious about how TypeScript transpiles our code to JavaScript, you can have a look at the [TypeScript Playground](https://www.typescriptlang.org/play/?target=1&e=4#example/hello-world).
First-class TypeScript support has been Svelte's most requested feature for quite some time. Thanks to the hard work of the Svelte team, together with many contributors, we have an [official solution](https://svelte.dev/blog/svelte-and-typescript) ready to be put to the test. In this section we'll show you how to set up a Svelte project with TypeScript support to give it a try.
## Why TypeScript?
TypeScript's main advantages are:
- Early spotted bugs: The compiler checks types at compile time and provides error reporting.
- Readability: Static typing gives the code more structure, making it self-documenting and more readable.
- Rich IDE support: Type information allows code editors and IDEs to offer features like code navigation, autocompletion, and smarter hints.
- Safer refactoring: Types allows IDEs to know more about your code, and assist you while refactoring large portions of your code base.
- Type inference: Enables you to take advantage of many TypeScript features even without declaring variable types.
- Availability of new and future JavaScript features: TypeScript transpiles many recent JavaScript features to plain old-school JavaScript, allowing you to use them even on user-agents that don't support them natively yet.
TypeScript also has some disadvantages:
- Not true static typing: Types are only checked at compile time, and they are removed from the generated code.
- Steep learning curve: Even though TypeScript is a superset of JavaScript and not a completely new language, there is a considerable learning curve, especially if you have no experience at all with static languages like Java or C#.
- More code: You have to write and maintain more code.
- No replacement for automatic tests: Even though types might help you catch several bugs, TypeScript is not a true replacement for a comprehensive suite of automated tests.
- Boilerplate code: Working with types, classes, interfaces, and generics can lead to over-engineered code bases.
There seems to be a broad consensus that TypeScript is particularly well suited for large-scale projects, with many developers working on the same codebase. And it is indeed being used by several large-scale projects, like Angular 2, Vue 3, Ionic, Visual Studio Code, Jest, and even the Svelte compiler. Nevertheless, some developers prefer to use it even on small projects like the one we are developing.
In the end, it's your decision. In the following sections we hope to give you more evidence to make up your mind about it.
## Creating a Svelte TypeScript project from scratch
You can start a new Svelte TypeScript project using the [standard template](https://github.com/sveltejs/template). All you have to do is run the following terminal commands (run them somewhere where you are storing your Svelte test projects — it creates a new directory):
```bash
npx degit sveltejs/template svelte-typescript-app
cd svelte-typescript-app
node scripts/setupTypeScript.js
```
This creates a starter project that includes TypeScript support, which you can then modify as you wish.
Then you'll have to tell npm to download dependencies and start the project in development mode, as we usually do:
```bash
npm install
npm run dev
```
## Adding TypeScript support to an existing Svelte Project
To add TypeScript support to an existing Svelte project, you can [follow these instructions](https://svelte.dev/blog/svelte-and-typescript#Adding_TypeScript_to_an_existing_project). Alternatively, you can download the [`setupTypeScript.js`](https://github.com/sveltejs/template/blob/master/scripts/setupTypeScript.js) file to a `scripts` folder inside your project's root folder, and then run `node scripts/setupTypeScript.js`.
You can even use `degit` to download the script. That's what we will do to start porting our application to TypeScript.
> **Note:** Remember that you can run `npx degit opensas/mdn-svelte-tutorial/07-typescript-support svelte-todo-typescript` to get the complete to-do list application in JavaScript before you start porting it to TypeScript.
Go to the root directory of the project and enter these commands:
```bash
npx degit sveltejs/template/scripts scripts # download script file to a scripts folder
node scripts/setupTypeScript.js # run it
# Converted to TypeScript.
```
You will need to re-run your dependency manager to get started.
```bash
npm install # download new dependencies
npm run dev # start the app in development mode
```
These instructions apply to any Svelte project you'd like to convert to TypeScript. Just take into account that the Svelte community is constantly improving Svelte TypeScript support, so you should run `npm update` regularly to take advantage of the latest changes.
> **Note:** if you find any trouble working with TypeScript inside a Svelte application, have a look at this [troubleshooting/FAQ section about TypeScript support](https://github.com/sveltejs/language-tools/blob/master/docs/preprocessors/typescript.md#troubleshooting--faq).
As we said before, TypeScript is a superset of JavaScript, so your application will run without modifications. Currently you will be running a regular JavaScript application with TypeScript support enabled, without taking advantage of any of the features that TypeScript provides. You can now start adding types progressively.
Once you have TypeScript configured, you can start using it from a Svelte component by just adding a `<script lang='ts'>` at the beginning of the script section. To use it from regular JavaScript files, just change the file extension from `.js` to `.ts`. You'll also have to update any corresponding import statements to remove the `.ts` file extension from all `import` statements.
> **Note:** Typescript will throw an error if you use the `.ts` file extension in an `import` statement, so you if you have a file `./foo.ts`, you must import it as "./foo".
> See the [Module resolution for bundlers, TypeScript runtimes, and Node.js loaders](https://www.typescriptlang.org/docs/handbook/2/modules.html##module-resolution-for-bundlers-typescript-runtimes-and-nodejs-loaders) section of the TypeScript manual for more information.
> **Note:** Using TypeScript in component markup sections is [not supported yet](https://github.com/sveltejs/svelte/issues/4701). You'll have to use JavaScript from the markup, and TypeScript in the `<script lang='ts'>` section.
## Improved developer experience with TypeScript
TypeScript provides code editors and IDEs with lots of information to allow them to deliver a friendlier development experience.
We'll use [Visual Studio Code](https://code.visualstudio.com/) to do a quick test and see how we can get autocompletion hints and type-checking as we're writing components.
> **Note:** If you don't wish to use VS Code, we also provide instructions for using TypeScript error checking from the terminal instead, slightly later on.
There is work in progress to support TypeScript in Svelte projects in several code editors; the most complete support so far is available in the [Svelte for VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode), which is developed and maintained by the Svelte team. This extension offers type checking, inspecting, refactoring, intellisense, hover-information, auto-completion, and other features. This kind of developer assistance is another good reason to start using TypeScript in your projects.
> **Note:** Make sure you are using [Svelte for VS Code](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) and NOT the old "Svelte" by James Birtles, which has been discontinued. In case you have it installed, you should uninstall it and install the official Svelte extension instead.
Assuming you are inside the VS Code application, from the root of your project's folder, type `code .` (the trailing dot tells VS Code to open the current folder) to open the code editor. VS Code will tell you that there are recommended extensions to install.

Clicking _Install all_ will install Svelte for VS Code.

We can also see that the `setupTypeScript.js` file made a couple of changes to our project. The `main.js` file has been renamed to `main.ts`, which means that VS Code can provide hover-information on our Svelte components:

We also get type checking for free. If we pass an unknown property in the options parameter of the `App` constructor (for example a typo like `traget` instead of `target`), TypeScript will complain:

In the `App.svelte` component, the `setupTypeScript.js` script has added the `lang="ts"` attribute to the `<script>` tag. Moreover, thanks to type inference, in many cases we won't even need to specify types to get code assistance. For example, if you start adding an `ms` property to the `Alert` component call, TypeScript will infer from the default value that the `ms` property should be a number:

And if you pass something that is not a number, it will complain about it:

The application template has a `check` script configured that runs `svelte-check` against your code. This package allows you to detect errors and warnings normally displayed by a code editor from the command line, which makes it pretty useful for running it in a continuous integration (CI) pipeline. Just run `npm run check` to check for unused CSS, and return A11y hints and TypeScript compile errors.
In this case, if you run `npm run check` (either in the VS Code console or terminal) you will get the following error:

Even better, if you run it from the VS Code integrated terminal (you can open it with the <kbd>Ctrl</kbd> + <kbd>\`</kbd> keyboard shortcut), <kbd>Cmd</kbd>/<kbd>Ctrl</kbd> clicking on the file name will take you to the line containing the error.
You can also run the `check` script in watch mode with `npm run check -- --watch`. In this case, the script will execute whenever you change any file. If you are running this in your regular terminal, keep it running in the background in a separate terminal window so that it can keep reporting errors but won't interfere with other terminal usage.
## Creating a custom type
TypeScript supports structural typing. Structural typing is a way of relating types based solely on their members, even if you do not explicitly define the type.
We'll define a `TodoType` type to see how TypeScript enforces that anything passed to a component expecting a `TodoType` will be structurally compatible with it.
1. Inside the `src` folder create a `types` folder.
2. Add a `todo.type.ts` file inside it.
3. Give `todo.type.ts` the following content:
```ts
export type TodoType = {
id: number;
name: string;
completed: boolean;
};
```
> **Note:** The Svelte template uses [svelte-preprocess](https://github.com/sveltejs/svelte-preprocess) 4.0.0 to support TypeScript. From that version onward you have to use `export`/`import` type syntax to import types and interfaces. Check [this section of the troubleshooting guide](https://github.com/sveltejs/language-tools/blob/master/docs/preprocessors/typescript.md#how-do-i-import-interfaces-into-my-svelte-components-i-get-errors-after-transpilation) for more information.
4. Now we'll use `TodoType` from our `Todo.svelte` component. First add the `lang="ts"` to our `<script>` tag.
5. Let's `import` the type and use it to declare the `todo` property. Replace the `export let todo` line with the following:
```ts
import type { TodoType } from "../types/todo.type";
export let todo: TodoType;
```
Note that the `.ts` file extension is not allowed in the `import` statement, and has been omitted.
6. Now from `Todos.svelte` we will instantiate a `Todo` component with a literal object as its parameter before the call to the `MoreActions` component, like this:
```svelte
<hr />
<Todo todo={ { name: 'a new task with no id!', completed: false } } />
<!-- MoreActions -->
<MoreActions {todos}
```
7. Add the `lang='ts'` to the `<script>` tag of the `Todos.svelte` component so that it knows to use the type checking we have specified.
We will get the following error:

By now you should get an idea about the kind of assistance we can get from TypeScript when building Svelte projects.
Now we will undo these changes in order to start porting our application to TypeScript, so we won't be bothered with all the check warnings.
1. Remove the flawed to-do and the `lang='ts'` attribute from the `Todos.svelte` file.
2. Also remove the import of `TodoType` and the `lang='ts'` from `Todo.svelte`.
We'll take care of them properly later on.
## Porting our to-do list app to TypeScript
Now we are ready to start porting our to-do list application to take advantage of all the features that TypeScript offers to us.
Let's start by running the check script in watch mode inside the project root:
```bash
npm run check -- --watch
```
This should output something like the following:
```bash
svelte-check "--watch"
Loading svelte-check in workspace: ./svelte-todo-typescript
Getting Svelte diagnostics...
====================================
svelte-check found no errors and no warnings
```
Note that if you are using a supporting code editor like VS Code, a simple way to start porting a Svelte component is to just add the `<script lang='ts'>` at the top of your component and look for the three-dotted hints:

### Alert.svelte
Let's start with our `Alert.svelte` component.
1. Add `lang="ts"` into your `Alert.svelte` component's `<script>` tag. You'll see some warnings in the output of the `check` script:
```bash
npm run check -- --watch
```
```plain
> svelte-check "--watch"
./svelte-todo-typescript
Getting Svelte diagnostics...
====================================
./svelte-todo-typescript/src/components/Alert.svelte:8:7
Warn: Variable 'visible' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
let visible
./svelte-todo-typescript/src/components/Alert.svelte:9:7
Warn: Variable 'timeout' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
let timeout
./svelte-todo-typescript/src/components/Alert.svelte:11:28
Warn: Parameter 'message' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
Change = (message, ms) => {
./svelte-todo-typescript/src/components/Alert.svelte:11:37
Warn: Parameter 'ms' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
(message, ms) => {
```
2. You can fix these by specifying the corresponding types, like so:
```ts
export let ms = 3000
let visible: boolean
let timeout: number
const onMessageChange = (message: string, ms: number) => {
clearTimeout(timeout)
if (!message) { // hide Alert if message is empty
```
> **Note:** There's no need to specify the `ms` type with `export let ms:number = 3000`, because TypeScript is already inferring it from its default value.
### MoreActions.svelte
Now we'll do the same for the `MoreActions.svelte` component.
1. Add the `lang='ts'` attribute, like before. TypeScript will warn us about the `todos` prop and the `t` variable in the call to `todos.filter((t) =>...)`.
```plain
Warn: Variable 'todos' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
export let todos
Warn: Parameter 't' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
$: completedTodos = todos.filter((t) => t.completed).length
```
2. We will use the `TodoType` we already defined to tell TypeScript that `todos` is a `TodoType` array. Replace the `export let todos` line with the following:
```ts
import type { TodoType } from "../types/todo.type";
export let todos: TodoType[];
```
Notice that now TypeScript can infer that the `t` variable in `todos.filter((t) => t.completed)` is of type `TodoType`. Nevertheless, if we think it makes our code easier to read, we could specify it like this:
```ts
$: completedTodos = todos.filter((t: TodoType) => t.completed).length;
```
Most of the time, TypeScript will be able to correctly infer the reactive variable type, but sometimes you might get an "implicitly has an 'any' type" error when working with reactive assignments. In those cases you can declare the typed variable in a different statement, like this:
```ts
let completedTodos: number;
$: completedTodos = todos.filter((t: TodoType) => t.completed).length;
```
You can't specify the type in the reactive assignment itself. The statement `$: completedTodos: number = todos.filter[...]` is invalid. For more information, read [How do I type reactive assignments? / I get an "implicitly has type 'any' error"](https://github.com/sveltejs/language-tools/blob/master/docs/preprocessors/typescript.md#how-do-i-type-reactive-assignments--i-get-an-implicitly-has-type-any-error).
### FilterButton.svelte
Now we'll take care of the `FilterButton` component.
1. Add the `lang='ts'` attribute to the `<script>` tag, as usual. You'll notice there are no warnings — TypeScript infers the type of the filter variable from the default value. But we know that there are only three valid values for the filter: all, active, and completed. So we can let TypeScript know about them by creating an enum Filter.
2. Create a `filter.enum.ts` file in the `types` folder.
3. Give it the following contents:
```ts
export enum Filter {
ALL = "all",
ACTIVE = "active",
COMPLETED = "completed",
}
```
4. Now we will use this from the `FilterButton` component. Replace the content of the `FilterButton.svelte` file with the following:
```svelte
<!-- components/FilterButton.svelte -->
<script lang="ts">
import { Filter } from "../types/filter.enum";
export let filter: Filter = Filter.ALL;
</script>
<div class="filters btn-group stack-exception">
<button class="btn toggle-btn" class:btn__primary={filter === Filter.ALL} aria-pressed={filter === Filter.ALL} on:click={()=> filter = Filter.ALL} >
<span class="visually-hidden">Show</span>
<span>All</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn__primary={filter === Filter.ACTIVE} aria-pressed={filter === Filter.ACTIVE} on:click={()=> filter = Filter.ACTIVE} >
<span class="visually-hidden">Show</span>
<span>Active</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn__primary={filter === Filter.COMPLETED} aria-pressed={filter === Filter.COMPLETED} on:click={()=> filter = Filter.COMPLETED} >
<span class="visually-hidden">Show</span>
<span>Completed</span>
<span class="visually-hidden">tasks</span>
</button>
</div>
```
Here we are just importing the `Filter` enum and using it instead of the string values we used previously.
### Todos.svelte
We will also use the `Filter` enum in the `Todos.svelte` component.
1. First, add the `lang='ts'` attribute to it, as before.
2. Next, import the `Filter` enum. Add the following `import` statement below your existing ones:
```js
import { Filter } from "../types/filter.enum";
```
3. Now we will use it whenever we reference the current filter. Replace your two filter-related blocks with the following:
```ts
let filter: Filter = Filter.ALL;
const filterTodos = (filter: Filter, todos) =>
filter === Filter.ACTIVE
? todos.filter((t) => !t.completed)
: filter === Filter.COMPLETED
? todos.filter((t) => t.completed)
: todos;
$: {
if (filter === Filter.ALL) {
$alert = "Browsing all todos";
} else if (filter === Filter.ACTIVE) {
$alert = "Browsing active todos";
} else if (filter === Filter.COMPLETED) {
$alert = "Browsing completed todos";
}
}
```
4. `check` will still give us some warnings from `Todos.svelte`. Let's fix them.
Start by importing the `TodoType` and telling TypeScript that our `todos` variable is an array of `TodoType`. Replace `export let todos = []` with the following two lines:
```ts
import type { TodoType } from "../types/todo.type";
export let todos: TodoType[] = [];
```
5. Next we'll specify all the missing types. The variable `todosStatus`, which we used to programmatically access the methods exposed by the `TodosStatus` component, is of type `TodosStatus`. And each `todo` will be of type `TodoType`.
Update your `<script>` section to look like this:
```ts
import FilterButton from "./FilterButton.svelte";
import Todo from "./Todo.svelte";
import MoreActions from "./MoreActions.svelte";
import NewTodo from "./NewTodo.svelte";
import TodosStatus from "./TodosStatus.svelte";
import { alert } from "../stores";
import { Filter } from "../types/filter.enum";
import type { TodoType } from "../types/todo.type";
export let todos: TodoType[] = [];
let todosStatus: TodosStatus; // reference to TodosStatus instance
$: newTodoId =
todos.length > 0 ? Math.max(...todos.map((t) => t.id)) + 1 : 1;
function addTodo(name: string) {
todos = [...todos, { id: newTodoId, name, completed: false }];
$alert = `Todo '${name}' has been added`;
}
function removeTodo(todo: TodoType) {
todos = todos.filter((t) => t.id !== todo.id);
todosStatus.focus(); // give focus to status heading
$alert = `Todo '${todo.name}' has been deleted`;
}
function updateTodo(todo: TodoType) {
const i = todos.findIndex((t) => t.id === todo.id);
if (todos[i].name !== todo.name)
$alert = `todo '${todos[i].name}' has been renamed to '${todo.name}'`;
if (todos[i].completed !== todo.completed)
$alert = `todo '${todos[i].name}' marked as ${
todo.completed ? "completed" : "active"
}`;
todos[i] = { ...todos[i], ...todo };
}
let filter: Filter = Filter.ALL;
const filterTodos = (filter: Filter, todos: TodoType[]) =>
filter === Filter.ACTIVE
? todos.filter((t) => !t.completed)
: filter === Filter.COMPLETED
? todos.filter((t) => t.completed)
: todos;
$: {
if (filter === Filter.ALL) {
$alert = "Browsing all todos";
} else if (filter === Filter.ACTIVE) {
$alert = "Browsing active todos";
} else if (filter === Filter.COMPLETED) {
$alert = "Browsing completed todos";
}
}
const checkAllTodos = (completed: boolean) => {
todos = todos.map((t) => ({ ...t, completed }));
$alert = `${completed ? "Checked" : "Unchecked"} ${todos.length} todos`;
};
const removeCompletedTodos = () => {
$alert = `Removed ${todos.filter((t) => t.completed).length} todos`;
todos = todos.filter((t) => !t.completed);
};
```
### TodosStatus.svelte
We are encountering the following errors related to passing `todos` to the `TodosStatus.svelte` (and `Todo.svelte`) components:
```plain
./src/components/Todos.svelte:70:39
Error: Type 'TodoType[]' is not assignable to type 'undefined'. (ts)
<TodosStatus bind:this={todosStatus} {todos} />
./src/components/Todos.svelte:76:12
Error: Type 'TodoType' is not assignable to type 'undefined'. (ts)
<Todo {todo}
```
This is because the `todos` prop in the `TodosStatus` component has no default value, so TypeScript has inferred it to be of type `undefined`, which is not compatible with an array of `TodoType`. The same thing is happening with our Todo component.
Let's fix it.
1. Open the file `TodosStatus.svelte` and add the `lang='ts'` attribute.
2. Then import the `TodoType` and declare the `todos` prop as an array of `TodoType`. Replace the first line of the `<script>` section with the following:
```ts
import type { TodoType } from "../types/todo.type";
export let todos: TodoType[];
```
3. We will also specify the `headingEl`, which we used to bind to the heading tag, as an `HTMLElement`. Update the `let headingEl` line with the following:
```ts
let headingEl: HTMLElement;
```
4. Finally, you'll notice the following error reported, related to where we set the `tabindex` attribute. That's because TypeScript is type checking the `<h2>` element and expects `tabindex` to be of type `number`.

To fix it, replace `tabindex="-1"` with `tabindex={-1}`, like this:
```svelte
<h2 id="list-heading" bind:this="{headingEl}" tabindex="{-1}">
{completedTodos} out of {totalTodos} items completed
</h2>
```
This way TypeScript can prevent us from incorrectly assigning it to a string variable.
### NewTodo.svelte
Next we will take care of `NewTodo.svelte`.
1. As usual, add the `lang='ts'` attribute.
2. The warning will indicate that we have to specify a type for the `nameEl` variable. Set its type to `HTMLElement` like this:
```ts
let nameEl: HTMLElement; // reference to the name input DOM node
```
3. Last for this file, we need to specify the correct type for our `autofocus` variable. Update its definition like this:
```ts
export let autofocus: boolean = false;
```
### Todo.svelte
Now the only warnings that `npm run check` emits are triggered by calling the `Todo.svelte` component. Let's fix them.
1. Open the `Todo.svelte` file, and add the `lang='ts'` attribute.
2. Let's import the `TodoType`, and set the type of the `todo` prop. Replace the `export let todo` line with the following:
```ts
import type { TodoType } from "../types/todo.type";
export let todo: TodoType;
```
3. The first warning we get is TypeScript telling us to define the type of the `update()` function's `updatedTodo` variable. This can be a little tricky because `updatedTodo` contains only the attributes of the `todo` that have been updated. That means it's not a complete `todo` — it only has a subset of a `todo`'s properties.
For these kinds of cases, TypeScript provides several [utility types](https://www.typescriptlang.org/docs/handbook/utility-types.html) to make it easier to apply these common transformations. What we need right now is the [`Partial<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt) utility, which allows us to represent all subsets of a given type. The partial utility returns a new type based on the type `T`, where every property of `T` is optional.
We'll use it in the `update()` function — update yours like so:
```ts
function update(updatedTodo: Partial<TodoType>) {
todo = { ...todo, ...updatedTodo }; // applies modifications to todo
dispatch("update", todo); // emit update event
}
```
With this we are telling TypeScript that the `updatedTodo` variable will hold a subset of the `TodoType` properties.
4. Now svelte-check tells us that we have to define the type of our action function parameters:
```bash
./07-next-steps/src/components/Todo.svelte:45:24
Warn: Parameter 'node' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
const focusOnInit = (node) => node && typeof node.focus === 'function' && node.focus()
./07-next-steps/src/components/Todo.svelte:47:28
Warn: Parameter 'node' implicitly has an 'any' type, but a better type may be inferred from usage. (ts)
const focusEditButton = (node) => editButtonPressed && node.focus()
```
We just have to define the node variable to be of type `HTMLElement`. In the two lines indicated above, replace the first instance of `node` with `node: HTMLElement`.
### actions.js
Next we'll take care of the `actions.js` file.
1. Rename it to `actions.ts` and add the type of the node parameter. It should end up looking like this:
```ts
// actions.ts
export function selectOnFocus(node: HTMLInputElement) {
if (node && typeof node.select === "function") {
// make sure node is defined and has a select() method
const onFocus = () => node.select(); // event handler
node.addEventListener("focus", onFocus); // when node gets focus call onFocus()
return {
destroy: () => node.removeEventListener("focus", onFocus), // this will be executed when the node is removed from the DOM
};
}
}
```
2. Now update `Todo.svelte` and `NewTodo.svelte` where we import the actions file. Remember that imports in TypeScript don't include the file extension. In each case it should end up like this:
```js
import { selectOnFocus } from "../actions";
```
### Migrating the stores to TypeScript
Now we have to migrate the `stores.js` and `localStore.js` files to TypeScript.
Tip: the script `npm run check`, which uses the [`svelte-check`](https://github.com/sveltejs/language-tools/tree/master/packages/svelte-check) tool, will only check our application's `.svelte` files. If you want to also check the `.ts` files, you can run `npm run check && npx tsc --noemit`, which tells the TypeScript compiler to check for errors without generating the `.js` output files. You could even add a script to your `package.json` file that runs that command.
We'll start with `stores.js`.
1. Rename the file to `stores.ts`.
2. Set the type of our `initialTodos` array to `TodoType[]`. This is how the contents will end up:
```ts
// stores.ts
import { writable } from "svelte/store";
import { localStore } from "./localStore.js";
import type { TodoType } from "./types/todo.type";
export const alert = writable("Welcome to the To-Do list app!");
const initialTodos: TodoType[] = [
{ id: 1, name: "Visit MDN web docs", completed: true },
{ id: 2, name: "Complete the Svelte Tutorial", completed: false },
];
export const todos = localStore("mdn-svelte-todo", initialTodos);
```
3. Remember to update the `import` statements in `App.svelte`, `Alert.svelte`, and `Todos.svelte`. Just remove the `.js` extension, like this:
```js
import { todos } from "../stores";
```
Now onto `localStore.js`.
Update the `import` statement in `stores.ts` like so:
```js
import { localStore } from "./localStore";
```
1. Start by renaming the file to `localStore.ts`.
2. TypeScript is telling us to specify the type of the `key`, `initial`, and `value` variables. The first one is easy: the key of our local web storage should be a string.
But `initial` and `value` should be any object that could be converted to a valid JSON string with the [`JSON.stringify`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) method, meaning any JavaScript object with a couple limitations: for example, `undefined`, functions, and symbols are not valid JSON values.
So we'll create the type `JsonValue` to specify these conditions.
Create the file `json.type.ts` in the `types` folder.
3. Give it the following content:
```ts
export type JsonValue =
| string
| number
| boolean
| null
| JsonValue[]
| { [key: string]: JsonValue };
```
The `|` operator lets us declare variables that could store values of two or more types. A `JsonValue` could be a string, a number, a boolean, and so on. In this case we are also making use of recursive types to specify that a `JsonValue` can have an array of `JsonValue` and also an object with properties of type `JsonValue`.
4. We will import our `JsonValue` type and use it accordingly. Update your `localStore.ts` file like this:
```ts
// localStore.ts
import { writable } from "svelte/store";
import type { JsonValue } from "./types/json.type";
export const localStore = (key: string, initial: JsonValue) => {
// receives the key of the local storage and an initial value
const toString = (value: JsonValue) => JSON.stringify(value, null, 2); // helper function
const toObj = JSON.parse; // helper function
if (localStorage.getItem(key) === null) {
// item not present in local storage
localStorage.setItem(key, toString(initial)); // initialize local storage with initial value
}
const saved = toObj(localStorage.getItem(key)); // convert to object
const { subscribe, set, update } = writable(saved); // create the underlying writable store
return {
subscribe,
set: (value: JsonValue) => {
localStorage.setItem(key, toString(value)); // save also to local storage as a string
return set(value);
},
update,
};
};
```
Now if we try to create a `localStore` with something that cannot be converted to JSON via `JSON.stringify()`, for example an object with a function as a property, VS Code/`validate` will complain about it:

And best of all, it will even work with the [`$store` auto-subscription syntax](https://svelte.dev/docs/svelte-components#script-4-prefix-stores-with-$-to-access-their-values). If we try to save an invalid value to our `todos` store using the `$store` syntax, like this:
```svelte
<!-- App.svelte -->
<script lang="ts">
import Todos from "./components/Todos.svelte";
import Alert from "./components/Alert.svelte";
import { todos } from "./stores";
// this is invalid, the content cannot be converted to JSON using JSON.stringify
$todos = { handler: () => {} };
</script>
```
The check script will report the following error:
```bash
> npm run check
Getting Svelte diagnostics...
====================================
./svelte-todo-typescript/src/App.svelte:8:12
Error: Argument of type '{ handler: () => void; }' is not assignable to parameter of type 'JsonValue'.
Types of property 'handler' are incompatible.
Type '() => void' is not assignable to type 'JsonValue'.
Type '() => void' is not assignable to type '{ [key: string]: JsonValue; }'.
Index signature is missing in type '() => void'. (ts)
$todos = { handler: () => {} }
```
This is another example of how specifying types can make our code more robust and help us catch more bugs before they get into production.
And that's it. We've converted our whole application to use TypeScript.
## Bulletproofing our stores with Generics
Our stores have already been ported to TypeScript, but we can do better. We shouldn't need to store any kind of value — we know that the alert store should contain string messages, and the to-dos store should contain an array of `TodoType`, etc. We can let TypeScript enforce this using [TypeScript Generics](https://www.typescriptlang.org/docs/handbook/generics.html). Let's find out more.
### Understanding TypeScript generics
Generics allow us to create reusable code components that work with a variety of types instead of a single type. They can be applied to interfaces, classes, and functions. Generic types are passed as parameters using a special syntax: they are specified between angle brackets, and by convention are denoted with an upper-cased single char letter. Generic types allow us to capture the types provided by the user to be used later.
Let's see a quick example, a simple `Stack` class that lets us `push` and `pop` elements, like this:
```ts
export class Stack {
private elements = [];
push = (element) => this.elements.push(element);
pop() {
if (this.elements.length === 0) throw new Error("The stack is empty!");
return this.elements.pop();
}
}
```
In this case `elements` is an array of type `any`, and accordingly the `push()` and `pop()` methods both receive and return a variable of type `any`. So it's perfectly valid to do something like the following:
```js
const anyStack = new Stack();
anyStack.push(1);
anyStack.push("hello");
```
But what if we wanted to have a `Stack` that would only work with type `string`? We could do the following:
```ts
export class StringStack {
private elements: string[] = [];
push = (element: string) => this.elements.push(element);
pop(): string {
if (this.elements.length === 0) throw new Error("The stack is empty!");
return this.elements.pop();
}
}
```
That would work. But if we wanted to work with numbers, we would then have to duplicate our code and create a `NumberStack` class. And how could we handle a stack of types we don't know yet, and that should be defined by the consumer?
To solve all these problems, we can use generics.
This is our `Stack` class reimplemented using generics:
```ts
export class Stack<T> {
private elements: T[] = [];
push = (element: T): number => this.elements.push(element);
pop(): T {
if (this.elements.length === 0) throw new Error("The stack is empty!");
return this.elements.pop();
}
}
```
We define a generic type `T` and then use it like we would normally use a specific type. Now elements is an array of type `T`, and `push()` and `pop()` both receive and return a variable of type `T`.
This is how we would use our generic `Stack`:
```ts
const numberStack = new Stack<number>();
numberStack.push(1);
```
Now TypeScript knows that our stack can only accept numbers, and will issue an error if we try to push anything else:

TypeScript can also infer generic types by its usage. Generics also support default values and constraints.
Generics are a powerful feature that allows our code to abstract away from the specific types being used, making it more reusable and generic without giving up on type safety. To learn more about it, check out the [TypeScript Introduction to Generics](https://www.typescriptlang.org/docs/handbook/generics.html).
### Using Svelte stores with generics
Svelte stores support generics out of the box. And, because of generic type inference, we can take advantage of it without even touching our code.
If you open the file `Todos.svelte` and assign a `number` type to our `$alert` store, you'll get the following error:

That's because when we defined our alert store in the `stores.ts` file with:
```js
export const alert = writable("Welcome to the To-Do list app!");
```
TypeScript inferred the generic type to be `string`. If we wanted to be explicit about it, we could do the following:
```ts
export const alert = writable<string>("Welcome to the To-Do list app!");
```
Now we'll make our `localStore` store support generics. Remember that we defined the `JsonValue` type to prevent the usage of our `localStore` store with values that cannot be persisted using `JSON.stringify()`. Now we want the consumers of `localStore` to be able to specify the type of data to persist, but instead of working with any type, they should comply with the `JsonValue` type. We'll specify that with a Generic constraint, like this:
```ts
export const localStore = <T extends JsonValue>(key: string, initial: T)
```
We define a generic type `T` and specify that it must be compatible with the `JsonValue` type. Then we'll use the `T` type appropriately.
Our `localStore.ts` file will end up like this — try the new code now in your version:
```ts
// localStore.ts
import { writable } from "svelte/store";
import type { JsonValue } from "./types/json.type";
export const localStore = <T extends JsonValue>(key: string, initial: T) => {
// receives the key of the local storage and an initial value
const toString = (value: T) => JSON.stringify(value, null, 2); // helper function
const toObj = JSON.parse; // helper function
if (localStorage.getItem(key) === null) {
// item not present in local storage
localStorage.setItem(key, toString(initial)); // initialize local storage with initial value
}
const saved = toObj(localStorage.getItem(key)); // convert to object
const { subscribe, set, update } = writable<T>(saved); // create the underlying writable store
return {
subscribe,
set: (value: T) => {
localStorage.setItem(key, toString(value)); // save also to local storage as a string
return set(value);
},
update,
};
};
```
And thanks to generic type inference, TypeScript already knows that our `$todos` store should contain an array of `TodoType`:

Once again, if we wanted to be explicit about it, we could do so in the `stores.ts` file like this:
```ts
const initialTodos: TodoType[] = [
{ id: 1, name: "Visit MDN web docs", completed: true },
{ id: 2, name: "Complete the Svelte Tutorial", completed: false },
];
export const todos = localStore<TodoType[]>("mdn-svelte-todo", initialTodos);
```
That will do for our brief tour of TypeScript Generics.
## The code so far
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/08-next-steps
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/08-next-steps
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
As we said earlier, TypeScript is not yet available in the REPL.
## Summary
In this article we took our to-do list application and ported it to TypeScript.
We first learnt about TypeScript and what advantages it can bring us. Then we saw how to create a new Svelte project with TypeScript support. We also saw how to convert an existing Svelte project to use TypeScript — our to-do list app.
We saw how to work with [Visual Studio Code](https://code.visualstudio.com/) and the [Svelte extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) to get features like type checking and auto-completion. We also used the `svelte-check` tool to inspect TypeScript issues from the command line.
In the next article we will learn how to compile and deploy our app to production. We will also see which resources are available online to go further with learning Svelte.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/angular_filtering/index.md | ---
title: Filtering our to-do items
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_filtering
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_item_component","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_building", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Now let's move on to adding functionality to allow users to filter their to-do items, so they can view active, completed, or all items.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To add filtering functionality to our app.</td>
</tr>
</tbody>
</table>
## Our filtering code
Filtering items builds on the `filter` property, which you previously added to `app.component.ts`:
```ts
filter: 'all' | 'active' | 'done' = 'all';
```
The default value for filter is `all`, but it can also be `active` or `done`.
## Adding filter controls
In `app.component.html`, add the following HTML below the **Add** button but above the section that lists the items.
In the following snippet, the existing sections in your HTML are in comments so you can see exactly where to put the buttons.
```html
<!-- <button class="btn-primary" (click)="addItem(newItem.value)">Add</button>
-->
<!-- Buttons that show all, still to do, or done items on click -->
<div class="btn-wrapper">
<button
class="btn btn-menu"
[class.active]="filter == 'all'"
(click)="filter = 'all'">
All
</button>
<button
class="btn btn-menu"
[class.active]="filter == 'active'"
(click)="filter = 'active'">
To Do
</button>
<button
class="btn btn-menu"
[class.active]="filter == 'done'"
(click)="filter = 'done'">
Done
</button>
</div>
<!-- <h2>\{{items.length}} item(s)</h2>
<ul>... -->
```
Clicking the buttons changes the `filter` values, which determines the `items` that show as well as the styles that Angular applies to the active button.
- If the user clicks the **All** button, all of the items show.
- If the user clicks the **To do** button, only the items with a `done` value of `false` show.
- If the user clicks the **Done** button, only the items with a `done` value of `true` show.
A class attribute binding, using square brackets, `[]`, controls the text color of the buttons.
The class binding, `[class.active]`, applies the `active` class when the value of `filter` matches the expression.
For example, when the user clicks the **Done** button, which sets the `filter` value to `done`, the class binding expression of `filter == 'done'` evaluates to `true`.
When the `filter` value is `done`, Angular applies the `active` class to the **Done** button to make the text color green.
As soon as the user clicks on one of the other buttons, the value a `filter` is no longer `done`, so the green text color no longer applies.
## Summary
That was quick! Since you already had the `filter` code in `app.component.ts`, all you had to do was edit the template in order to provide controls for filtering the items. Our next — and last — article looks at how to build your Angular app ready for production, and provides further resources to carry on your learning journey.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_item_component","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_building", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/angular_item_component/index.md | ---
title: Creating an item component
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_item_component
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_styling","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_filtering", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Components provide a way for you to organize your application. This article walks you through creating a component to handle the individual items in the list, and adding check, edit, and delete functionality. The Angular event model is covered here.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn more about components, including how events work to handle
updates. To add check, edit, and delete functionality.
</td>
</tr>
</tbody>
</table>
## Creating the new component
At the command line, create a component named `item` with the following CLI command:
```bash
ng generate component item
```
The `ng generate component` command creates a component and folder with the name you specify.
Here, the folder and component name is `item`.
You can find the `item` directory within the `app` folder.
Just as with the `AppComponent`, the `ItemComponent` is made up of the following files:
- `item.component.html` for HTML
- `item.component.ts` for logic
- `item.component.css` for styles
You can see a reference to the HTML and CSS files in the `@Component()` decorator metadata in `item.component.ts`.
```js
@Component({
selector: 'app-item',
templateUrl: './item.component.html',
styleUrls: ['./item.component.css'],
})
```
## Add HTML for the ItemComponent
The `ItemComponent` can take over the task of giving the user a way to check items off as done, edit them, or delete them.
Add markup for managing items by replacing the placeholder content in `item.component.html` with the following:
```html
<div class="item">
<input
[id]="item.description"
type="checkbox"
(change)="item.done = !item.done"
[checked]="item.done" />
<label [for]="item.description">\{{item.description}}</label>
<div class="btn-wrapper" *ngIf="!editable">
<button class="btn" (click)="editable = !editable">Edit</button>
<button class="btn btn-warn" (click)="remove.emit()">Delete</button>
</div>
<!-- This section shows only if user clicks Edit button -->
<div *ngIf="editable">
<input
class="sm-text-input"
placeholder="edit item"
[value]="item.description"
#editedItem
(keyup.enter)="saveItem(editedItem.value)" />
<div class="btn-wrapper">
<button class="btn" (click)="editable = !editable">Cancel</button>
<button class="btn btn-save" (click)="saveItem(editedItem.value)">
Save
</button>
</div>
</div>
</div>
```
The first input is a checkbox so users can check off items when an item is complete.
The double curly braces, `\{{}}`, in the `<label>` for the checkbox signifies Angular's interpolation.
Angular uses `\{{item.description}}` to retrieve the description of the current `item` from the `items` array.
The next section explains how components share data in detail.
The next two buttons for editing and deleting the current item are within a `<div>`.
On this `<div>` is an `*ngIf`, a built-in Angular directive that you can use to dynamically change the structure of the DOM.
This `*ngIf` means that if `editable` is `false`, this `<div>` is in the DOM. If `editable` is `true`, Angular removes this `<div>` from the DOM.
```html
<div class="btn-wrapper" *ngIf="!editable">
<button class="btn" (click)="editable = !editable">Edit</button>
<button class="btn btn-warn" (click)="remove.emit()">Delete</button>
</div>
```
When a user clicks the **Edit** button, `editable` becomes true, which removes this `<div>` and its children from the DOM.
If, instead of clicking **Edit**, a user clicks **Delete**, the `ItemComponent` raises an event that notifies the `AppComponent` of the deletion.
An `*ngIf` is also on the next `<div>`, but is set to an `editable` value of `true`.
In this case, if `editable` is `true`, Angular puts the `<div>` and its child `<input>` and `<button>` elements in the DOM.
```html
<!-- This section shows only if user clicks Edit button -->
<div *ngIf="editable">
<input
class="sm-text-input"
placeholder="edit item"
[value]="item.description"
#editedItem
(keyup.enter)="saveItem(editedItem.value)" />
<div class="btn-wrapper">
<button class="btn" (click)="editable = !editable">Cancel</button>
<button class="btn btn-save" (click)="saveItem(editedItem.value)">
Save
</button>
</div>
</div>
```
With `[value]="item.description"`, the value of the `<input>` is bound to the `description` of the current item.
This binding makes the item's `description` the value of the `<input>`.
So if the `description` is `eat`, the `description` is already in the `<input>`.
This way, when the user edits the item, the value of the `<input>` is already `eat`.
The template variable, `#editedItem`, on the `<input>` means that Angular stores whatever a user types in this `<input>` in a variable called `editedItem`.
The `keyup` event calls the `saveItem()` method and passes in the `editedItem` value if the user chooses to press enter instead of click **Save**.
When a user clicks the **Cancel** button, `editable` toggles to `false`, which removes the input and buttons for editing from the DOM.
When `editable` is `false`, Angular puts `<div>` with the **Edit** and **Delete** buttons back in the DOM.
Clicking the **Save** button calls the `saveItem()` method.
The `saveItem()` method takes the value from the `#editedItem` element and changes the item's `description` to `editedItem.value` string.
## Prepare the AppComponent
In the next section, you will add code that relies on communication between the `AppComponent` and the `ItemComponent`.
Add the following line near the top of the `app.component.ts` file to import the `Item`:
```ts
import { Item } from "./item";
```
Then, configure the AppComponent by adding the following to the same file's class:
```js
remove(item: Item) {
this.allItems.splice(this.allItems.indexOf(item), 1);
}
```
The `remove()` method uses the JavaScript `Array.splice()` method to remove one item at the `indexOf` the relevant item.
In plain English, this means that the `splice()` method removes the item from the array.
For more information on the `splice()` method, see the MDN Web Docs article on [`Array.prototype.splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice).
## Add logic to ItemComponent
To use the `ItemComponent` UI, you must add logic to the component such as functions, and ways for data to go in and out.
In `item.component.ts`, edit the JavaScript imports as follows:
```js
import { Component, Input, Output, EventEmitter } from "@angular/core";
import { Item } from "../item";
```
The addition of `Input`, `Output`, and `EventEmitter` allows `ItemComponent` to share data with `AppComponent`.
By importing `Item`, `ItemComponent` can understand what an `item` is.
Further down `item.component.ts`, replace the generated `ItemComponent` class with the following:
```js
export class ItemComponent {
editable = false;
@Input() item!: Item;
@Output() remove = new EventEmitter<Item>();
saveItem(description: string) {
if (!description) return;
this.editable = false;
this.item.description = description;
}
}
```
The `editable` property helps toggle a section of the template where a user can edit an item.
`editable` is the same property in the HTML as in the `*ngIf` statement, `*ngIf="editable"`.
When you use a property in the template, you must also declare it in the class.
`@Input()`, `@Output()`, and `EventEmitter` facilitate communication between your two components.
An `@Input()` serves as a doorway for data to come into the component, and an `@Output()` acts as a doorway for data to go out of the component.
An `@Output()` has to be of type `EventEmitter`, so that a component can raise an event when there's data ready to share with another component.
> **Note:** The `!` in the class's property declaration is called a [definite assignment assertion](https://www.typescriptlang.org/docs/handbook/2/classes.html#--strictpropertyinitialization). This operator tells Typescript that the `item` field is always initialized and not `undefined`, even when TypeScript cannot tell from the constructor's definition. If this operator is not included in your code and you have strict TypeScript compilation settings, the app will fail to compile.
Use `@Input()` to specify that the value of a property can come from outside of the component.
Use `@Output()` in conjunction with `EventEmitter` to specify that the value of a property can leave the component so that another component can receive that data.
The `saveItem()` method takes as an argument a `description` of type `string`.
The `description` is the text that the user enters into the HTML `<input>` when editing an item in the list.
This `description` is the same string from the `<input>` with the `#editedItem` template variable.
If the user doesn't enter a value but clicks **Save**, `saveItem()` returns nothing and does not update the `description`.
If you didn't have this `if` statement, the user could click **Save** with nothing in the HTML `<input>`, and the `description` would become an empty string.
If a user enters text and clicks save, `saveItem()` sets `editable` to false, which causes the `*ngIf` in the template to remove the edit feature and render the **Edit** and **Delete** buttons again.
Though the application should compile at this point, you need to use the `ItemComponent` in `AppComponent` so you can see the new features in the browser.
## Use the ItemComponent in the AppComponent
Including one component within another in the context of a parent-child relationship gives you the flexibility of using components wherever you need them.
The `AppComponent` serves as a shell for the application where you can include other components.
To use the `ItemComponent` in `AppComponent`, put the `ItemComponent` selector in the `AppComponent` template.
Angular specifies the selector of a component in the metadata of the `@Component()` decorator.
In this example, the selector is `app-item`:
```js
@Component({
selector: 'app-item',
templateUrl: './item.component.html',
styleUrls: ['./item.component.css']
})
```
To use the `ItemComponent` selector within the `AppComponent`, you add the element, `<app-item>`, which corresponds to the selector you defined for the component class to `app.component.html`.
Replace the current unordered list in `app.component.html` with the following updated version:
```html
<h2>
\{{items.length}}
<span *ngIf="items.length === 1; else elseBlock">item</span>
<ng-template #elseBlock>items</ng-template>
</h2>
<ul>
<li *ngFor="let i of items">
<app-item (remove)="remove(i)" [item]="i"></app-item>
</li>
</ul>
```
The double curly brace syntax, `\{{}}`, in the `<h2>` interpolates the length of the `items` array and displays the number.
The `<span>` in the `<h2>` uses an `*ngIf` and `else` to determine whether the `<h2>` should say "item" or "items".
If there is only a single item in the list, the `<span>` containing "item" displays.
Otherwise, if the length of the `items` array is anything other than `1`, the `<ng-template>`, which we've named `elseBlock`, with the syntax `#elseBlock`, shows instead of the `<span>`.
You can use Angular's `<ng-template>` when you don't want content to render by default.
In this case, when the length of the `items` array is not `1`, the `*ngIf` shows the `elseBlock` and not the `<span>`.
The `<li>` uses Angular's repeater directive, `*ngFor`, to iterate over all of the items in the `items` array.
Angular's `*ngFor` like `*ngIf`, is another directive that helps you change the structure of the DOM while writing less code.
For each `item`, Angular repeats the `<li>` and everything within it, which includes `<app-item>`.
This means that for each item in the array, Angular creates another instance of `<app-item>`.
For any number of items in the array, Angular would create that many `<li>` elements.
You can use an `*ngFor` on other elements, too, such as `<div>`, `<span>`, or `<p>`, to name a few.
The `AppComponent` has a `remove()` method for removing the item, which is bound to the `remove` property in the `ItemComponent`.
The `item` property in the square brackets, `[]`, binds the value of `i` between the `AppComponent` and the `ItemComponent`.
Now you should be able to edit and delete items from the list.
When you add or delete items, the count of the items should also change.
To make the list more user-friendly, add some styles to the `ItemComponent`.
## Add styles to ItemComponent
You can use a component's style sheet to add styles specific to that component.
The following CSS adds basic styles, flexbox for the buttons, and custom checkboxes.
Paste the following styles into `item.component.css`.
```css
.item {
padding: 0.5rem 0 0.75rem 0;
text-align: left;
font-size: 1.2rem;
}
.btn-wrapper {
margin-top: 1rem;
margin-bottom: 0.5rem;
}
.btn {
/* menu buttons flexbox styles */
flex-basis: 49%;
}
.btn-save {
background-color: #000;
color: #fff;
border-color: #000;
}
.btn-save:hover {
background-color: #444242;
}
.btn-save:focus {
background-color: #fff;
color: #000;
}
.checkbox-wrapper {
margin: 0.5rem 0;
}
.btn-warn {
background-color: #b90000;
color: #fff;
border-color: #9a0000;
}
.btn-warn:hover {
background-color: #9a0000;
}
.btn-warn:active {
background-color: #e30000;
border-color: #000;
}
.sm-text-input {
width: 100%;
padding: 0.5rem;
border: 2px solid #555;
display: block;
box-sizing: border-box;
font-size: 1rem;
margin: 1rem 0;
}
/* Custom checkboxes
Adapted from https://css-tricks.com/the-checkbox-hack/#custom-designed-radio-buttons-and-checkboxes */
/* Base for label styling */
[type="checkbox"]:not(:checked),
[type="checkbox"]:checked {
position: absolute;
left: -9999px;
}
[type="checkbox"]:not(:checked) + label,
[type="checkbox"]:checked + label {
position: relative;
padding-left: 1.95em;
cursor: pointer;
}
/* checkbox aspect */
[type="checkbox"]:not(:checked) + label:before,
[type="checkbox"]:checked + label:before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 1.25em;
height: 1.25em;
border: 2px solid #ccc;
background: #fff;
}
/* checked mark aspect */
[type="checkbox"]:not(:checked) + label:after,
[type="checkbox"]:checked + label:after {
content: "\2713\0020";
position: absolute;
top: 0.15em;
left: 0.22em;
font-size: 1.3em;
line-height: 0.8;
color: #0d8dee;
transition: all 0.2s;
font-family: "Lucida Sans Unicode", "Arial Unicode MS", Arial;
}
/* checked mark aspect changes */
[type="checkbox"]:not(:checked) + label:after {
opacity: 0;
transform: scale(0);
}
[type="checkbox"]:checked + label:after {
opacity: 1;
transform: scale(1);
}
/* accessibility */
[type="checkbox"]:checked:focus + label:before,
[type="checkbox"]:not(:checked):focus + label:before {
border: 2px dotted blue;
}
```
## Summary
You should now have a styled Angular to-do list application that can add, edit, and remove items.
The next step is to add filtering so that you can look at items that meet specific criteria.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_styling","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_filtering", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/angular_todo_list_beginning/index.md | ---
title: Beginning our Angular todo list app
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_todo_list_beginning
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_getting_started","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_styling", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
At this point, we are ready to start creating our to-do list application using Angular. The finished application will display a list of to-do items and includes editing, deleting, and adding features. In this article you will get to know your application structure, and work up to displaying a basic list of to-do items.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To create our basic app structure, get it displaying a list of to-do
items, and understand fundamental Angular concepts such as component
structure, sharing data between components, and looping content
creation.
</td>
</tr>
</tbody>
</table>
## The to-do application structure
Just like a basic application that doesn't use a framework, an Angular application has an `index.html`.
Within the `<body>` tag of the `index.html`, Angular uses a special element — `<app-root>` — to insert your main component, which in turn includes other components you create.
Generally, you don't need to touch the `index.html`, instead focusing your work within specialized areas of your application called components.
### Organize your application with components
Components are a central building block of Angular applications.
This to-do application has two components — a component as a foundation for your application, and a component for handling to-do items.
Each component is made up of a TypeScript class, HTML, and CSS.
TypeScript transpiles, or converts, into JavaScript, which means that your application ultimately ends up in plain JavaScript but you have the convenience of using Typescript's extended features and streamlined syntax.
### Dynamically change the UI with \*ngIf and \*ngFor
This tutorial also covers two important Angular directives for dynamically altering the structure of the DOM.
A directive is like a command that you can use in your HTML to affect change in your application.
The first directive that this tutorial covers is Angular's iterator, `*ngFor`.
`*ngFor` can dynamically create DOM elements based on items in an array.
The second directive that you learn in this tutorial is `*ngIf`.
You can use `*ngIf` to add or remove elements from the DOM based on a condition.
For example, if users want to edit an item in the to-do list, you can provide them with the means to edit the item.
If they do not want to edit an item, you can remove the interface for editing.
### Share data between components
In this to-do application, you configure your components to share data.
To add new items to the to do list, the main component has to send the new item to the second component.
This second component manages the items and takes care of editing, marking as done, and deleting individual items.
You accomplish sharing data between Angular components with special decorators called `@Input()` and `@Output()`.
You use these decorators to specify that certain properties allow data to go into or out of a component.
To use `@Output()`, you raise an event in one component so that the other component knows that there is data available.
## Define Item
In the `app` directory, create a new file named `item.ts` with the following contents:
```ts
export interface Item {
description: string;
done: boolean;
}
```
You won't use this file until [later](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_item_component#add_logic_to_itemcomponent), but it is a good time to know and record your knowledge of what an `item` is. The `Item` interface creates an `item` object model so that your application will understand what an `item` is. For this to-do list, an `item` is an object that has a description and can be done.
## Add logic to AppComponent
Now that you know what an `item` is, you can give your application some items by adding them to the TypeScript file, `app.component.ts`.
In `app.component.ts`, replace the contents with the following:
```js
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
title = "todo";
filter: "all" | "active" | "done" = "all";
allItems = [
{ description: "eat", done: true },
{ description: "sleep", done: false },
{ description: "play", done: false },
{ description: "laugh", done: false },
];
get items() {
if (this.filter === "all") {
return this.allItems;
}
return this.allItems.filter((item) =>
this.filter === "done" ? item.done : !item.done
);
}
}
```
The first line is a JavaScript import that imports Angular.
The `@Component()` decorator specifies metadata about the `AppComponent`.
The default metadata properties are as follows:
- `selector`: Tells you the name of the CSS selector that you use in a template to instantiate this component. Here it is `'app-root'`.
In the `index.html`, within the `body` tag, the Angular CLI added `<app-root></app-root>` when generating your application.
You use all component selectors in the same way by adding them to other component HTML templates.
- `templateUrl`: Specifies the HTML file to associate with this component.
Here it is, './app.component.html',
- `styleUrls`: Provides the location and name of the file for your styles that apply specifically to this component. Here it is `'./app.component.css'`.
The `filter` property is of type `union`, which means `filter` could have the value of `all`, `active`, or `done`.
With the `union` type, if you make a typo in the value you assign to the `filter` property, TypeScript lets you know so that you can catch the bug early.
This guide shows you how to add filtering in a later step, but you can also use a filter to show the default list of all the items.
The `allItems` array contains the to-do items and whether they are `done`.
The first item, `eat`, has a `done` value of true.
The getter, `get items()`, retrieves the items from the `allItems` array if the `filter` is equal to `all`.
Otherwise, `get items()` returns the `done` items or the outstanding items depending on how the user filters the view.
The getter also establishes the name of the array as `items`, which you'll use in the next section.
## Add HTML to the AppComponent template
To see the list of items in the browser, replace the contents of `app.component.html` with the following HTML:
```html
<div class="main">
<h1>My To Do List</h1>
<h2>What would you like to do today?</h2>
<ul>
<li *ngFor="let item of items">\{{item.description}}</li>
</ul>
</div>
```
The `<li>` contains an `*ngFor`, a built-in Angular directive that iterates over the items in the `items` array.
For each item, `*ngFor` creates a new `<li>`.
The double curly braces that contain `item.description` instructs Angular to populate each `<li>` with the text of each item's description.
In the browser, you should see the list of items as follows:
```plain
My To Do List
What would you like to do today?
* eat
* sleep
* play
* laugh
```
## Add items to the list
A to-do list needs a way to add items.
In `app.component.ts`, add the following method to the class:
```ts
addItem(description: string) {
this.allItems.unshift({
description,
done: false
});
}
```
The `addItem()` method takes an item that the user provides and adds it to the array when the user clicks the **Add** button.
The `addItem()` method uses the array method `unshift()` to add a new item to the beginning of the array and the top of the list.
You could alternatively use `push()`, which would add the new item to the end of the array and the bottom of the list.
To use the `addItem()` method, edit the HTML in the `AppComponent` template.
In `app.component.html`, replace the `<h2>` with the following:
```html
<label for="addItemInput">What would you like to do today?</label>
<input
#newItem
placeholder="add an item"
(keyup.enter)="addItem(newItem.value); newItem.value = ''"
class="lg-text-input"
id="addItemInput" />
<button class="btn-primary" (click)="addItem(newItem.value)">Add</button>
```
In the above HTML, `#newItem` is a template variable. The template variable in this case uses the `<input>` element as its value. Template variables can be referred to anywhere in the component's template.
When the user types a new item in the `<input>` field and presses **Enter**, the `addItem()` method adds the value to the `allItems` array.
Pressing the **Enter** key also resets the value of `<input>` to an empty string. The template variable `#newItem` is used to access the value of the `<input>` element in the template.
Instead of pressing the **Enter** key, the user can also click the **Add** button, which calls the same `addItem()` method.
## Summary
By now you should have your basic list of to-dos displaying in your browser. That's great progress! Of course, we have a lot more to do. In the next article we will look at adding some styling to our application.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_getting_started","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_styling", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/vue_computed_properties/index.md | ---
title: Using Vue computed properties
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In this article we'll add a counter that displays the number of completed todo items, using a feature of Vue called computed properties. These work similarly to methods, but only re-run when one of their dependencies changes.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn how to use Vue computed properties.</td>
</tr>
</tbody>
</table>
## Using computed properties
The aim here is to add a summary count of our to-do list. This can be useful for users, while also serving to label the list for assistive technology. If we have 2 of 5 items completed in our to-do list, our summary could read "2 items completed out of 5". While it might be tempting to do something like this:
```vue
<h2>
\{{ToDoItems.filter(item => item.done).length}} out of
\{{ToDoItems.length}} items completed
</h2>
```
It would be recalculated on every render. For a small app like this, that probably doesn't matter too much. For bigger apps, or when the expression is more complicated, that could cause a serious performance problem.
A better solution is to use Vue's [computed properties](https://vuejs.org/guide/essentials/computed.html). Computed Properties work similarly to methods, but only re-run when one of their dependencies changes. In our case, this would only re-run when the `ToDoItems` array changes.
To create a computed property, we need to add a `computed` property to our component object, much like the `methods` property we've used previously.
## Adding a summary counter
Add the following code to your `App` component object, below the `methods` property. The list summary method will get the number of finished `ToDoItems`, and return a string reporting this.
```js
computed: {
listSummary() {
const numberFinishedItems = this.ToDoItems.filter((item) =>item.done).length
return `${numberFinishedItems} out of ${this.ToDoItems.length} items completed`
}
}
```
Now we can add `\{{listSummary}}` directly to our template; we'll add this inside an `<h2>` element, just above our `<ul>`. We'll also add an `id` and an `aria-labelledby` attribute to assign the `<h2>` contents to be a label for the `<ul>` element.
Add the described `<h2>` and update the `<ul>` inside your `App`'s template as follows:
```vue
<h2 id="list-summary">\{{listSummary}}</h2>
<ul aria-labelledby="list-summary" class="stack-large">
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item
:label="item.label"
:done="item.done"
:id="item.id"></to-do-item>
</li>
</ul>
```
You should now see the list summary in your app, and the total number of items update as you add more todo items! However, if you try checking and unchecking some items, you'll reveal a bug. Currently, we're not actually tracking the "done" data in any fashion, so the number of completed items does not change.
## Tracking changes to "done"
We can use events to capture the checkbox update and manage our list accordingly.
Since we're not relying on a button press to trigger the change, we can attach a `@change` event handler to each checkbox instead of using `v-model`.
Update the `<input>` element in `ToDoItem.vue` to look like this.
```vue
<input
type="checkbox"
class="checkbox"
:id="id"
:checked="isDone"
@change="$emit('checkbox-changed')" />
```
Since all we need to do is emit that the checkbox was checked, we can include the `$emit()` inline.
In `App.vue`, add a new method called `updateDoneStatus()`, below your `addToDo()` method. This method should take one parameter: the todo item _id_. We want to find the item with the matching `id` and update its `done` status to be the opposite of its current status:
```js
updateDoneStatus(toDoId) {
const toDoToUpdate = this.ToDoItems.find((item) => item.id === toDoId)
toDoToUpdate.done = !toDoToUpdate.done
}
```
We want to run this method whenever a `ToDoItem` emits a `checkbox-changed` event, and pass in its `item.id` as the parameter. Update your `<to-do-item></to-do-item>` call as follows:
```vue
<to-do-item
:label="item.label"
:done="item.done"
:id="item.id"
@checkbox-changed="updateDoneStatus(item.id)">
</to-do-item>
```
Now if you check a `ToDoItem`, you should see the summary update appropriately!

## Summary
In this article we've used a computed property to add a nice little feature to our app. We do however have bigger fish to fry — in the next article we will look at conditional rendering, and how we can use it to show an edit form when we want to edit existing todo items.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
Subsets and Splits