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/javascript/objects | data/mdn-content/files/en-us/learn/javascript/objects/adding_bouncing_balls_features/index.md | ---
title: Adding features to our bouncing balls demo
slug: Learn/JavaScript/Objects/Adding_bouncing_balls_features
page-type: learn-module-assessment
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Objects/Object_building_practice", "", "Learn/JavaScript/Objects")}}
In this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it.
<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 JavaScript objects and object-oriented
constructs
</td>
</tr>
</tbody>
</table>
## Starting point
To get this assessment started, make a local copy of [index-finished.html](https://github.com/mdn/learning-area/blob/main/javascript/oojs/bouncing-balls/index-finished.html), [style.css](https://github.com/mdn/learning-area/blob/main/javascript/oojs/bouncing-balls/style.css), and [main-finished.js](https://github.com/mdn/learning-area/blob/main/javascript/oojs/bouncing-balls/main-finished.js) from our last article in a new directory in your local computer.
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, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have a separate JavaScript panel, feel free to put it inline in a `<script>` element inside the HTML page.
> **Note:** If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Hints and tips
A couple of pointers before you get started.
- This assessment is quite challenging. Read the whole assessment before you start coding, and take each step slowly and carefully.
- It might be a good idea to save a separate copy of the demo after you get each stage working, so you can refer back to it if you find yourself in trouble later on.
## Project brief
Our bouncy ball demo is fun, but now we want to make it a little bit more interactive by adding a user-controlled evil circle, which will eat the balls if it catches them. We also want to test your object-building skills by creating a generic `Shape()` object that our balls and evil circle can inherit from. Finally, we want to add a score counter to track the number of balls left to capture.
The following screenshot gives you an idea of what the finished program should look like:

To give you more of an idea, have a look at the [finished example](https://mdn.github.io/learning-area/javascript/oojs/assessment/) (no peeking at the source code!)
## Steps to complete
The following sections describe what you need to do.
### Create a Shape class
First of all, create a new `Shape` class. This has only a constructor. The `Shape` constructor should define the `x`, `y`, `velX`, and `velY` properties in the same way as the `Ball()` constructor did originally, but not the `color` and `size` properties.
The `Ball` class should be made to derive from `Shape` using `extends`. The constructor for `Ball` should:
- take the same arguments as before: `x`, `y`, `velX`, `velY`, `size`, and `color`
- call the `Shape` constructor using `super()`, passing in the `x`, `y`, `velX`, and `velY` arguments
- initialize its own `color` and `size` properties from the parameters it is given.
The `Ball` constructor should define a new property called `exists`, which is used to track whether the balls exist in the program (have not been eaten by the evil circle). This should be a boolean (`true`/`false`), initialized to `true` in the constructor.
The `collisionDetect()` method of the `Ball` class needs a small update. A ball needs to be considered for collision detection only if the `exists` property is `true`. So, replace the existing `collisionDetect()` code with the following code:
```js
collisionDetect() {
for (const ball of balls) {
if (!(this === ball) && ball.exists) {
const dx = this.x - ball.x;
const dy = this.y - ball.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < this.size + ball.size) {
ball.color = this.color = randomRGB();
}
}
}
}
```
As discussed above, the only addition is to check if the ball exists β by using `ball.exists` in the `if` conditional.
The ball `draw()` and `update()` method definitions should be able to stay exactly the same as they were before.
At this point, try reloading the code β it should work just the same as it did before, with our redesigned objects.
### Defining EvilCircle
Now it's time to meet the bad guy β the `EvilCircle()`! Our game is only going to involve one evil circle, but we are still going to define it using a constructor that inherits from `Shape()`, to give you some practice. You might want to add another circle to the app later on that can be controlled by another player, or have several computer-controlled evil circles. You're probably not going to take over the world with a single evil circle, but it will do for this assessment.
Create a definition for an `EvilCircle` class. It should inherit from `Shape` using `extends`.
#### EvilCircle constructor
The constructor for `EvilCircle` should:
- be passed just `x`, `y` arguments
- pass the `x`, `y` arguments up to the `Shape` superclass along with values for `velX` and `velY` hardcoded to 20. You should do this with code like `super(x, y, 20, 20);`
- set `color` to `white` and `size` to `10`.
Finally, the constructor should set up the code enabling the user to move the evil circle around the screen:
```js
window.addEventListener("keydown", (e) => {
switch (e.key) {
case "a":
this.x -= this.velX;
break;
case "d":
this.x += this.velX;
break;
case "w":
this.y -= this.velY;
break;
case "s":
this.y += this.velY;
break;
}
});
```
This adds a `keydown` event listener to the `window` object so that when a key is pressed, the event object's [`key`](/en-US/docs/Web/API/KeyboardEvent/key) property is consulted to see which key is pressed. If it is one of the four specified keys, then the evil circle will move left/right/up/down.
### Defining methods for EvilCircle
The `EvilCircle` class should have three methods, as described below.
#### draw()
This method has the same purpose as the `draw()` method for `Ball`: it draws the object instance on the canvas. The `draw()` method for `EvilCircle` will work in a very similar way, so you can start by copying the `draw()` method for `Ball`. You should then make the following changes:
- We want the evil circle to not be filled in, but rather just have an outer line (stroke). You can achieve this by updating [`fillStyle`](/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle) and [`fill()`](/en-US/docs/Web/API/CanvasRenderingContext2D/fill) to [`strokeStyle`](/en-US/docs/Web/API/CanvasRenderingContext2D/strokeStyle) and [`stroke()`](/en-US/docs/Web/API/CanvasRenderingContext2D/stroke) respectively.
- We also want to make the stroke a bit thicker, so you can see the evil circle a bit more easily. This can be achieved by setting a value for [`lineWidth`](/en-US/docs/Web/API/CanvasRenderingContext2D/lineWidth) somewhere after the [`beginPath()`](/en-US/docs/Web/API/CanvasRenderingContext2D/beginPath) call (3 will do).
#### checkBounds()
This method will do the same thing as the first part of the `update()` method for `Ball` β look to see whether the evil circle is going to go off the edge of the screen, and stop it from doing so. Again, you can mostly just copy the `update()` method for `Ball`, but there are a few changes you should make:
- Get rid of the last two lines β we don't want to automatically update the evil circle's position on every frame, because we will be moving it in some other way, as you'll see below.
- Inside the `if ()` statements, if the tests return true we don't want to update `velX`/`velY`; we want to instead change the value of `x`/`y` so the evil circle is bounced back onto the screen slightly. Adding or subtracting (as appropriate) the evil circle's `size` property would make sense.
#### collisionDetect()
This method will act in a very similar way to the `collisionDetect()` method for `Ball` method, so you can use a copy of that as the basis of this new method. But there are a couple of differences:
- In the outer `if` statement, you no longer need to check whether the current ball in the iteration is the same as the ball that is doing the checking β because it is no longer a ball, it is the evil circle! Instead, you need to do a test to see if the ball being checked exists (with which property could you do this with?). If it doesn't exist, it has already been eaten by the evil circle, so there is no need to check it again.
- In the inner `if` statement, you no longer want to make the objects change color when a collision is detected β instead, you want to set any balls that collide with the evil circle to not exist any more (again, how do you think you'd do that?).
### Bringing the evil circle into the program
Now we've defined the evil circle, we need to actually make it appear in our scene. To do this, you need to make some changes to the `loop()` function.
- First of all, create a new evil circle object instance (specifying the necessary parameters). You only need to do this once, not on every iteration of the loop.
- At the point where you loop through every ball and call the `draw()`, `update()`, and `collisionDetect()` functions for each one, make it so that these functions are only called if the current ball exists.
- Call the evil circle instance's `draw()`, `checkBounds()`, and `collisionDetect()` methods on every iteration of the loop.
### Implementing the score counter
To implement the score counter, follow the following steps:
1. In your HTML file, add a {{HTMLElement("p")}} element just below the {{HTMLElement("Heading_Elements", "h1")}} element containing the text "Ball count: ".
2. In your CSS file, add the following rule at the bottom:
```css
p {
position: absolute;
margin: 0;
top: 35px;
right: 5px;
color: #aaa;
}
```
3. In your JavaScript, make the following updates:
- Create a variable that stores a reference to the paragraph.
- Keep a count of the number of balls on screen in some way.
- Increment the count and display the updated number of balls each time a ball is added to the scene.
- Decrement the count and display the updated number of balls each time the evil circle eats a ball (causes it not to exist).
{{PreviousMenuNext("Learn/JavaScript/Objects/Object_building_practice", "", "Learn/JavaScript/Objects")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/objects | data/mdn-content/files/en-us/learn/javascript/objects/classes_in_javascript/index.md | ---
title: Classes in JavaScript
slug: Learn/JavaScript/Objects/Classes_in_JavaScript
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Objects/Object-oriented_programming", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}
In [the last article](/en-US/docs/Learn/JavaScript/Objects/Object-oriented_programming), we introduced some basic concepts of object-oriented programming (OOP), and discussed an example where we used OOP principles to model professors and students in a school.
We also talked about how it's possible to use [prototypes](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes) and [constructors](/en-US/docs/Learn/JavaScript/Objects/Basics#introducing_constructors) to implement a model like this, and that JavaScript also provides features that map more closely to classical OOP concepts.
In this article, we'll go through these features. It's worth keeping in mind that the features described here are not a new way of combining objects: under the hood, they still use prototypes. They're just a way to make it easier to set up a prototype chain.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML and CSS,
familiarity with JavaScript basics (see
<a href="/en-US/docs/Learn/JavaScript/First_steps">First steps</a> and
<a href="/en-US/docs/Learn/JavaScript/Building_blocks"
>Building blocks</a
>) and OOJS basics (see
<a href="/en-US/docs/Learn/JavaScript/Objects/Basics"
>Introduction to objects</a
>, <a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">Object prototypes</a>, and <a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_programming">Object-oriented programming</a>).
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand how to use the features JavaScript provides to implement "classical" object-oriented programs.
</td>
</tr>
</tbody>
<table>
## Classes and constructors
You can declare a class using the {{jsxref("Statements/class", "class")}} keyword. Here's a class declaration for our `Person` from the previous article:
```js
class Person {
name;
constructor(name) {
this.name = name;
}
introduceSelf() {
console.log(`Hi! I'm ${this.name}`);
}
}
```
This declares a class called `Person`, with:
- a `name` property.
- a constructor that takes a `name` parameter that is used to initialize the new object's `name` property
- an `introduceSelf()` method that can refer to the object's properties using `this`.
The `name;` declaration is optional: you could omit it, and the line `this.name = name;` in the constructor will create the `name` property before initializing it. However, listing properties explicitly in the class declaration might make it easier for people reading your code to see which properties are part of this class.
You could also initialize the property to a default value when you declare it, with a line like `name = '';`.
The constructor is defined using the {{jsxref("Classes/constructor", "constructor")}} keyword. Just like a [constructor outside a class definition](/en-US/docs/Learn/JavaScript/Objects/Basics#introducing_constructors), it will:
- create a new object
- bind `this` to the new object, so you can refer to `this` in your constructor code
- run the code in the constructor
- return the new object.
Given the class declaration code above, you can create and use a new `Person` instance like this:
```js
const giles = new Person("Giles");
giles.introduceSelf(); // Hi! I'm Giles
```
Note that we call the constructor using the name of the class, `Person` in this example.
### Omitting constructors
If you don't need to do any special initialization, you can omit the constructor, and a default constructor will be generated for you:
```js
class Animal {
sleep() {
console.log("zzzzzzz");
}
}
const spot = new Animal();
spot.sleep(); // 'zzzzzzz'
```
## Inheritance
Given our `Person` class above, let's define the `Professor` subclass.
```js
class Professor extends Person {
teaches;
constructor(name, teaches) {
super(name);
this.teaches = teaches;
}
introduceSelf() {
console.log(
`My name is ${this.name}, and I will be your ${this.teaches} professor.`,
);
}
grade(paper) {
const grade = Math.floor(Math.random() * (5 - 1) + 1);
console.log(grade);
}
}
```
We use the {{jsxref("Classes/extends", "extends")}} keyword to say that this class inherits from another class.
The `Professor` class adds a new property `teaches`, so we declare that.
Since we want to set `teaches` when a new `Professor` is created, we define a constructor, which takes the `name` and `teaches` as arguments. The first thing this constructor does is call the superclass constructor using {{jsxref("Operators/super", "super()")}}, passing up the `name` parameter. The superclass constructor takes care of setting `name`. After that, the `Professor` constructor sets the `teaches` property.
> **Note:** If a subclass has any of its own initialization to do, it **must** first call the superclass constructor using `super()`, passing up any parameters that the superclass constructor is expecting.
We've also overridden the `introduceSelf()` method from the superclass, and added a new method `grade()`, to grade a paper (our professor isn't very good, and just assigns random grades to papers).
With this declaration we can now create and use professors:
```js
const walsh = new Professor("Walsh", "Psychology");
walsh.introduceSelf(); // 'My name is Walsh, and I will be your Psychology professor'
walsh.grade("my paper"); // some random grade
```
## Encapsulation
Finally, let's see how to implement encapsulation in JavaScript. In the last article we discussed how we would like to make the `year` property of `Student` private, so we could change the rules about archery classes without breaking any code that uses the `Student` class.
Here's a declaration of the `Student` class that does just that:
```js
class Student extends Person {
#year;
constructor(name, year) {
super(name);
this.#year = year;
}
introduceSelf() {
console.log(`Hi! I'm ${this.name}, and I'm in year ${this.#year}.`);
}
canStudyArchery() {
return this.#year > 1;
}
}
```
In this class declaration, `#year` is a [private data property](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties). We can construct a `Student` object, and it can use `#year` internally, but if code outside the object tries to access `#year` the browser throws an error:
```js
const summers = new Student("Summers", 2);
summers.introduceSelf(); // Hi! I'm Summers, and I'm in year 2.
summers.canStudyArchery(); // true
summers.#year; // SyntaxError
```
> **Note:** Code run in the Chrome console can access private properties outside the class. This is a DevTools-only relaxation of the JavaScript syntax restriction.
Private data properties must be declared in the class declaration, and their names start with `#`.
### Private methods
You can have private methods as well as private data properties. Just like private data properties, their names start with `#`, and they can only be called by the object's own methods:
```js
class Example {
somePublicMethod() {
this.#somePrivateMethod();
}
#somePrivateMethod() {
console.log("You called me?");
}
}
const myExample = new Example();
myExample.somePublicMethod(); // 'You called me?'
myExample.#somePrivateMethod(); // SyntaxError
```
## 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: Object-oriented JavaScript](/en-US/docs/Learn/JavaScript/Objects/Test_your_skills:_Object-oriented_JavaScript).
## Summary
In this article, we've gone through the main tools available in JavaScript for writing object-oriented programs. We haven't covered everything here, but this should be enough to get you started. Our [article on Classes](/en-US/docs/Web/JavaScript/Reference/Classes) is a good place to learn more.
{{PreviousMenuNext("Learn/JavaScript/Objects/Object-oriented_programming", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/objects | data/mdn-content/files/en-us/learn/javascript/objects/test_your_skills_colon__object-oriented_javascript/index.md | ---
title: "Test your skills: Object-oriented JavaScript"
slug: Learn/JavaScript/Objects/Test_your_skills:_Object-oriented_JavaScript
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Classes in JavaScript](/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript) 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 there is an error in your code, it will be logged into the results panel on this page or in the JavaScript console.
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## OOJS 1
In this task we provide you with the start of a definition for a `Shape` class. It has three properties: `name`, `sides`, and `sideLength`. This class only models shapes for which all sides are the same length, like a square or an equilateral triangle.
We'd like you to:
- Add a constructor to this class. The constructor takes arguments for the `name`, `sides`, and `sideLength` properties, and initializes them.
- Add a new method `calcPerimeter()` method to the class, which calculates its perimeter (the length of the shape's outer edge) and logs the result to the console.
- Create a new instance of the `Shape` class called `square`. Give it a `name` of `square`, `4` `sides`, and a `sideLength` of `5`.
- Call your `calcPerimeter()` method on the instance, to see whether it logs the calculation result to the browser's console as expected.
- Create a new instance of `Shape` called `triangle`, with a `name` of `triangle`, `3` `sides` and a `sideLength` of `3`.
- Call `triangle.calcPerimeter()` to check that it works OK.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/oojs/tasks/oojs/oojs1.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/oojs/tasks/oojs/oojs1-download.html) to work in your own editor or in an online editor.
## OOJS 2
Next we'd like you to create a `Square` class that inherits from `Shape`, and adds a `calcArea()` method that calculates the square's area. Also set up the constructor so that the `name` property of `Square` object instances is automatically set to `square`, and the `sides` property is automatically set to `4`. When invoking the constructor, you should therefore just need to provide the `sideLength` property.
Create an instance of the `Square` class called `square` with appropriate property values, and call its `calcPerimeter()` and `calcArea()` methods to show that it works OK.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/oojs/tasks/oojs/oojs2.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/oojs/tasks/oojs/oojs2-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/javascript/objects | data/mdn-content/files/en-us/learn/javascript/objects/object_prototypes/index.md | ---
title: Object prototypes
slug: Learn/JavaScript/Objects/Object_prototypes
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object-oriented_programming", "Learn/JavaScript/Objects")}}
Prototypes are the mechanism by which JavaScript objects inherit features from one another. In this article, we explain what a prototype is, how prototype chains work, and how a prototype for an object can be set.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Understanding JavaScript functions, familiarity with JavaScript basics
(see
<a href="/en-US/docs/Learn/JavaScript/First_steps">First steps</a> and
<a href="/en-US/docs/Learn/JavaScript/Building_blocks"
>Building blocks</a
>), and OOJS basics (see
<a href="/en-US/docs/Learn/JavaScript/Objects/Basics"
>Introduction to objects</a
>).
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand JavaScript object prototypes, how prototype chains work,
and how to set the prototype of an object.
</td>
</tr>
</tbody>
</table>
## The prototype chain
In the browser's console, try creating an object literal:
```js
const myObject = {
city: "Madrid",
greet() {
console.log(`Greetings from ${this.city}`);
},
};
myObject.greet(); // Greetings from Madrid
```
This is an object with one data property, `city`, and one method, `greet()`. If you type the object's name _followed by a period_ into the console, like `myObject.`, then the console will pop up a list of all the properties available to this object. You'll see that as well as `city` and `greet`, there are lots of other properties!
```plain
__defineGetter__
__defineSetter__
__lookupGetter__
__lookupSetter__
__proto__
city
constructor
greet
hasOwnProperty
isPrototypeOf
propertyIsEnumerable
toLocaleString
toString
valueOf
```
Try accessing one of them:
```js
myObject.toString(); // "[object Object]"
```
It works (even if it's not obvious what `toString()` does).
What are these extra properties, and where do they come from?
Every object in JavaScript has a built-in property, which is called its **prototype**. The prototype is itself an object, so the prototype will have its own prototype, making what's called a **prototype chain**. The chain ends when we reach a prototype that has `null` for its own prototype.
> **Note:** The property of an object that points to its prototype is **not** called `prototype`. Its name is not standard, but in practice all browsers use [`__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto). The standard way to access an object's prototype is the {{jsxref("Object/getPrototypeOf", "Object.getPrototypeOf()")}} method.
When you try to access a property of an object: if the property can't be found in the object itself, the prototype is searched for the property. If the property still can't be found, then the prototype's prototype is searched, and so on until either the property is found, or the end of the chain is reached, in which case `undefined` is returned.
So when we call `myObject.toString()`, the browser:
- looks for `toString` in `myObject`
- can't find it there, so looks in the prototype object of `myObject` for `toString`
- finds it there, and calls it.
What is the prototype for `myObject`? To find out, we can use the function `Object.getPrototypeOf()`:
```js
Object.getPrototypeOf(myObject); // Object { }
```
This is an object called `Object.prototype`, and it is the most basic prototype, that all objects have by default. The prototype of `Object.prototype` is `null`, so it's at the end of the prototype chain:

The prototype of an object is not always `Object.prototype`. Try this:
```js
const myDate = new Date();
let object = myDate;
do {
object = Object.getPrototypeOf(object);
console.log(object);
} while (object);
// Date.prototype
// Object { }
// null
```
This code creates a `Date` object, then walks up the prototype chain, logging the prototypes. It shows us that the prototype of `myDate` is a `Date.prototype` object, and the prototype of _that_ is `Object.prototype`.

In fact, when you call familiar methods, like `myDate2.getMonth()`,
you are calling a method that's defined on `Date.prototype`.
## Shadowing properties
What happens if you define a property in an object, when a property with the same name is defined in the object's prototype? Let's see:
```js
const myDate = new Date(1995, 11, 17);
console.log(myDate.getYear()); // 95
myDate.getYear = function () {
console.log("something else!");
};
myDate.getYear(); // 'something else!'
```
This should be predictable, given the description of the prototype chain. When we call `getYear()` the browser first looks in `myDate` for a property with that name, and only checks the prototype if `myDate` does not define it. So when we add `getYear()` to `myDate`, then the version in `myDate` is called.
This is called "shadowing" the property.
## Setting a prototype
There are various ways of setting an object's prototype in JavaScript, and here we'll describe two: `Object.create()` and constructors.
### Using Object.create
The `Object.create()` method creates a new object and allows you to specify an object that will be used as the new object's prototype.
Here's an example:
```js
const personPrototype = {
greet() {
console.log("hello!");
},
};
const carl = Object.create(personPrototype);
carl.greet(); // hello!
```
Here we create an object `personPrototype`, which has a `greet()` method. We then use `Object.create()` to create a new object with `personPrototype` as its prototype. Now we can call `greet()` on the new object, and the prototype provides its implementation.
### Using a constructor
In JavaScript, all functions have a property named `prototype`. When you call a function as a constructor, this property is set as the prototype of the newly constructed object (by convention, in the property named `__proto__`).
So if we set the `prototype` of a constructor, we can ensure that all objects created with that constructor are given that prototype:
```js
const personPrototype = {
greet() {
console.log(`hello, my name is ${this.name}!`);
},
};
function Person(name) {
this.name = name;
}
Object.assign(Person.prototype, personPrototype);
// or
// Person.prototype.greet = personPrototype.greet;
```
Here we create:
- an object `personPrototype`, which has a `greet()` method
- a `Person()` constructor function which initializes the name of the person to create.
We then put the methods defined in `personPrototype` onto the `Person` function's `prototype` property using [Object.assign](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign).
After this code, objects created using `Person()` will get `Person.prototype` as their prototype, which automatically contains the `greet` method.
```js
const reuben = new Person("Reuben");
reuben.greet(); // hello, my name is Reuben!
```
This also explains why we said earlier that the prototype of `myDate` is called `Date.prototype`: it's the `prototype` property of the `Date` constructor.
### Own properties
The objects we create using the `Person` constructor above have two properties:
- a `name` property, which is set in the constructor, so it appears directly on `Person` objects
- a `greet()` method, which is set in the prototype.
It's common to see this pattern, in which methods are defined on the prototype, but data properties are defined in the constructor. That's because methods are usually the same for every object we create, while we often want each object to have its own value for its data properties (just as here where every person has a different name).
Properties that are defined directly in the object, like `name` here, are called **own properties**, and you can check whether a property is an own property using the static {{jsxref("Object/hasOwn", "Object.hasOwn()")}} method:
```js
const irma = new Person("Irma");
console.log(Object.hasOwn(irma, "name")); // true
console.log(Object.hasOwn(irma, "greet")); // false
```
> **Note:** You can also use the non-static {{jsxref("Object/hasOwnProperty", "Object.hasOwnProperty()")}} method here, but we recommend that you use `Object.hasOwn()` if you can.
## Prototypes and inheritance
Prototypes are a powerful and very flexible feature of JavaScript, making it possible to reuse code and combine objects.
In particular they support a version of **inheritance**. Inheritance is a feature of object-oriented programming languages that lets programmers express the idea that some objects in a system are more specialized versions of other objects.
For example, if we're modeling a school, we might have _professors_ and _students_: they are both _people_, so have some features in common (for example, they both have names), but each might add extra features (for example, professors have a subject that they teach), or might implement the same feature in different ways. In an OOP system we might say that professors and students both **inherit from** people.
You can see how in JavaScript, if `Professor` and `Student` objects can have `Person` prototypes, then they can inherit the common properties, while adding and redefining those properties which need to differ.
In the next article we'll discuss inheritance along with the other main features of object-oriented programming languages, and see how JavaScript supports them.
## Summary
This article has covered JavaScript object prototypes, including how prototype object chains allow objects to inherit features from one another, the prototype property and how it can be used to add methods to constructors, and other related topics.
In the next article we'll look at the concepts underlying object-oriented programming.
{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object-oriented_programming", "Learn/JavaScript/Objects")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/objects | data/mdn-content/files/en-us/learn/javascript/objects/object_prototypes/myobject-prototype-chain.svg | <svg xmlns="http://www.w3.org/2000/svg" style="background-color:#fff" xmlns:xlink="http://www.w3.org/1999/xlink" width="792" height="192" viewBox="-0.5 -0.5 792 192"><path fill="#fff" stroke="#000" stroke-width="1.5" pointer-events="all" d="M19.5 34.5h120v120h-120z"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:78px;height:1px;padding-top:63px;margin-left:14px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:12px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;white-space:normal;word-wrap:normal"><div><font>myObject</font></div><div><font/></div><div align="left"><font>city</font></div><div align="left"><font>greet()</font><br/></div></div></div></div></foreignObject><text x="53" y="67" font-family="Helvetica" font-size="12" text-anchor="middle">myObject...</text></switch><path fill="#fff" stroke="#000" stroke-width="1.5" pointer-events="all" d="M349.5 19.5h195v150h-195z"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:128px;height:1px;padding-top:63px;margin-left:234px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:12px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;white-space:normal;word-wrap:normal"><div><font/></div><div><font>Object.prototype</font></div><div><font/></div><div align="left"><font>hasOwnProperty()</font></div><div align="left"><font>isPrototypeOf()</font></div><div align="left"><font>...</font></div><div align="left"><font/></div></div></div></div></foreignObject><text x="298" y="67" font-family="Helvetica" font-size="12" text-anchor="middle">Object.prototype...</text></switch><path d="M139.5 94.5h200.45" fill="none" stroke="#000" stroke-width="1.5" stroke-miterlimit="10" pointer-events="stroke"/><path d="m347.82 94.5-10.5 5.25 2.63-5.25-2.63-5.25z" stroke="#000" stroke-width="1.5" stroke-miterlimit="10" pointer-events="all"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:64px;margin-left:156px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:11px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;background-color:#fff;white-space:nowrap"><font>__proto__</font></div></div></div></foreignObject><text x="156" y="67" font-family="Helvetica" font-size="11" text-anchor="middle">__proto__</text></switch><path fill="none" pointer-events="all" d="M709.5 79.5h60v30h-60z"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:38px;height:1px;padding-top:63px;margin-left:474px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:12px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;white-space:normal;word-wrap:normal"><font>null</font></div></div></div></foreignObject><text x="493" y="67" font-family="Helvetica" font-size="12" text-anchor="middle">null</text></switch><path d="M544.5 94.5h155.45" fill="none" stroke="#000" stroke-width="1.5" stroke-miterlimit="10" pointer-events="stroke"/><path d="m707.82 94.5-10.5 5.25 2.63-5.25-2.63-5.25z" stroke="#000" stroke-width="1.5" stroke-miterlimit="10" pointer-events="all"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:64px;margin-left:414px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:11px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;background-color:#fff;white-space:nowrap"><font>__proto__</font></div></div></div></foreignObject><text x="414" y="67" font-family="Helvetica" font-size="11" text-anchor="middle">__proto__</text></switch><switch><a transform="translate(0 -5)" xlink:href="https://www.diagrams.net/doc/faq/svg-export-text-problems" target="_blank"><text text-anchor="middle" font-size="10" x="50%" y="100%">Viewer does not support full SVG 1.1</text></a></switch></svg> | 0 |
data/mdn-content/files/en-us/learn/javascript/objects | data/mdn-content/files/en-us/learn/javascript/objects/object_prototypes/mydate-prototype-chain.svg | <svg xmlns="http://www.w3.org/2000/svg" style="background-color:#fff" xmlns:xlink="http://www.w3.org/1999/xlink" width="1087" height="192" viewBox="-0.5 -0.5 1087 192"><path fill="#fff" stroke="#000" stroke-width="1.5" pointer-events="all" d="M19.5 34.5h120v120h-120z"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:78px;height:1px;padding-top:63px;margin-left:14px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:12px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;white-space:normal;word-wrap:normal"><font>myDate</font></div></div></div></foreignObject><text x="53" y="67" font-family="Helvetica" font-size="12" text-anchor="middle">myDate</text></switch><path fill="#fff" stroke="#000" stroke-width="1.5" pointer-events="all" d="M660 19.5h195v150H660z"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:128px;height:1px;padding-top:63px;margin-left:441px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:12px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;white-space:normal;word-wrap:normal"><div><font/></div><div><font>Object.prototype</font></div><div><font/></div><div align="left"><font>hasOwnProperty()</font></div><div align="left"><font>isPrototypeOf()</font></div><div align="left"><font>...</font></div><div align="left"><font/></div></div></div></div></foreignObject><text x="505" y="67" font-family="Helvetica" font-size="12" text-anchor="middle">Object.prototype...</text></switch><path d="M495 94.5h155.45" fill="none" stroke="#000" stroke-width="1.5" stroke-miterlimit="10" pointer-events="stroke"/><path d="m658.32 94.5-10.5 5.25 2.63-5.25-2.63-5.25z" stroke="#000" stroke-width="1.5" stroke-miterlimit="10" pointer-events="all"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:64px;margin-left:384px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:11px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;background-color:#fff;white-space:nowrap"><font>__proto__</font></div></div></div></foreignObject><text x="384" y="67" font-family="Helvetica" font-size="11" text-anchor="middle">__proto__</text></switch><path fill="none" pointer-events="all" d="M1005 79.5h60v30h-60z"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:38px;height:1px;padding-top:63px;margin-left:671px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:12px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;white-space:normal;word-wrap:normal"><font>null</font></div></div></div></foreignObject><text x="690" y="67" font-family="Helvetica" font-size="12" text-anchor="middle">null</text></switch><path d="M855 94.5h140.45" fill="none" stroke="#000" stroke-width="1.5" stroke-miterlimit="10" pointer-events="stroke"/><path d="m1003.32 94.5-10.5 5.25 2.63-5.25-2.63-5.25z" stroke="#000" stroke-width="1.5" stroke-miterlimit="10" pointer-events="all"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:64px;margin-left:615px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:11px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;background-color:#fff;white-space:nowrap"><font>__proto__</font></div></div></div></foreignObject><text x="615" y="67" font-family="Helvetica" font-size="11" text-anchor="middle">__proto__</text></switch><path fill="#fff" stroke="#000" stroke-width="1.5" pointer-events="all" d="M300 19.5h195v150H300z"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:128px;height:1px;padding-top:63px;margin-left:201px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:12px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;white-space:normal;word-wrap:normal"><div><font/></div><div><font>Date.prototype</font></div><div><font/></div><div align="left"><font>getMonth()</font></div><div align="left"><font>getYear()</font></div><div align="left"><font>...</font></div><div align="left"><font/></div></div></div></div></foreignObject><text x="265" y="67" font-family="Helvetica" font-size="12" text-anchor="middle">Date.prototype...</text></switch><path d="M139.5 94.5h150.95" fill="none" stroke="#000" stroke-width="1.5" stroke-miterlimit="10" pointer-events="stroke"/><path d="m298.32 94.5-10.5 5.25 2.63-5.25-2.63-5.25z" stroke="#000" stroke-width="1.5" stroke-miterlimit="10" pointer-events="all"/><switch transform="matrix(1.5 0 0 1.5 -.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:64px;margin-left:145px"><div style="box-sizing:border-box;font-size:0;text-align:center"><div style="display:inline-block;font-size:11px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:all;background-color:#fff;white-space:nowrap"><font>__proto__</font></div></div></div></foreignObject><text x="145" y="67" font-family="Helvetica" font-size="11" text-anchor="middle">__proto__</text></switch><switch><a transform="translate(0 -5)" xlink:href="https://www.diagrams.net/doc/faq/svg-export-text-problems" target="_blank"><text text-anchor="middle" font-size="10" x="50%" y="100%">Viewer does not support full SVG 1.1</text></a></switch></svg> | 0 |
data/mdn-content/files/en-us/learn/javascript/objects | data/mdn-content/files/en-us/learn/javascript/objects/test_your_skills_colon__object_basics/index.md | ---
title: "Test your skills: Object basics"
slug: Learn/JavaScript/Objects/Test_your_skills:_Object_basics
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [JavaScript object basics](/en-US/docs/Learn/JavaScript/Objects/Basics) 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 there is an error in your code, it will be logged into the results panel on this page or in the JavaScript console.
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Object basics 1
In this task you are provided with an object literal, and your tasks are to
- Store the value of the `name` property inside the `catName` variable, using bracket notation.
- Run the `greeting()` method using dot notation (it will log the greeting to the browser's console).
- Update the `color` property value to `black`.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/oojs/tasks/object-basics/object-basics1.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/oojs/tasks/object-basics/object-basics1-download.html) to work in your own editor or in an online editor.
## Object basics 2
In our next task, we want you to have a go at creating your own object literal to represent one of your favorite bands. The required properties are:
- `name`: A string representing the band name.
- `nationality`: A string representing the country the band comes from.
- `genre`: What type of music the band plays.
- `members`: A number representing the number of members the band has.
- `formed`: A number representing the year the band formed.
- `split`: A number representing the year the band split up, or `false` if they are still together.
- `albums`: An array representing the albums released by the band. Each array item should be an object containing the following members:
- `name`: A string representing the name of the album.
- `released`: A number representing the year the album was released.
Include at least two albums in the `albums` array.
Once you've done this, you should then write a string to the variable `bandInfo`, which will contain a small biography detailing their name, nationality, years active, and style, and the title and release date of their first album.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/oojs/tasks/object-basics/object-basics2.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/oojs/tasks/object-basics/object-basics2-download.html) to work in your own editor or in an online editor.
## Object basics 3
In this task, we want you to return to the `cat` object literal from Task 1. We want you to rewrite the `greeting()` method so that it logs `"Hello, said Bertie the Cymric."` to the browser's console, but in a way that will work across _any_ cat object of the same structure, regardless of its name or breed.
When you are done, write your own object called `cat2`, which has the same structure, exactly the same `greeting()` method, but a different `name`, `breed`, and `color`.
Call both `greeting()` methods to check that they log appropriate greetings to the console.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/oojs/tasks/object-basics/object-basics3.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/oojs/tasks/object-basics/object-basics3-download.html) to work in your own editor or in an online editor.
## Object basics 4
In the code you wrote for Task 3, the `greeting()` method is defined twice, once for each cat. This isn't ideal (specifically, it violates a principle in programming sometimes called [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) or "Don't Repeat Yourself").
In this task we want you to improve the code so `greeting()` is only defined once, and every `cat` instance gets its own `greeting()` method. Hint: you should use a JavaScript constructor to create `cat` instances.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/oojs/tasks/object-basics/object-basics4.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/oojs/tasks/object-basics/object-basics4-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/javascript | data/mdn-content/files/en-us/learn/javascript/howto/index.md | ---
title: Solve common problems in your JavaScript code
slug: Learn/JavaScript/Howto
page-type: landing-page
---
{{LearnSidebar}}
The following links point to solutions to common problems you may encounter when writing JavaScript.
## Common beginner's mistakes
### Correct spelling and casing
If your code doesn't work and/or the browser complains that something is undefined, check that you've spelt all your variable names, function names, etc. correctly.
Some common built-in browser functions that cause problems are:
| Correct | Wrong |
| -------------------------- | ------------------------- |
| `getElementsByTagName()` | `getElementByTagName()` |
| `getElementsByName()` | `getElementByName()` |
| `getElementsByClassName()` | `getElementByClassName()` |
| `getElementById()` | `getElementsById()` |
### Semicolon position
You need to make sure you don't place any semicolons incorrectly. For example:
| Correct | Wrong |
| --------------------------- | --------------------------- |
| `elem.style.color = 'red';` | `elem.style.color = 'red;'` |
### Functions
There are a number of things that can go wrong with functions.
One of the most common errors is to declare the function, but not call it anywhere. For example:
```js
function myFunction() {
alert("This is my function.");
}
```
This code won't do anything unless you call it with the following statement:
```js
myFunction();
```
#### Function scope
Remember that [functions have their own scope](/en-US/docs/Learn/JavaScript/Building_blocks/Functions#function_scope_and_conflicts) β you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or [return the value](/en-US/docs/Learn/JavaScript/Building_blocks/Return_values) from the function.
#### Running code after a return statement
Remember also that when you return from a function, the JavaScript interpreter exits the function β no code after the return statement will run.
In fact, some browsers (like Firefox) will give you an error message in the developer console if you have code after a return statement. Firefox gives you "unreachable code after return statement".
### Object notation versus normal assignment
When you assign something normally in JavaScript, you use a single equals sign, e.g.:
```js
const myNumber = 0;
```
With [Objects](/en-US/docs/Learn/JavaScript/Objects), however, you need to take care to use the correct syntax. The object must be surrounded by curly braces, member names must be separated from their values using colons, and members must be separated by commas. For example:
```js
const myObject = {
name: "Chris",
age: 38,
};
```
## Basic definitions
- [What is JavaScript?](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#a_high-level_definition)
- [What is a variable?](/en-US/docs/Learn/JavaScript/First_steps/Variables#what_is_a_variable)
- [What are strings?](/en-US/docs/Learn/JavaScript/First_steps/Strings)
- [What is an array?](/en-US/docs/Learn/JavaScript/First_steps/Arrays#what_is_an_array)
- [What is a loop?](/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code)
- [What is a function?](/en-US/docs/Learn/JavaScript/Building_blocks/Functions)
- [What is an event?](/en-US/docs/Learn/JavaScript/Building_blocks/Events)
- [What is an object?](/en-US/docs/Learn/JavaScript/Objects/Basics#object_basics)
- [What is JSON?](/en-US/docs/Learn/JavaScript/Objects/JSON#no_really_what_is_json)
- [What is a web API?](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction#what_are_apis)
- [What is the DOM?](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents#the_document_object_model)
## Basic use cases
### General
- [How do you add JavaScript to your page?](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#how_do_you_add_javascript_to_your_page)
- [How do you add comments to JavaScript code?](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#comments)
### Variables
- [How do you declare a variable?](/en-US/docs/Learn/JavaScript/First_steps/Variables#declaring_a_variable)
- [How do you initialize a variable with a value?](/en-US/docs/Learn/JavaScript/First_steps/Variables#initializing_a_variable)
- [How do you update a variable's value?](/en-US/docs/Learn/JavaScript/First_steps/Variables#updating_a_variable) (also see [Assignment operators](/en-US/docs/Learn/JavaScript/First_steps/Math#assignment_operators))
- [What data types can values have in JavaScript?](/en-US/docs/Learn/JavaScript/First_steps/Variables#variable_types)
- [What does 'loosely typed' mean?](/en-US/docs/Learn/JavaScript/First_steps/Variables#dynamic_typing)
### Math
- [What types of number do you have to deal with in web development?](/en-US/docs/Learn/JavaScript/First_steps/Math#types_of_numbers)
- [How do you do basic math in JavaScript?](/en-US/docs/Learn/JavaScript/First_steps/Math#arithmetic_operators)
- [What is operator precedence, and how is it handled in JavaScript?](/en-US/docs/Learn/JavaScript/First_steps/Math#operator_precedence)
- [How do you increment and decrement values in JavaScript?](/en-US/docs/Learn/JavaScript/First_steps/Math#increment_and_decrement_operators)
- [How do you compare values in JavaScript?](/en-US/docs/Learn/JavaScript/First_steps/Math#comparison_operators) (e.g. to see which one is bigger, or to see if one value is equal to another).
### Strings
- [How do you create a string in JavaScript?](/en-US/docs/Learn/JavaScript/First_steps/Strings#creating_a_string)
- [Do you have to use single quotes or double quotes?](/en-US/docs/Learn/JavaScript/First_steps/Strings#single_quotes_vs._double_quotes)
- [How do you escape characters in strings?](/en-US/docs/Learn/JavaScript/First_steps/Strings#escaping_characters_in_a_string)
- [How do you join strings together?](/en-US/docs/Learn/JavaScript/First_steps/Strings#concatenating_strings)
- [Can you join strings and numbers together?](/en-US/docs/Learn/JavaScript/First_steps/Strings#numbers_vs._strings)
- [How do you find the length of a string?](/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#finding_the_length_of_a_string)
- [How do you find what character is at a certain position in a string?](/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#retrieving_a_specific_string_character)
- [How do you find and extract a specific substring from a string?](/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#extracting_a_substring_from_a_string)
- [How do you change the case of a string?](/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#changing_case)
- [How do you replace one specific substring with another?](/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#updating_parts_of_a_string)
### Arrays
- [How do you create an array?](/en-US/docs/Learn/JavaScript/First_steps/Arrays#creating_arrays)
- [How do you access and modify the items in an array?](/en-US/docs/Learn/JavaScript/First_steps/Arrays#accessing_and_modifying_array_items) (this includes multidimensional arrays)
- [How do you find the length of an array?](/en-US/docs/Learn/JavaScript/First_steps/Arrays#finding_the_length_of_an_array)
- [How do you add items to an array?](/en-US/docs/Learn/JavaScript/First_steps/Arrays#adding_items)
- [How do you remove items from an array?](/en-US/docs/Learn/JavaScript/First_steps/Arrays#removing_items)
- [How do you split a string into array items, or join array items into a string?](/en-US/docs/Learn/JavaScript/First_steps/Arrays#converting_between_strings_and_arrays)
### Debugging JavaScript
- [What are the basic types of error?](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong#types_of_error)
- [What are browser developer tools, and how do you access them?](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools)
- [How do you log a value to the JavaScript console?](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript#the_console_api)
- [How do you use breakpoints and other JavaScript debugging features?](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript#using_the_javascript_debugger)
For more information on JavaScript debugging, see [Handling common JavaScript problems](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript). Also, see [Other common errors](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong#other_common_errors) for a description of common errors.
### Making decisions in code
- [How do you execute different blocks of code, depending on a variable's value or other condition?](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals)
- [How do you use if ...else statements?](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#if...else_statements)
- [How do you nest one decision block inside another?](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#nesting_if...else)
- [How do you use AND, OR, and NOT operators in JavaScript?](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#logical_operators_and_or_and_not)
- [How do you conveniently handle a large number of choices for one condition?](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#switch_statements)
- [How do you use a ternary operator to make a quick choice between two options based on a true or false test?](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#ternary_operator)
### Looping/iteration
- [How do you run the same bit of code over and over again?](/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code)
- [How do you exit a loop before the end if a certain condition is met?](/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#exiting_loops_with_break)
- [How do you skip to the next iteration of a loop if a certain condition is met?](/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#skipping_iterations_with_continue)
- [How do you use while and do...while loops?](/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#while_and_do_..._while)
## Intermediate use cases
### Functions
- [How do you find functions in the browser?](/en-US/docs/Learn/JavaScript/Building_blocks/Functions#built-in_browser_functions)
- [What is the difference between a function and a method?](/en-US/docs/Learn/JavaScript/Building_blocks/Functions#functions_versus_methods)
- [How do you create your own functions?](/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function)
- [How do you run (call, or invoke) a function?](/en-US/docs/Learn/JavaScript/Building_blocks/Functions#invoking_functions)
- [What is an anonymous function?](/en-US/docs/Learn/JavaScript/Building_blocks/Functions#anonymous_functions)
- [How do you specify parameters (or arguments) when invoking a function?](/en-US/docs/Learn/JavaScript/Building_blocks/Functions#function_parameters)
- [What is function scope?](/en-US/docs/Learn/JavaScript/Building_blocks/Functions#function_scope_and_conflicts)
- [What are return values, and how do you use them?](/en-US/docs/Learn/JavaScript/Building_blocks/Return_values)
### Objects
- [How do you create an object?](/en-US/docs/Learn/JavaScript/Objects/Basics#object_basics)
- [What is dot notation?](/en-US/docs/Learn/JavaScript/Objects/Basics#dot_notation)
- [What is bracket notation?](/en-US/docs/Learn/JavaScript/Objects/Basics#bracket_notation)
- [How do you get and set the methods and properties of an object?](/en-US/docs/Learn/JavaScript/Objects/Basics#setting_object_members)
- [What is `this`, in the context of an object?](/en-US/docs/Learn/JavaScript/Objects/Basics#what_is_this)
- [What is object-oriented programming?](/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript#object-oriented_programming_from_10000_meters)
- [What are constructors and instances, and how do you create them?](/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript#constructors_and_object_instances)
- [What different ways are there to create objects in JavaScript?](/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript#other_ways_to_create_object_instances)
### JSON
- [How do you structure JSON data, and read it from JavaScript?](/en-US/docs/Learn/JavaScript/Objects/JSON#json_structure)
- [How can you load a JSON file into a page?](/en-US/docs/Learn/JavaScript/Objects/JSON#loading_our_json)
- [How do you convert a JSON object to a text string, and back again?](/en-US/docs/Learn/JavaScript/Objects/JSON#converting_between_objects_and_text)
### Events
- [What are event handlers and how do you use them?](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_handler_properties)
- [What are inline event handlers?](/en-US/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%e2%80%94_don%27t_use_these)
- [What does the `addEventListener()` function do, and how do you use it?](/en-US/docs/Learn/JavaScript/Building_blocks/Events#using_addeventlistener)
- [Which mechanism should I use to add event code to my web pages?](/en-US/docs/Learn/JavaScript/Building_blocks/Events#what_mechanism_should_i_use)
- [What are event objects, and how do you use them?](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_objects)
- [How do you prevent default event behavior?](/en-US/docs/Learn/JavaScript/Building_blocks/Events#preventing_default_behavior)
- [How do events fire on nested elements? (event propagation, also related β event bubbling and capturing)](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture)
- [What is event delegation, and how does it work?](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_delegation)
### Object-oriented JavaScript
- [What are object prototypes?](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes)
- [What is the constructor property, and how can you use it?](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes#the_constructor_property)
- [How do you add methods to the constructor?](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes#modifying_prototypes)
- [How do you create a new constructor that inherits its members from a parent constructor?](/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript)
- [When should you use inheritance in JavaScript?](/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript#object_member_summary)
### Web APIs
- [How do you manipulate the DOM (e.g. adding or removing elements) using JavaScript?](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents#active_learning_basic_dom_manipulation)
| 0 |
data/mdn-content/files/en-us/learn/javascript | data/mdn-content/files/en-us/learn/javascript/first_steps/index.md | ---
title: JavaScript First Steps
slug: Learn/JavaScript/First_steps
page-type: learn-module
---
{{LearnSidebar}}
In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key building blocks in detail, such as variables, strings, numbers and arrays.
> **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 don't need any previous JavaScript knowledge, but you should have some familiarity with HTML and CSS. You are advised to work through the following modules before starting on JavaScript:
- [Getting started with the Web](/en-US/docs/Learn/Getting_started_with_the_web) (which includes a really [basic JavaScript introduction](/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics)).
- [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML).
- [Introduction to CSS](/en-US/docs/Learn/CSS/First_steps).
> **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
- [What is JavaScript?](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript)
- : Welcome to the MDN beginner's JavaScript course! In this first article we will look at JavaScript from a high level, answering questions such as "what is it?", and "what is it doing?", and making sure you are comfortable with JavaScript's purpose.
- [A first splash into JavaScript](/en-US/docs/Learn/JavaScript/First_steps/A_first_splash)
- : Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course on the basic features of JavaScript via a completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step.
- [What went wrong? Troubleshooting JavaScript](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong)
- : When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear β this article aims to save you from tearing your hair out over such problems by providing you with some simple tips on how to find and fix errors in JavaScript programs.
- [Storing the information you need β Variables](/en-US/docs/Learn/JavaScript/First_steps/Variables)
- : After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of JavaScript β Variables.
- [Basic math in JavaScript β numbers and operators](/en-US/docs/Learn/JavaScript/First_steps/Math)
- : At this point in the course, we discuss maths in JavaScript β how we can combine operators and other features to successfully manipulate numbers to do our bidding.
- [Handling text β strings in JavaScript](/en-US/docs/Learn/JavaScript/First_steps/Strings)
- : Next, we'll turn our attention to strings β this is what pieces of text are called in programming. In this article, we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in strings, and joining them together.
- [Useful string methods](/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods)
- : Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.
- [Arrays](/en-US/docs/Learn/JavaScript/First_steps/Arrays)
- : In the final article of this module, we'll look at arrays β a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
## Assessments
The following assessment will test your understanding of the JavaScript basics covered in the guides above.
- [Silly story generator](/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator)
- : In this assessment, you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!
## See also
- [Learn JavaScript](https://learnjavascript.online/)
- : An excellent resource for aspiring web developers β Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment.
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/strings/index.md | ---
title: Handling text β strings in JavaScript
slug: Learn/JavaScript/First_steps/Strings
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}
Next, we'll turn our attention to strings β this is what pieces of text are called in programming. In this article, we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in strings, and joining strings together.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To gain familiarity with the basics of strings in JavaScript.</td>
</tr>
</tbody>
</table>
## The power of words
Words are very important to humans β they are a large part of how we communicate. Since the web is a largely text-based medium designed to allow humans to communicate and share information, it is useful for us to have control over the words that appear on it. {{glossary("HTML")}} provides structure and meaning to text, {{glossary("CSS")}} allows us to precisely style it, and JavaScript offers many features for manipulating strings. These include creating custom welcome messages and prompts, showing the right text labels when needed, sorting terms into the desired order, and much more.
Pretty much all of the programs we've shown you so far in the course have involved some string manipulation.
## Declaring strings
Strings are dealt with similarly to numbers at first glance, but when you dig deeper you'll start to see some notable differences. Let's start by entering some basic lines into the [browser developer console](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools) to familiarize ourselves.
To start with, enter the following lines:
```js
const string = "The revolution will not be televised.";
console.log(string);
```
Just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. The only difference here is that when writing a string, you need to surround the value with quotes.
If you don't do this, or miss one of the quotes, you'll get an error. Try entering the following lines:
```js example-bad
const badString1 = This is a test;
const badString2 = 'This is a test;
const badString3 = This is a test';
```
These lines don't work because any text without quotes around it is interpreted as a variable name, property name, reserved word, or similar. If the browser doesn't recognize the unquoted text, then an error is raised (e.g., "missing; before statement"). If the browser can detect where a string starts but not its end (owing to the missing second quote), it reports an "unterminated string literal" error. If your program is raising such errors, then go back and check all your strings to make sure you have no missing quotation marks.
The following will work if you previously defined the variable `string` β try it now:
```js
const badString = string;
console.log(badString);
```
`badString` is now set to have the same value as `string`.
### Single quotes, double quotes, and backticks
In JavaScript, you can choose single quotes (`'`), double quotes (`"`), or backticks (`` ` ``) to wrap your strings in. All of the following will work:
```js-nolint
const single = 'Single quotes';
const double = "Double quotes";
const backtick = `Backtick`;
console.log(single);
console.log(double);
console.log(backtick);
```
You must use the same character for the start and end of a string, or you will get an error:
```js-nolint example-bad
const badQuotes = 'This is not allowed!";
```
Strings declared using single quotes and strings declared using double quotes are the same, and which you use is down to personal preference β although it is good practice to choose one style and use it consistently in your code.
Strings declared using backticks are a special kind of string called a [_template literal_](/en-US/docs/Web/JavaScript/Reference/Template_literals). In most ways, template literals are like normal strings, but they have some special properties:
- you can [embed JavaScript](#embedding_javascript) in them
- you can declare template literals over [multiple lines](#multiline_strings)
## Embedding JavaScript
Inside a template literal, you can wrap JavaScript variables or expressions inside `${ }`, and the result will be included in the string:
```js
const name = "Chris";
const greeting = `Hello, ${name}`;
console.log(greeting); // "Hello, Chris"
```
You can use the same technique to join together two variables:
```js
const one = "Hello, ";
const two = "how are you?";
const joined = `${one}${two}`;
console.log(joined); // "Hello, how are you?"
```
Joining strings together like this is called _concatenation_.
### Concatenation in context
Let's have a look at concatenation being used in action:
```html
<button>Press me</button>
<div id="greeting"></div>
```
```js
const button = document.querySelector("button");
function greet() {
const name = prompt("What is your name?");
const greeting = document.querySelector("#greeting");
greeting.textContent = `Hello ${name}, nice to see you!`;
}
button.addEventListener("click", greet);
```
{{ EmbedLiveSample('Concatenation_in_context', '100%', 50) }}
Here, we are using the {{domxref("window.prompt()", "window.prompt()")}} function, which prompts the user to answer a question via a popup dialog box and then stores the text they enter inside a given variable β in this case `name`. We then display a string that inserts the name into a generic greeting message.
### Concatenation using "+"
You can use `${}` only with template literals, not normal strings. You can concatenate normal strings using the `+` operator:
```js
const greeting = "Hello";
const name = "Chris";
console.log(greeting + ", " + name); // "Hello, Chris"
```
However, template literals usually give you more readable code:
```js
const greeting = "Hello";
const name = "Chris";
console.log(`${greeting}, ${name}`); // "Hello, Chris"
```
### Including expressions in strings
You can include JavaScript expressions in template literals, as well as just variables, and the results will be included in the result:
```js
const song = "Fight the Youth";
const score = 9;
const highestScore = 10;
const output = `I like the song ${song}. I gave it a score of ${
(score / highestScore) * 100
}%.`;
console.log(output); // "I like the song Fight the Youth. I gave it a score of 90%."
```
## Multiline strings
Template literals respect the line breaks in the source code, so you can write strings that span multiple lines like this:
```js
const newline = `One day you finally knew
what you had to do, and began,`;
console.log(newline);
/*
One day you finally knew
what you had to do, and began,
*/
```
To have the equivalent output using a normal string you'd have to include line break characters (`\n`) in the string:
```js
const newline = "One day you finally knew\nwhat you had to do, and began,";
console.log(newline);
/*
One day you finally knew
what you had to do, and began,
*/
```
See our [Template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals) reference page for more examples and details of advanced features.
## Including quotes in strings
Since we use quotes to indicate the start and end of strings, how can we include actual quotes in strings? We know that this won't work:
```js-nolint example-bad
const badQuotes = "She said "I think so!"";
```
One common option is to use one of the other characters to declare the string:
```js-nolint
const goodQuotes1 = 'She said "I think so!"';
const goodQuotes2 = `She said "I'm not going in there!"`;
```
Another option is to _escape_ the problem quotation mark. Escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character. Try this:
```js-nolint
const bigmouth = 'I\'ve got no right to take my placeβ¦';
console.log(bigmouth);
```
You can use the same technique to insert other special characters. See [Escape sequences](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#escape_sequences) for more details.
## Numbers vs. strings
What happens when we try to concatenate a string and a number? Let's try it in our console:
```js
const name = "Front ";
const number = 242;
console.log(name + number); // "Front 242"
```
You might expect this to return an error, but it works just fine. How numbers should be displayed as strings is fairly well-defined, so the browser automatically converts the number to a string and concatenates the two strings.
If you have a numeric variable that you want to convert to a string or a string variable that you want to convert to a number, you can use the following two constructs:
- The {{jsxref("Number/Number", "Number()")}} function converts anything passed to it into a number if it can. Try the following:
```js
const myString = "123";
const myNum = Number(myString);
console.log(typeof myNum);
// number
```
- Conversely, the {{jsxref("String/String", "String()")}} function converts its argument to a string. Try this:
```js
const myNum2 = 123;
const myString2 = String(myNum2);
console.log(typeof myString2);
// string
```
These constructs can be really useful in some situations. For example, if a user enters a number into a form's text field, it's a string. However, if you want to add this number to something, you'll need it to be a number, so you could pass it through `Number()` to handle this. We did exactly this in our [Number Guessing Game, in line 59](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/first-splash/number-guessing-game.html#L59).
## Conclusion
So that's the very basics of strings covered in JavaScript. In the next article, we'll build on this, looking at some of the built-in methods available to strings in JavaScript and how we can use them to manipulate our strings into just the form we want.
{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/a_first_splash/index.md | ---
title: A first splash into JavaScript
slug: Learn/JavaScript/First_steps/A_first_splash
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}
Now you've learned something about the theory of JavaScript and what you can do with it, we are going to give you an idea of what the process of creating a simple JavaScript program is like, by guiding you through a practical tutorial. Here you'll build up a simple "Guess the number" game, step by step.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To have a first bit of experience at writing some JavaScript, and gain
at least a basic understanding of what writing a JavaScript program
involves.
</td>
</tr>
</tbody>
</table>
We want to set really clear expectations here: You won't be expected to learn JavaScript by the end of this article, or even understand all the code we are asking you to write. Instead, we want to give you an idea of how JavaScript's features work together, and what writing JavaScript feels like. In subsequent articles you'll revisit all the features shown here in a lot more detail, so don't worry if you don't understand it all immediately!
> **Note:** Many of the code features you'll see in JavaScript are the same as in other programming languages β functions, loops, etc. The code syntax looks different, but the concepts are still largely the same.
## Thinking like a programmer
One of the hardest things to learn in programming is not the syntax you need to learn, but how to apply it to solve real-world problems. You need to start thinking like a programmer β this generally involves looking at descriptions of what your program needs to do, working out what code features are needed to achieve those things, and how to make them work together.
This requires a mixture of hard work, experience with the programming syntax, and practice β plus a bit of creativity. The more you code, the better you'll get at it. We can't promise that you'll develop "programmer brain" in five minutes, but we will give you plenty of opportunities to practice thinking like a programmer throughout the course.
With that in mind, let's look at the example we'll be building up in this article, and review the general process of dissecting it into tangible tasks.
## Example β Guess the number game
In this article we'll show you how to build up the simple game you can see below:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/first-splash/number-guessing-game", 900, 300)}}
Have a go at playing it β familiarize yourself with the game before you move on.
Let's imagine your boss has given you the following brief for creating this game:
> I want you to create a simple guess the number type game. It should choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. After each turn, the player should be told if they are right or wrong, and if they are wrong, whether the guess was too low or too high. It should also tell the player what numbers they previously guessed. The game will end once the player guesses correctly, or once they run out of turns. When the game ends, the player should be given an option to start playing again.
Upon looking at this brief, the first thing we can do is to start breaking it down into simple actionable tasks, in as much of a programmer mindset as possible:
1. Generate a random number between 1 and 100.
2. Record the turn number the player is on. Start it on 1.
3. Provide the player with a way to guess what the number is.
4. Once a guess has been submitted first record it somewhere so the user can see their previous guesses.
5. Next, check whether it is the correct number.
6. If it is correct:
1. Display congratulations message.
2. Stop the player from being able to enter more guesses (this would mess the game up).
3. Display control allowing the player to restart the game.
7. If it is wrong and the player has turns left:
1. Tell the player they are wrong and whether their guess was too high or too low.
2. Allow them to enter another guess.
3. Increment the turn number by 1.
8. If it is wrong and the player has no turns left:
1. Tell the player it is game over.
2. Stop the player from being able to enter more guesses (this would mess the game up).
3. Display control allowing the player to restart the game.
9. Once the game restarts, make sure the game logic and UI are completely reset, then go back to step 1.
Let's now move forward, looking at how we can turn these steps into code, building up the example, and exploring JavaScript features as we go.
### Initial setup
To begin this tutorial, we'd like you to make a local copy of the [number-guessing-game-start.html](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/first-splash/number-guessing-game-start.html) file ([see it live here](https://mdn.github.io/learning-area/javascript/introduction-to-js-1/first-splash/number-guessing-game-start.html)). Open it in both your text editor and your web browser. At the moment you'll see a simple heading, paragraph of instructions and form for entering a guess, but the form won't currently do anything.
The place where we'll be adding all our code is inside the {{htmlelement("script")}} element at the bottom of the HTML:
```html
<script>
// Your JavaScript goes here
</script>
```
### Adding variables to store our data
Let's get started. First of all, add the following lines inside your {{htmlelement("script")}} element:
```js
let randomNumber = Math.floor(Math.random() * 100) + 1;
const guesses = document.querySelector(".guesses");
const lastResult = document.querySelector(".lastResult");
const lowOrHi = document.querySelector(".lowOrHi");
const guessSubmit = document.querySelector(".guessSubmit");
const guessField = document.querySelector(".guessField");
let guessCount = 1;
let resetButton;
```
This section of the code sets up the variables and constants we need to store the data our program will use.
Variables are basically names for values (such as numbers, or strings of text). You create a variable with the keyword `let` followed by a name for your variable.
Constants are also used to name values, but unlike variables, you can't change the value once set. In this case, we are using constants to store references to parts of our user interface. The text inside some of these elements might change, but each constant always references the same HTML element that it was initialized with. You create a constant with the keyword `const` followed by a name for the constant.
You can assign a value to your variable or constant with an equals sign (`=`) followed by the value you want to give it.
In our example:
- The first variable β `randomNumber` β is assigned a random number between 1 and 100, calculated using a mathematical algorithm.
- The first three constants are each made to store a reference to the results paragraphs in our HTML, and are used to insert values into the paragraphs later on in the code (note how they are inside a `<div>` element, which is itself used to select all three later on for resetting, when we restart the game):
```html
<div class="resultParas">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
```
- The next two constants store references to the form text input and submit button and are used to control submitting the guess later on.
```html
<label for="guessField">Enter a guess: </label>
<input type="number" id="guessField" class="guessField" />
<input type="submit" value="Submit guess" class="guessSubmit" />
```
- Our final two variables store a guess count of 1 (used to keep track of how many guesses the player has had), and a reference to a reset button that doesn't exist yet (but will later).
> **Note:** You'll learn a lot more about variables and constants later on in the course, starting with the article [Storing the information you need β Variables](/en-US/docs/Learn/JavaScript/First_steps/Variables).
### Functions
Next, add the following below your previous JavaScript:
```js
function checkGuess() {
alert("I am a placeholder");
}
```
Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword `function`, followed by a name, with parentheses put after it. After that, we put two curly braces (`{ }`). Inside the curly braces goes all the code that we want to run whenever we call the function.
When we want to run the code, we type the name of the function followed by the parentheses.
Let's try that now. Save your code and refresh the page in your browser. Then go into the [developer tools JavaScript console](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools), and enter the following line:
```js
checkGuess();
```
After pressing <kbd>Return</kbd>/<kbd>Enter</kbd>, you should see an alert come up that says `I am a placeholder`; we have defined a function in our code that creates an alert whenever we call it.
> **Note:** You'll learn a lot more about functions later on in the article [Functions β reusable blocks of code](/en-US/docs/Learn/JavaScript/Building_blocks/Functions).
### Operators
JavaScript operators allow us to perform tests, do math, join strings together, and other such things.
If you haven't already done so, save your code, refresh the page in your browser, and open the [developer tools JavaScript console](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools). Then we can try typing in the examples shown below β type in each one from the "Example" columns exactly as shown, pressing <kbd>Return</kbd>/<kbd>Enter</kbd> after each one, and see what results they return.
First let's look at arithmetic operators, for example:
| Operator | Name | Example |
| -------- | -------------- | --------- |
| `+` | Addition | `6 + 9` |
| `-` | Subtraction | `20 - 15` |
| `*` | Multiplication | `3 * 7` |
| `/` | Division | `10 / 5` |
There are also some shortcut operators available, called [compound assignment operators](/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators). For example, if you want to add a new number to an existing one and return the result, you could do this:
```js
let number1 = 1;
number1 += 2;
```
This is equivalent to
```js
let number2 = 1;
number2 = number2 + 2;
```
When we are running true/false tests (for example inside conditionals β see [below](#conditionals)) we use [comparison operators](/en-US/docs/Web/JavaScript/Reference/Operators). For example:
<table class="standard-table">
<thead>
<tr>
<th scope="col">Operator</th>
<th scope="col">Name</th>
<th scope="col">Example</th>
</tr>
<tr>
<td><code>===</code></td>
<td>Strict equality (is it exactly the same?)</td>
<td>
<pre class="brush: js">
5 === 2 + 4 // false
'Chris' === 'Bob' // false
5 === 2 + 3 // true
2 === '2' // false; number versus string
</pre
>
</td>
</tr>
<tr>
<td><code>!==</code></td>
<td>Non-equality (is it not the same?)</td>
<td>
<pre class="brush: js">
5 !== 2 + 4 // true
'Chris' !== 'Bob' // true
5 !== 2 + 3 // false
2 !== '2' // true; number versus string
</pre
>
</td>
</tr>
<tr>
<td><code><</code></td>
<td>Less than</td>
<td>
<pre class="brush: js">
6 < 10 // true
20 < 10 // false</pre
>
</td>
</tr>
<tr>
<td><code>></code></td>
<td>Greater than</td>
<td>
<pre class="brush: js">
6 > 10 // false
20 > 10 // true</pre
>
</td>
</tr>
</thead>
</table>
### Text strings
Strings are used for representing text. We've already seen a string variable: in the following code, `"I am a placeholder"` is a string:
```js
function checkGuess() {
alert("I am a placeholder");
}
```
You can declare strings using double quotes (`"`) or single quotes (`'`), but you must use the same form for the start and end of a single string declaration: you can't write `"I am a placeholder'`.
You can also declare strings using backticks (`` ` ``). Strings declared like this are called _template literals_ and have some special properties. In particular, you can embed other variables or even expressions in them:
```js
const name = "Mahalia";
const greeting = `Hello ${name}`;
```
This gives you a mechanism to join strings together.
### Conditionals
Returning to our `checkGuess()` function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately.
At this point, replace your current `checkGuess()` function with this version instead:
```js
function checkGuess() {
const userGuess = Number(guessField.value);
if (guessCount === 1) {
guesses.textContent = "Previous guesses:";
}
guesses.textContent = `${guesses.textContent} ${userGuess}`;
if (userGuess === randomNumber) {
lastResult.textContent = "Congratulations! You got it right!";
lastResult.style.backgroundColor = "green";
lowOrHi.textContent = "";
setGameOver();
} else if (guessCount === 10) {
lastResult.textContent = "!!!GAME OVER!!!";
lowOrHi.textContent = "";
setGameOver();
} else {
lastResult.textContent = "Wrong!";
lastResult.style.backgroundColor = "red";
if (userGuess < randomNumber) {
lowOrHi.textContent = "Last guess was too low!";
} else if (userGuess > randomNumber) {
lowOrHi.textContent = "Last guess was too high!";
}
}
guessCount++;
guessField.value = "";
guessField.focus();
}
```
This is a lot of code β phew! Let's go through each section and explain what it does.
- The first line declares a variable called `userGuess` and sets its value to the current value entered inside the text field. We also run this value through the built-in `Number()` constructor, just to make sure the value is definitely a number. Since we're not changing this variable, we'll declare it using `const`.
- Next, we encounter our first conditional code block. A conditional code block allows you to run code selectively, depending on whether a certain condition is true or not. It looks a bit like a function, but it isn't. The simplest form of conditional block starts with the keyword `if`, then some parentheses, then some curly braces. Inside the parentheses, we include a test. If the test returns `true`, we run the code inside the curly braces. If not, we don't, and move on to the next bit of code. In this case, the test is testing whether the `guessCount` variable is equal to `1` (i.e. whether this is the player's first go or not):
```js
guessCount === 1;
```
If it is, we make the guesses paragraph's text content equal to `Previous guesses:`. If not, we don't.
- Next, we use a template literal to append the current `userGuess` value onto the end of the `guesses` paragraph, with a blank space in between.
- The next block does a few checks:
- The first `if (){ }` checks whether the user's guess is equal to the `randomNumber` set at the top of our JavaScript. If it is, the player has guessed correctly and the game is won, so we show the player a congratulations message with a nice green color, clear the contents of the Low/High guess information box, and run a function called `setGameOver()`, which we'll discuss later.
- Now we've chained another test onto the end of the last one using an `else if (){ }` structure. This one checks whether this turn is the user's last turn. If it is, the program does the same thing as in the previous block, except with a game over message instead of a congratulations message.
- The final block chained onto the end of this code (the `else { }`) contains code that is only run if neither of the other two tests returns true (i.e. the player didn't guess right, but they have more guesses left). In this case we tell them they are wrong, then we perform another conditional test to check whether the guess was higher or lower than the answer, displaying a further message as appropriate to tell them higher or lower.
- The last three lines in the function (lines 26β28 above) get us ready for the next guess to be submitted. We add 1 to the `guessCount` variable so the player uses up their turn (`++` is an incrementation operation β increment by 1), and empty the value out of the form text field and focus it again, ready for the next guess to be entered.
### Events
At this point, we have a nicely implemented `checkGuess()` function, but it won't do anything because we haven't called it yet. Ideally, we want to call it when the "Submit guess" button is pressed, and to do this we need to use an **event**. Events are things that happen in the browser β a button being clicked, a page loading, a video playing, etc. β in response to which we can run blocks of code. **Event listeners** observe specific events and call **event handlers**, which are blocks of code that run in response to an event firing.
Add the following line below your `checkGuess()` function:
```js
guessSubmit.addEventListener("click", checkGuess);
```
Here we are adding an event listener to the `guessSubmit` button. This is a method that takes two input values (called _arguments_) β the type of event we are listening out for (in this case `click`) as a string, and the code we want to run when the event occurs (in this case the `checkGuess()` function). Note that we don't need to specify the parentheses when writing it inside {{domxref("EventTarget.addEventListener", "addEventListener()")}}.
Try saving and refreshing your code now, and your example should work β to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the `setGameOver()` function that is supposed to be run once the game is over. Let's add our missing code now and complete the example functionality.
### Finishing the game functionality
Let's add that `setGameOver()` function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript:
```js
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement("button");
resetButton.textContent = "Start new game";
document.body.append(resetButton);
resetButton.addEventListener("click", resetGame);
}
```
- The first two lines disable the form text input and button by setting their disabled properties to `true`. This is necessary, because if we didn't, the user could submit more guesses after the game is over, which would mess things up.
- The next three lines generate a new {{htmlelement("button")}} element, set its text label to "Start new game", and add it to the bottom of our existing HTML.
- The final line sets an event listener on our new button so that when it is clicked, a function called `resetGame()` is run.
Now we need to define this function too! Add the following code, again to the bottom of your JavaScript:
```js
function resetGame() {
guessCount = 1;
const resetParas = document.querySelectorAll(".resultParas p");
for (const resetPara of resetParas) {
resetPara.textContent = "";
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = "";
guessField.focus();
lastResult.style.backgroundColor = "white";
randomNumber = Math.floor(Math.random() * 100) + 1;
}
```
This rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. It:
- Puts the `guessCount` back down to 1.
- Empties all the text out of the information paragraphs. We select all paragraphs inside `<div class="resultParas"></div>`, then loop through each one, setting their `textContent` to `''` (an empty string).
- Removes the reset button from our code.
- Enables the form elements, and empties and focuses the text field, ready for a new guess to be entered.
- Removes the background color from the `lastResult` paragraph.
- Generates a new random number so that you are not just guessing the same number again!
**At this point, you should have a fully working (simple) game β congratulations!**
All we have left to do now in this article is to talk about a few other important code features that you've already seen, although you may have not realized it.
### Loops
One part of the above code that we need to take a more detailed look at is the [for...of](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.
To start with, go to your [browser developer tools JavaScript console](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools) again, and enter the following:
```js
const fruits = ["apples", "bananas", "cherries"];
for (const fruit of fruits) {
console.log(fruit);
}
```
What happened? The strings `'apples', 'bananas', 'cherries'` were printed out in your console.
This is because of the loop. The line `const fruits = ['apples', 'bananas', 'cherries'];` creates an array. We will work through [a complete Arrays guide](/en-US/docs/Learn/JavaScript/First_steps/Arrays) later in this module, but for now: an array is a collection of items (in this case strings).
A `for...of` loop gives you a way to get each item in the array and run some JavaScript on it. The line `for (const fruit of fruits)` says:
1. Get the first item in `fruits`.
2. Set the `fruit` variable to that item, then run the code between the `{}` curly braces.
3. Get the next item in `fruits`, and repeat 2, until you reach the end of `fruits`.
In this case, the code inside the curly braces is writing out `fruit` to the console.
Now let's look at the loop in our number guessing game β the following can be found inside the `resetGame()` function:
```js
const resetParas = document.querySelectorAll(".resultParas p");
for (const resetPara of resetParas) {
resetPara.textContent = "";
}
```
This code creates a variable containing a list of all the paragraphs inside `<div class="resultParas">` using the {{domxref("Document.querySelectorAll", "querySelectorAll()")}} method, then it loops through each one, removing the text content of each.
Note that even though `resetPara` is a constant, we can change its internal properties like `textContent`.
### A small discussion on objects
Let's add one more final improvement before we get to this discussion. Add the following line just below the `let resetButton;` line near the top of your JavaScript, then save your file:
```js
guessField.focus();
```
This line uses the {{domxref("HTMLElement/focus", "focus()")}} method to automatically put the text cursor into the {{htmlelement("input")}} text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field first. It's only a small addition, but it improves usability β giving the user a good visual clue as to what they've got to do to play the game.
Let's analyze what's going on here in a bit more detail. In JavaScript, most of the items you will manipulate in your code are objects. An object is a collection of related functionality stored in a single grouping. You can create your own objects, but that is quite advanced and we won't be covering it until much later in the course. For now, we'll just briefly discuss the built-in objects that your browser contains, which allow you to do lots of useful things.
In this particular case, we first created a `guessField` constant that stores a reference to the text input form field in our HTML β the following line can be found amongst our declarations near the top of the code:
```js
const guessField = document.querySelector(".guessField");
```
To get this reference, we used the {{domxref("document.querySelector", "querySelector()")}} method of the {{domxref("document")}} object. `querySelector()` takes one piece of information β a [CSS selector](/en-US/docs/Learn/CSS/Building_blocks/Selectors) that selects the element you want a reference to.
Because `guessField` now contains a reference to an {{htmlelement("input")}} element, it now has access to a number of properties (basically variables stored inside objects, some of which can't have their values changed) and methods (basically functions stored inside objects). One method available to input elements is `focus()`, so we can now use this line to focus the text input:
```js
guessField.focus();
```
Variables that don't contain references to form elements won't have `focus()` available to them. For example, the `guesses` constant contains a reference to a {{htmlelement("p")}} element, and the `guessCount` variable contains a number.
### Playing with browser objects
Let's play with some browser objects a bit.
1. First of all, open up your program in a browser.
2. Next, open your [browser developer tools](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools), and make sure the JavaScript console tab is open.
3. Type `guessField` into the console and the console shows you that the variable contains an {{htmlelement("input")}} element. You'll also notice that the console autocompletes the names of objects that exist inside the execution environment, including your variables!
4. Now type in the following:
```js
guessField.value = 2;
```
The `value` property represents the current value entered into the text field. You'll see that by entering this command, we've changed the text in the text field!
5. Now try typing `guesses` into the console and pressing <kbd>Enter</kbd> (or <kbd>Return</kbd>, depending on your keyboard). The console shows you that the variable contains a {{htmlelement("p")}} element.
6. Now try entering the following line:
```js
guesses.value;
```
The browser returns `undefined`, because paragraphs don't have the `value` property.
7. To change the text inside a paragraph, you need the {{domxref("Node.textContent", "textContent")}} property instead. Try this:
```js
guesses.textContent = "Where is my paragraph?";
```
8. Now for some fun stuff. Try entering the below lines, one by one:
```js
guesses.style.backgroundColor = "yellow";
guesses.style.fontSize = "200%";
guesses.style.padding = "10px";
guesses.style.boxShadow = "3px 3px 6px black";
```
Every element on a page has a `style` property, which itself contains an object whose properties contain all the inline CSS styles applied to that element. This allows us to dynamically set new CSS styles on elements using JavaScript.
## Finished for nowβ¦
So that's it for building the example. You got to the end β well done! Try your final code out, or [play with our finished version here](https://mdn.github.io/learning-area/javascript/introduction-to-js-1/first-splash/number-guessing-game.html). If you can't get the example to work, check it against the [source code](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/first-splash/number-guessing-game.html).
{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/what_is_javascript/index.md | ---
title: What is JavaScript?
slug: Learn/JavaScript/First_steps/What_is_JavaScript
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}
Welcome to the MDN beginner's JavaScript course!
In this article we will look at JavaScript from a high level, answering questions such as "What is it?" and "What can you do with it?", and making sure you are comfortable with JavaScript's purpose.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>A basic understanding of HTML and CSS.</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To gain familiarity with what JavaScript is, what it can do, and how it
fits into a website.
</td>
</tr>
</tbody>
</table>
## A high-level definition
JavaScript is a scripting or programming language that allows you to implement complex features on web pages β every time a web page does more than just sit there and display static information for you to look at β displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. β you can bet that JavaScript is probably involved.
It is the third layer of the layer cake of standard web technologies, two of which ([HTML](/en-US/docs/Learn/HTML) and [CSS](/en-US/docs/Learn/CSS)) we have covered in much more detail in other parts of the Learning Area.

- {{glossary("HTML")}} is the markup language that we use to structure and give meaning to our web content, for example defining paragraphs, headings, and data tables, or embedding images and videos in the page.
- {{glossary("CSS")}} is a language of style rules that we use to apply styling to our HTML content, for example setting background colors and fonts, and laying out our content in multiple columns.
- {{glossary("JavaScript")}} is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. (Okay, not everything, but it is amazing what you can achieve with a few lines of JavaScript code.)
The three layers build on top of one another nicely. Let's take a button as an example. We can mark it up using HTML to give it structure and purpose:
```html
<button type="button">Player 1: Chris</button>
```

Then we can add some CSS into the mix to get it looking nice:
```css
button {
font-family: "helvetica neue", helvetica, sans-serif;
letter-spacing: 1px;
text-transform: uppercase;
border: 2px solid rgb(200 200 0 / 60%);
background-color: rgb(0 217 217 / 60%);
color: rgb(100 0 0 / 100%);
box-shadow: 1px 1px 2px rgb(0 0 200 / 40%);
border-radius: 10px;
padding: 3px 10px;
cursor: pointer;
}
```

And finally, we can add some JavaScript to implement dynamic behavior:
```js
const button = document.querySelector("button");
button.addEventListener("click", updateName);
function updateName() {
const name = prompt("Enter a new name");
button.textContent = `Player 1: ${name}`;
}
```
{{ EmbedLiveSample('A_high-level_definition', '100%', 80) }}
Try clicking on this last version of the text label to see what happens (note also that you can find this demo on GitHub β see the [source code](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/what-is-js/javascript-label.html), or [run it live](https://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/javascript-label.html))!
JavaScript can do a lot more than that β let's explore what in more detail.
## So what can it really do?
The core client-side JavaScript language consists of some common programming features that allow you to do things like:
- Store useful values inside variables. In the above example for instance, we ask for a new name to be entered then store that name in a variable called `name`.
- Operations on pieces of text (known as "strings" in programming). In the above example we take the string "Player 1: " and join it to the `name` variable to create the complete text label, e.g. "Player 1: Chris".
- Running code in response to certain events occurring on a web page. We used a {{domxref("Element/click_event", "click")}} event in our example above to detect when the label is clicked and then run the code that updates the text label.
- And much more!
What is even more exciting however is the functionality built on top of the client-side JavaScript language. So-called **Application Programming Interfaces** (**APIs**) provide you with extra superpowers to use in your JavaScript code.
APIs are ready-made sets of code building blocks that allow a developer to implement programs that would otherwise be hard or impossible to implement.
They do the same thing for programming that ready-made furniture kits do for home building β it is much easier to take ready-cut panels and screw them together to make a bookshelf than it is to work out the design yourself, go and find the correct wood, cut all the panels to the right size and shape, find the correct-sized screws, and _then_ put them together to make a bookshelf.
They generally fall into two categories.

**Browser APIs** are built into your web browser, and are able to expose data from the surrounding computer environment, or do useful complex things. For example:
- The {{domxref("Document_Object_Model","DOM (Document Object Model) API")}} allows you to manipulate HTML and CSS, creating, removing and changing HTML, dynamically applying new styles to your page, etc.
Every time you see a popup window appear on a page, or some new content displayed (as we saw above in our simple demo) for example, that's the DOM in action.
- The {{domxref("Geolocation","Geolocation API")}} retrieves geographical information.
This is how [Google Maps](https://www.google.com/maps) is able to find your location and plot it on a map.
- The {{domxref("Canvas_API","Canvas")}} and {{domxref("WebGL_API","WebGL")}} APIs allow you to create animated 2D and 3D graphics.
People are doing some amazing things using these web technologies β see [Chrome Experiments](https://experiments.withgoogle.com/collection/chrome) and [webglsamples](https://webglsamples.org/).
- [Audio and Video APIs](/en-US/docs/Web/Media/Audio_and_video_delivery) like {{domxref("HTMLMediaElement")}} and {{domxref("WebRTC API", "WebRTC")}} allow you to do really interesting things with multimedia, such as play audio and video right in a web page, or grab video from your web camera and display it on someone else's computer (try our simple [Snapshot demo](https://chrisdavidmills.github.io/snapshot/) to get the idea).
> **Note:** Many of the above demos won't work in an older browser β when experimenting, it's a good idea to use a modern browser like Firefox, Chrome, Edge or Opera to run your code in.
> You will need to consider [cross browser testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing) in more detail when you get closer to delivering production code (i.e. real code that real customers will use).
**Third party APIs** are not built into the browser by default, and you generally have to grab their code and information from somewhere on the Web. For example:
- The [Twitter API](https://developer.twitter.com/en/docs) allows you to do things like displaying your latest tweets on your website.
- The [Google Maps API](https://developers.google.com/maps/) and [OpenStreetMap API](https://wiki.openstreetmap.org/wiki/API) allows you to embed custom maps into your website, and other such functionality.
> **Note:** These APIs are advanced, and we'll not be covering any of these in this module. You can find out much more about these in our [Client-side web APIs module](/en-US/docs/Learn/JavaScript/Client-side_web_APIs).
There's a lot more available, too! However, don't get over excited just yet. You won't be able to build the next Facebook, Google Maps, or Instagram after studying JavaScript for 24 hours β there are a lot of basics to cover first. And that's why you're here β let's move on!
## What is JavaScript doing on your page?
Here we'll actually start looking at some code, and while doing so, explore what actually happens when you run some JavaScript in your page.
Let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our [How CSS works](/en-US/docs/Learn/CSS/First_steps/How_CSS_works#how_does_css_actually_work) article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page).

A very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above).
Note that the code in your web documents is generally loaded and executed in the order it appears on the page.
Errors may occur if JavaScript is loaded and run before the HTML and CSS that it is intended to modify.
You will learn ways around this later in the article, in the [Script loading strategies](#script_loading_strategies) section.
### Browser security
Each browser tab has its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) β this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab β or on another website.
This is a good security measure β if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.
> **Note:** There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.
### JavaScript running order
When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom.
This means that you need to be careful what order you put things in.
For example, let's return to the block of JavaScript we saw in our first example:
```js
const button = document.querySelector("button");
button.addEventListener("click", updateName);
function updateName() {
const name = prompt("Enter a new name");
button.textContent = `Player 1: ${name}`;
}
```
Here we are selecting a button (line 1), then attaching an event listener to it (line 3) so that when the button is clicked, the `updateName()` code block (lines 5β8) is run. The `updateName()` code block (these types of reusable code blocks are called "functions") asks the user for a new name, and then inserts that name into the button text to update the display.
If you swapped the order of the first two lines of code, it would no longer work β instead, you'd get an error returned in the [browser developer console](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools) β `Uncaught ReferenceError: Cannot access 'button' before initialization`.
This means that the `button` object has not been initialized yet, so we can't add an event listener to it.
> **Note:** This is a very common error β you need to be careful that the objects referenced in your code exist before you try to do stuff to them.
### Interpreted versus compiled code
You might hear the terms **interpreted** and **compiled** in the context of programming.
In interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned.
You don't have to transform the code into a different form before the browser runs it.
The code is received in its programmer-friendly text form and processed directly from that.
Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer.
For example, C/C++ are compiled into machine code that is then run by the computer.
The program is executed from a binary format, which was generated from the original program source code.
JavaScript is a lightweight interpreted programming language.
The web browser receives the JavaScript code in its original text form and runs the script from that.
From a technical standpoint, most modern JavaScript interpreters actually use a technique called **just-in-time compiling** to improve performance; the JavaScript source code gets compiled into a faster, binary format while the script is being used, so that it can be run as quickly as possible.
However, JavaScript is still considered an interpreted language, since the compilation is handled at run time, rather than ahead of time.
There are advantages to both types of language, but we won't discuss them right now.
### Server-side versus client-side code
You might also hear the terms **server-side** and **client-side** code, especially in the context of web development.
Client-side code is code that is run on the user's computer β when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser.
In this module we are explicitly talking about **client-side JavaScript**.
Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser.
Examples of popular server-side web languages include PHP, Python, Ruby, ASP.NET, and even JavaScript!
JavaScript can also be used as a server-side language, for example in the popular Node.js environment β you can find out more about server-side JavaScript in our [Dynamic Websites β Server-side programming](/en-US/docs/Learn/Server-side) topic.
### Dynamic versus static code
The word **dynamic** is used to describe both client-side JavaScript, and server-side languages β it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required.
Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, filling it with data requested from the server, then displaying the table in a web page shown to the user.
The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.
A web page with no dynamically updating content is referred to as **static** β it just shows the same content all the time.
## How do you add JavaScript to your page?
JavaScript is applied to your HTML page in a similar manner to CSS.
Whereas CSS uses {{htmlelement("link")}} elements to apply external stylesheets and {{htmlelement("style")}} elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML β the {{htmlelement("script")}} element. Let's learn how this works.
### Internal JavaScript
1. First of all, make a local copy of our example file [apply-javascript.html](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/what-is-js/apply-javascript.html). Save it in a directory somewhere sensible.
2. Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.
3. Next, go to your text editor and add the following in your head β just before your closing `</head>` tag:
```html
<script>
// JavaScript goes here
</script>
```
4. Now we'll add some JavaScript inside our {{htmlelement("script")}} element to make the page do something more interesting β add the following code just below the "// JavaScript goes here" line:
```js
document.addEventListener("DOMContentLoaded", () => {
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the button!";
document.body.appendChild(para);
}
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
}
});
```
5. Save your file and refresh the browser β now you should see that when you click the button, a new paragraph is generated and placed below.
> **Note:** If your example doesn't seem to work, go through the steps again and check that you did everything right.
> Did you save your local copy of the starting code as a `.html` file?
> Did you add your {{htmlelement("script")}} element just before the `</head>` tag?
> Did you enter the JavaScript exactly as shown? **JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.**
> **Note:** You can see this version on GitHub as [apply-javascript-internal.html](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/what-is-js/apply-javascript-internal.html) ([see it live too](https://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/apply-javascript-internal.html)).
### External JavaScript
This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now.
1. First, create a new file in the same directory as your sample HTML file. Call it `script.js` β make sure it has that .js filename extension, as that's how it is recognized as JavaScript.
2. Replace your current {{htmlelement("script")}} element with the following:
```html
<script src="script.js" defer></script>
```
3. Inside `script.js`, add the following script:
```js
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the button!";
document.body.appendChild(para);
}
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
}
```
4. Save and refresh your browser, and you should see the same thing!
It works just the same, but now we've got our JavaScript in an external file.
This is generally a good thing in terms of organizing your code and making it reusable across multiple HTML files.
Plus, the HTML is easier to read without huge chunks of script dumped in it.
> **Note:** You can see this version on GitHub as [apply-javascript-external.html](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/what-is-js/apply-javascript-external.html) and [script.js](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/what-is-js/script.js) ([see it live too](https://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/apply-javascript-external.html)).
### Inline JavaScript handlers
Note that sometimes you'll come across bits of actual JavaScript code living inside HTML.
It might look something like this:
```js example-bad
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the button!";
document.body.appendChild(para);
}
```
```html example-bad
<button onclick="createParagraph()">Click me!</button>
```
You can try this version of our demo below.
{{ EmbedLiveSample('Inline_JavaScript_handlers', '100%', 150) }}
This demo has exactly the same functionality as in the previous two sections, except that the {{htmlelement("button")}} element includes an inline `onclick` handler to make the function run when the button is pressed.
**Please don't do this, however.** It is bad practice to pollute your HTML with JavaScript, and it is inefficient β you'd have to include the `onclick="createParagraph()"` attribute on every button you want the JavaScript to apply to.
### Using addEventListener instead
Instead of including JavaScript in your HTML, use a pure JavaScript construct.
The `querySelectorAll()` function allows you to select all the buttons on a page.
You can then loop through the buttons, assigning a handler for each using `addEventListener()`.
The code for this is shown below:
```js
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
}
```
This might be a bit longer than the `onclick` attribute, but it will work for all buttons β no matter how many are on the page, nor how many are added or removed.
The JavaScript does not need to be changed.
> **Note:** Try editing your version of `apply-javascript.html` and add a few more buttons into the file.
> When you reload, you should find that all of the buttons when clicked will create a paragraph.
> Neat, huh?
### Script loading strategies
There are a number of issues involved with getting scripts to load at the right time. Nothing is as simple as it seems!
A common problem is that all the HTML on a page is loaded in the order in which it appears.
If you are using JavaScript to manipulate elements on the page (or more accurately, the [Document Object Model](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents#the_document_object_model)), your code won't work if the JavaScript is loaded and parsed before the HTML you are trying to do something to.
In the above code examples, in the internal and external examples the JavaScript is loaded and run in the head of the document, before the HTML body is parsed.
This could cause an error, so we've used some constructs to get around it.
In the internal example, you can see this structure around the code:
```js
document.addEventListener("DOMContentLoaded", () => {
// β¦
});
```
This is an event listener, which listens for the browser's `DOMContentLoaded` event, which signifies that the HTML body is completely loaded and parsed.
The JavaScript inside this block will not run until after that event is fired, therefore the error is avoided (you'll [learn about events](/en-US/docs/Learn/JavaScript/Building_blocks/Events) later in the course).
In the external example, we use a more modern JavaScript feature to solve the problem, the `defer` attribute, which tells the browser to continue downloading the HTML content once the `<script>` tag element has been reached.
```html
<script src="script.js" defer></script>
```
In this case both the script and the HTML will load simultaneously and the code will work.
> **Note:** In the external case, we did not need to use the `DOMContentLoaded` event because the `defer` attribute solved the problem for us.
> We didn't use the `defer` solution for the internal JavaScript example because `defer` only works for external scripts.
An old-fashioned solution to this problem used to be to put your script element right at the bottom of the body (e.g. just before the `</body>` tag), so that it would load after all the HTML has been parsed.
The problem with this solution is that loading/parsing of the script is completely blocked until the HTML DOM has been loaded.
On larger sites with lots of JavaScript, this can cause a major performance issue, slowing down your site.
#### async and defer
There are actually two modern features we can use to bypass the problem of the blocking script β `async` and `defer` (which we saw above).
Let's look at the difference between these two.
Scripts loaded using the `async` attribute will download the script without blocking the page while the script is being fetched.
However, once the download is complete, the script will execute, which blocks the page from rendering. This means that the rest of the content on the web page is prevented from being processed and displayed to the user until the script finishes executing.
You get no guarantee that scripts will run in any specific order.
It is best to use `async` when the scripts in the page run independently from each other and depend on no other script on the page.
Scripts loaded with the `defer` attribute will load in the order they appear on the page.
They won't run until the page content has all loaded, which is useful if your scripts depend on the DOM being in place (e.g. they modify one or more elements on the page).
Here is a visual representation of the different script loading methods and what that means for your page:

_This image is from the [HTML spec](https://html.spec.whatwg.org/images/asyncdefer.svg), copied and cropped to a reduced version, under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) license terms._
For example, if you have the following script elements:
```html
<script async src="js/vendor/jquery.js"></script>
<script async src="js/script2.js"></script>
<script async src="js/script3.js"></script>
```
You can't rely on the order the scripts will load in.
`jquery.js` may load before or after `script2.js` and `script3.js` and if this is the case, any functions in those scripts depending on `jquery` will produce an error because `jquery` will not be defined at the time the script runs.
`async` should be used when you have a bunch of background scripts to load in, and you just want to get them in place as soon as possible.
For example, maybe you have some game data files to load, which will be needed when the game actually begins, but for now you just want to get on with showing the game intro, titles, and lobby, without them being blocked by script loading.
Scripts loaded using the `defer` attribute (see below) will run in the order they appear in the page and execute them as soon as the script and content are downloaded:
```html
<script defer src="js/vendor/jquery.js"></script>
<script defer src="js/script2.js"></script>
<script defer src="js/script3.js"></script>
```
In the second example, we can be sure that `jquery.js` will load before `script2.js` and `script3.js` and that `script2.js` will load before `script3.js`.
They won't run until the page content has all loaded, which is useful if your scripts depend on the DOM being in place (e.g. they modify one or more elements on the page).
To summarize:
- `async` and `defer` both instruct the browser to download the script(s) in a separate thread, while the rest of the page (the DOM, etc.) is downloading, so the page loading is not blocked during the fetch process.
- scripts with an `async` attribute will execute as soon as the download is complete.
This blocks the page and does not guarantee any specific execution order.
- scripts with a `defer` attribute will load in the order they are in and will only execute once everything has finished loading.
- If your scripts should be run immediately and they don't have any dependencies, then use `async`.
- If your scripts need to wait for parsing and depend on other scripts and/or the DOM being in place, load them using `defer` and put their corresponding `<script>` elements in the order you want the browser to execute them.
## Comments
As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after six months and can't remember what you did).
Comments are very useful, and you should use them often, particularly for larger applications.
There are two types:
- A single line comment is written after a double forward slash (//), e.g.
```js
// I am a comment
```
- A multi-line comment is written between the strings /\* and \*/, e.g.
```js
/*
I am also
a comment
*/
```
So for example, we could annotate our last demo's JavaScript with comments like so:
```js
// Function: creates a new paragraph and appends it to the bottom of the HTML body.
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the button!";
document.body.appendChild(para);
}
/*
1. Get references to all the buttons on the page in an array format.
2. Loop through all the buttons and add a click event listener to each one.
When any button is pressed, the createParagraph() function will be run.
*/
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
}
```
> **Note:** In general more comments are usually better than less, but you should be careful if you find yourself adding lots of comments to explain what variables are (your variable names perhaps should be more intuitive), or to explain very simple operations (maybe your code is overcomplicated).
## Summary
So there you go, your first step into the world of JavaScript.
We've begun with just theory, to start getting you used to why you'd use JavaScript and what kind of things you can do with it.
Along the way, you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.
JavaScript may seem a bit daunting right now, but don't worry β in this course, we will take you through it in simple steps that will make sense going forward.
In the next article, we will [plunge straight into the practical](/en-US/docs/Learn/JavaScript/First_steps/A_first_splash), getting you to jump straight in and build your own JavaScript examples.
{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/test_your_skills_colon__strings/index.md | ---
title: "Test your skills: Strings"
slug: Learn/JavaScript/First_steps/Test_your_skills:_Strings
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Handling text β strings in JavaScript](/en-US/docs/Learn/JavaScript/First_steps/Strings) and [Useful string methods](/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods) 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).
> **Note:** In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version).
## Strings 1
In our first strings task, we start off small. You already have half of a famous quote inside a variable called `quoteStart`; we would like you to:
1. Look up the other half of the quote, and add it to the example inside a variable called `quoteEnd`.
2. Concatenate the two strings together to make a single string containing the complete quote. Save the result inside a variable called `finalQuote`.
You'll find that you get an error at this point. Can you fix the problem with `quoteStart`, so that the full quote displays correctly?
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/strings/strings1.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/strings/strings1-download.html) to work in your own editor or in an online editor.
## Strings 2
In this task you are provided with two variables, `quote` and `substring`, which contain two strings. We would like you to:
1. Retrieve the length of the quote, and store it in a variable called `quoteLength`.
2. Find the index position where `substring` appears in `quote`, and store that value in a variable called `index`.
3. Use a combination of the variables you have and available string properties/methods to trim down the original quote to "I do not like green eggs and ham.", and store it in a variable called `revisedQuote`.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/strings/strings2.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/strings/strings2-download.html) to work in your own editor or in an online editor.
## Strings 3
In the next string task, you are given the same quote that you ended up with in the previous task, but it is somewhat broken! We want you to fix and update it, like so:
1. Change the casing to correct sentence case (all lowercase, except for upper case first letter). Store the new quote in a variable called `fixedQuote`.
2. In `fixedQuote`, replace "green eggs and ham" with another food that you really don't like.
3. There is one more small fix to do β add a period to the end of the quote, and save the final version in a variable called `finalQuote`.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/strings/strings3.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/strings/strings3-download.html) to work in your own editor or in an online editor.
## Strings 4
In the final string task, we have given you the name of a theorem, two numeric values, and an incomplete string (the bits that need adding are marked with asterisks (`*`)). We want you to change the value of the string as follows:
1. Change it from a regular string literal into a template literal.
2. Replace the four asterisks with four template literal placeholders. These should be:
1. The name of the theorem.
2. The two number values we have.
3. The length of the hypotenuse of a right-angled triangle, given that the two other side lengths are the same as the two values we have. You'll need to look up how to calculate this from what you have. Do the calculation inside the placeholder.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/strings/strings4.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/strings/strings4-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/test_your_skills_colon__variables/index.md | ---
title: "Test your skills: variables"
slug: Learn/JavaScript/First_steps/Test_your_skills:_variables
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Storing the information you need β Variables](/en-US/docs/Learn/JavaScript/First_steps/Variables) 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 there is an error in your code, it will be logged into the results panel on this page or in the JavaScript console.
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Variables 1
In this task we want you to:
- Declare a variable called `myName`.
- Initialize `myName` with a suitable value, on a separate line (you can use your actual name, or something else).
- Declare a variable called `myAge` and initialize it with a value, on the same line.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/variables/variables1.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/variables/variables1-download.html) to work in your own editor or in an online editor.
## Variables 2
In this task you need to add a new line to correct the value stored in the existing `myName` variable to your own name.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/variables/variables2.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/variables/variables2-download.html) to work in your own editor or in an online editor.
## Variables 3
The final task for now β in this case you are provided with some existing code, which has two errors present in it. The results panel should be outputting the name `Chris`, and a statement about how old Chris will be in 20 years' time. How can you fix the problem and correct the output?
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/variables/variables3.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/variables/variables3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/what_went_wrong/index.md | ---
title: What went wrong? Troubleshooting JavaScript
slug: Learn/JavaScript/First_steps/What_went_wrong
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}
When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear β this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix errors in JavaScript programs.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To gain the ability and confidence to start fixing problems in your own
code.
</td>
</tr>
</tbody>
</table>
## Types of error
Generally speaking, when you do something wrong in code, there are two main types of error that you'll come across:
- **Syntax errors**: These are spelling errors in your code that actually cause the program not to run at all, or stop working part way through β you will usually be provided with some error messages too. These are usually okay to fix, as long as you are familiar with the right tools and know what the error messages mean!
- **Logic errors**: These are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn't an error message to direct you to the source of the error.
Okay, so it's not quite _that_ simple β there are some other differentiators as you drill down deeper. But the above classifications will do at this early stage in your career. We'll look at both of these types going forward.
## An erroneous example
To get started, let's return to our number guessing game β except this time we'll be exploring a version that has some deliberate errors introduced. Go to GitHub and make yourself a local copy of [number-game-errors.html](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/troubleshooting/number-game-errors.html) (see it [running live here](https://mdn.github.io/learning-area/javascript/introduction-to-js-1/troubleshooting/number-game-errors.html)).
1. To get started, open the local copy inside your favorite text editor, and your browser.
2. Try playing the game β you'll notice that when you press the "Submit guess" button, it doesn't work!
> **Note:** You might well have your own version of the game example that doesn't work, which you might want to fix! We'd still like you to work through the article with our version, so that you can learn the techniques we are teaching here. Then you can go back and try to fix your example.
At this point, let's consult the developer console to see if it reports any syntax errors, then try to fix them. You'll learn how below.
## Fixing syntax errors
Earlier on in the course we got you to type some simple JavaScript commands into the [developer tools JavaScript console](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools) (if you can't remember how to open this in your browser, follow the previous link to find out how). What's even more useful is that the console gives you error messages whenever a syntax error exists inside the JavaScript being fed into the browser's JavaScript engine. Now let's go hunting.
1. Go to the tab that you've got `number-game-errors.html` open in, and open your JavaScript console. You should see an error message along the following lines: !["Number guessing game" demo page in Firefox. One error is visible in the JavaScript console: "X TypeError: guessSubmit.addeventListener is not a function [Learn More] (number-game-errors.html:86:3)".](not-a-function.png)
2. The first line of the error message is:
```plain
Uncaught TypeError: guessSubmit.addeventListener is not a function
number-game-errors.html:86:15
```
- The first part, `Uncaught TypeError: guessSubmit.addeventListener is not a function`, is telling us something about what went wrong.
- The second part, `number-game-errors.html:86:15`, is telling us where in the code the error came from: line 86, character 15 of the file "number-game-errors.html".
3. If we look at line 86 in our code editor, we'll find this line:
> **Warning:** Error message may not be on line 86.
>
> If you are using any code editor with an extension that launches a live server on your local machine, this will cause extra code to be injected. Because of this, the developer tools will list the error as occurring on a line that is not 86.
```js
guessSubmit.addeventListener("click", checkGuess);
```
4. The error message says "guessSubmit.addeventListener is not a function", which means that the function we're calling is not recognized by the JavaScript interpreter. Often, this error message actually means that we've spelled something wrong. If you are not sure of the correct spelling of a piece of syntax, it is often good to look up the feature on MDN. The best way to do this currently is to search for "mdn _name-of-feature_" with your favorite search engine. Here's a shortcut to save you some time in this instance: [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener).
5. So, looking at this page, the error appears to be that we've spelled the function name wrong! Remember that JavaScript is case-sensitive, so any slight difference in spelling or casing will cause an error. Changing `addeventListener` to `addEventListener` should fix this. Do this now.
> **Note:** See our [TypeError: "x" is not a function](/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function) reference page for more details about this error.
### Syntax errors round two
1. Save your page and refresh, and you should see the error has gone.
2. Now if you try to enter a guess and press the Submit guess button, you'll see another error! 
3. This time the error being reported is:
```plain
Uncaught TypeError: can't access property "textContent", lowOrHi is null
```
Depending on the browser you are using, you might see a different message here. The message above is what Firefox will show you, but Chrome, for example, will show you this:
```plain
Uncaught TypeError: Cannot set properties of null (setting 'textContent')
```
It's the same error, but different browsers describe it in a different way.
> **Note:** This error didn't come up as soon as the page was loaded because this error occurred inside a function (inside the `checkGuess() { }` block). As you'll learn in more detail in our later [functions article](/en-US/docs/Learn/JavaScript/Building_blocks/Functions), code inside functions runs in a separate scope than code outside functions. In this case, the code was not run and the error was not thrown until the `checkGuess()` function was run by line 86.
4. The line number given in the error is 80. Have a look at line 80, and you'll see the following code:
```js
lowOrHi.textContent = "Last guess was too high!";
```
5. This line is trying to set the `textContent` property of the `lowOrHi` variable to a text string, but it's not working because `lowOrHi` does not contain what it's supposed to. Let's see why this is β try searching for other instances of `lowOrHi` in the code. The earliest instance you'll find is on line 49:
```js
const lowOrHi = document.querySelector("lowOrHi");
```
6. At this point we are trying to make the variable contain a reference to an element in the document's HTML. Let's see what the variable contains after this line has been run. Add the following code on line 50:
```js
console.log(lowOrHi);
```
This code will print the value of `lowOrHi` to the console after we tried to set it in line 49. See {{domxref("console/log_static", "console.log()")}} for more information.
7. Save and refresh, and you should now see the `console.log()` result in your console.  Sure enough, `lowOrHi`'s value is `null` at this point, and this matches up with the Firefox error message `lowOrHi is null`. So there is definitely a problem with line 49. The [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) value means "nothing", or "no value". So our code to set `lowOrHi` to an element is going wrong.
8. Let's think about what the problem could be. Line 49 is using a [`document.querySelector()`](/en-US/docs/Web/API/Document/querySelector) method to get a reference to an element by selecting it with a CSS selector. Looking further up our file, we can find the paragraph in question:
```html
<p class="lowOrHi"></p>
```
9. So we need a class selector here, which begins with a dot (`.`), but the selector being passed into the `querySelector()` method in line 49 has no dot. This could be the problem! Try changing `lowOrHi` to `.lowOrHi` in line 49.
10. Try saving and refreshing again, and your `console.log()` statement should return the `<p>` element we want. Phew! Another error fixed! You can delete your `console.log()` line now, or keep it to reference later on β your choice.
> **Note:** See our [TypeError: "x" is (not) "y"](/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_type) reference page for more details about this error.
### Syntax errors round three
1. Now if you try playing the game through again, you should get more success β the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of guesses.
2. At that point, the game fails again, and the same error is spat out that we got at the beginning β "TypeError: resetButton.addeventListener is not a function"! However, this time it's listed as coming from line 94.
3. Looking at line number 94, it is easy to see that we've made the same mistake here. We again just need to change `addeventListener` to `addEventListener`. Do this now.
## A logic error
At this point, the game should play through fine, however after playing through a few times you'll undoubtedly notice that the game always chooses 1 as the "random" number you've got to guess. Definitely not quite how we want the game to play out!
There's definitely a problem in the game logic somewhere β the game is not returning an error; it just isn't playing right.
1. Search for the `randomNumber` variable, and the lines where the random number is first set. The instance that stores the random number that we want to guess at the start of the game should be around line number 45:
```js
let randomNumber = Math.floor(Math.random()) + 1;
```
2. And the one that generates the random number before each subsequent game is around line 113:
```js
randomNumber = Math.floor(Math.random()) + 1;
```
3. To check whether these lines are indeed the problem, let's turn to our friend `console.log()` again β insert the following line directly below each of the above two lines:
```js
console.log(randomNumber);
```
4. Save and refresh, then play a few games β you'll see that `randomNumber` is equal to 1 at each point where it is logged to the console.
### Working through the logic
To fix this, let's consider how this line is working. First, we invoke [`Math.random()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random), which generates a random decimal number between 0 and 1, e.g. 0.5675493843.
```js
Math.random();
```
Next, we pass the result of invoking `Math.random()` through [`Math.floor()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor), which rounds the number passed to it down to the nearest whole number. We then add 1 to that result:
```js
Math.floor(Math.random()) + 1;
```
Rounding a random decimal number between 0 and 1 down will always return 0, so adding 1 to it will always return 1. We need to multiply the random number by 100 before we round it down. The following would give us a random number between 0 and 99:
```js
Math.floor(Math.random() * 100);
```
Hence us wanting to add 1, to give us a random number between 1 and 100:
```js
Math.floor(Math.random() * 100) + 1;
```
Try updating both lines like this, then save and refresh β the game should now play like we are intending it to!
## Other common errors
There are other common errors you'll come across in your code. This section highlights most of them.
### SyntaxError: missing ; before statement
This error generally means that you have missed a semicolon at the end of one of your lines of code, but it can sometimes be more cryptic. For example, if we change this line inside the `checkGuess()` function:
```js
const userGuess = Number(guessField.value);
```
to
```js example-bad
const userGuess === Number(guessField.value);
```
It throws this error because it thinks you are trying to do something different. You should make sure that you don't mix up the assignment operator (`=`) β which sets a variable to be equal to a value β with the strict equality operator (`===`), which tests whether one value is equal to another, and returns a `true`/`false` result.
> **Note:** See our [SyntaxError: missing ; before statement](/en-US/docs/Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement) reference page for more details about this error.
### The program always says you've won, regardless of the guess you enter
This could be another symptom of mixing up the assignment and strict equality operators. For example, if we were to change this line inside `checkGuess()`:
```js
if (userGuess === randomNumber) {
```
to
```js
if (userGuess = randomNumber) {
```
the test would always return `true`, causing the program to report that the game has been won. Be careful!
### SyntaxError: missing ) after argument list
This one is pretty simple β it generally means that you've missed the closing parenthesis at the end of a function/method call.
> **Note:** See our [SyntaxError: missing ) after argument list](/en-US/docs/Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list) reference page for more details about this error.
### SyntaxError: missing : after property id
This error usually relates to an incorrectly formed JavaScript object, but in this case we managed to get it by changing
```js
function checkGuess() {
```
to
```js
function checkGuess( {
```
This has caused the browser to think that we are trying to pass the contents of the function into the function as an argument. Be careful with those parentheses!
### SyntaxError: missing } after function body
This is easy β it generally means that you've missed one of your curly braces from a function or conditional structure. We got this error by deleting one of the closing curly braces near the bottom of the `checkGuess()` function.
### SyntaxError: expected expression, got '_string_' or SyntaxError: unterminated string literal
These errors generally mean that you've left off a string value's opening or closing quote mark. In the first error above, _string_ would be replaced with the unexpected character(s) that the browser found instead of a quote mark at the start of a string. The second error means that the string has not been ended with a quote mark.
For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go to that line and see if you can spot what's wrong. Bear in mind that the error is not necessarily going to be on that line, and also that the error might not be caused by the exact same problem we cited above!
> **Note:** See our [SyntaxError: Unexpected token](/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_token) and [SyntaxError: unterminated string literal](/en-US/docs/Web/JavaScript/Reference/Errors/Unterminated_string_literal) reference pages for more details about these errors.
## Summary
So there we have it, the basics of figuring out errors in simple JavaScript programs. It won't always be that simple to work out what's wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don't turn out right, especially in the earlier stages of your learning journey.
## See also
- There are many other types of errors that aren't listed here; we are compiling a reference that explains what they mean in detail β see the [JavaScript error reference](/en-US/docs/Web/JavaScript/Reference/Errors).
- If you come across any errors in your code that you aren't sure how to fix after reading this article, you can get help! Ask for help on the [communication channels](/en-US/docs/MDN/Community/Communication_channels). Tell us what your error is, and we'll try to help you. A listing of your code would be useful as well.
{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/test_your_skills_colon__math/index.md | ---
title: "Test your skills: Math"
slug: Learn/JavaScript/First_steps/Test_your_skills:_Math
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of the tests on this page is to assess whether you've understood the [Basic math in JavaScript β numbers and operators](/en-US/docs/Learn/JavaScript/First_steps/Math) 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 there is an error in your code, it will be logged into the results panel on this page or in the JavaScript console.
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Math 1
Let's start out by testing your knowledge of basic math operators.
You will create four numeric values, add two together, subtract one from another, then multiply the results.
Finally, we need to write a check that proves that this value is an even number.
Try updating the live code below to recreate the finished example by following these steps:
1. Create four variables that contain numbers. Call the variables something sensible.
2. Add the first two variables together and store the result in another variable.
3. Subtract the fourth variable from the third and store the result in another variable.
4. Multiply the results from steps **2** and **3** and store the result in a variable called `finalResult`.
5. Check if `finalResult` is an even number using one of the [arithmetic operators](/en-US/docs/Learn/JavaScript/First_steps/Math#arithmetic_operators). Store the result (`0` for even, `1` for odd) in a variable called `evenOddResult`.
To pass this test, `finalResult` should have a value of `48` and `evenOddResult` should have a value of `0`.
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/math/math1.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/math/math1-download.html) to work in your own editor or in an online editor.
## Math 2
In the second task, you are provided with two calculations with the results stored in the variables `result` and `result2`.
You need to take the calculations, multiply them, and format the result to two decimal places.
Try updating the live code below to recreate the finished example by following these steps:
1. Multiply `result` and `result2` and assign the result back to `result` (use assignment shorthand).
2. Format `result` so that it has two decimal places and store it in a variable called `finalResult`.
3. Check the data type of `finalResult` using `typeof`. If it's a `string`, convert it to a `number` type and store the result in a variable called `finalNumber`.
To pass this test, `finalNumber` should have a result of `4633.33`.
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/math/math2.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/math/math2-download.html) to work in your own editor or in an online editor.
## Math 3
In the final task for this article, we want you to write some tests.
There are three groups, each consisting of a statement and two variables.
For each one, write a test that proves or disproves the statement made.
Store the results of those tests in variables called `weightComparison`, `heightComparison`, and `pwdMatch`, respectively.
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/math/math3.html", '100%', 550)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/math/math3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/arrays/index.md | ---
title: Arrays
slug: Learn/JavaScript/First_steps/Arrays
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/Silly_story_generator", "Learn/JavaScript/First_steps")}}
In the final article of this module, we'll look at arrays β a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand what arrays are and how to manipulate them in JavaScript.
</td>
</tr>
</tbody>
</table>
## What is an array?
Arrays are generally described as "list-like objects"; they are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do super useful and efficient things with the list, like loop through it and do the same thing to every value. Maybe we've got a series of product items and their prices stored in an array, and we want to loop through them all and print them out on an invoice, while totaling all the prices together and printing out the total price at the bottom.
If we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item. This would be much longer to write out, less efficient, and more error-prone. If we had 10 items to add to the invoice it would already be annoying, but what about 100 items, or 1000? We'll return to this example later on in the article.
As in previous articles, let's learn about the real basics of arrays by entering some examples into [browser developer console](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools).
## Creating arrays
Arrays consist of square brackets and items that are separated by commas.
1. Suppose we want to store a shopping list in an array. Paste the following code into the console:
```js
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
console.log(shopping);
```
2. In the above example, each item is a string, but in an array we can store various data types β strings, numbers, objects, and even other arrays. We can also mix data types in a single array β we do not have to limit ourselves to storing only numbers in one array, and in another only strings. For example:
```js
const sequence = [1, 1, 2, 3, 5, 8, 13];
const random = ["tree", 795, [0, 1, 2]];
```
3. Before proceeding, create a few example arrays.
## Finding the length of an array
You can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string β by using the {{jsxref("Array.prototype.length","length")}} property. Try the following:
```js
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
console.log(shopping.length); // 5
```
## Accessing and modifying array items
Items in an array are numbered, starting from zero. This number is called the item's _index_. So the first item has index 0, the second has index 1, and so on. You can access individual items in the array using bracket notation and supplying the item's index, in the same way that you [accessed the letters in a string](/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#retrieving_a_specific_string_character).
1. Enter the following into your console:
```js
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
console.log(shopping[0]);
// returns "bread"
```
2. You can also modify an item in an array by giving a single array item a new value. Try this:
```js
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
shopping[0] = "tahini";
console.log(shopping);
// shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]
```
> **Note:** We've said it before, but just as a reminder β computers start counting from 0!
3. Note that an array inside an array is called a multidimensional array. You can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. For example, to access one of the items inside the array that is the third item inside the `random` array (see previous section), we could do something like this:
```js
const random = ["tree", 795, [0, 1, 2]];
random[2][2];
```
4. Try making some more modifications to your array examples before moving on. Play around a bit, and see what works and what doesn't.
## Finding the index of items in an array
If you don't know the index of an item, you can use the {{jsxref("Array.prototype.indexOf()","indexOf()")}} method.
The `indexOf()` method takes an item as an argument and will either return the item's index or `-1` if the item is not in the array:
```js
const birds = ["Parrot", "Falcon", "Owl"];
console.log(birds.indexOf("Owl")); // 2
console.log(birds.indexOf("Rabbit")); // -1
```
## Adding items
To add one or more items to the end of an array we can use {{jsxref("Array.prototype.push()","push()")}}. Note that you need to include one or more items that you want to add to the end of your array.
```js
const cities = ["Manchester", "Liverpool"];
cities.push("Cardiff");
console.log(cities); // [ "Manchester", "Liverpool", "Cardiff" ]
cities.push("Bradford", "Brighton");
console.log(cities); // [ "Manchester", "Liverpool", "Cardiff", "Bradford", "Brighton" ]
```
The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:
```js
const cities = ["Manchester", "Liverpool"];
const newLength = cities.push("Bristol");
console.log(cities); // [ "Manchester", "Liverpool", "Bristol" ]
console.log(newLength); // 3
```
To add an item to the start of the array, use {{jsxref("Array.prototype.unshift()","unshift()")}}:
```js
const cities = ["Manchester", "Liverpool"];
cities.unshift("Edinburgh");
console.log(cities); // [ "Edinburgh", "Manchester", "Liverpool" ]
```
## Removing items
To remove the last item from the array, use {{jsxref("Array.prototype.pop()","pop()")}}.
```js
const cities = ["Manchester", "Liverpool"];
cities.pop();
console.log(cities); // [ "Manchester" ]
```
The `pop()` method returns the item that was removed. To save that item in a new variable, you could do this:
```js
const cities = ["Manchester", "Liverpool"];
const removedCity = cities.pop();
console.log(removedCity); // "Liverpool"
```
To remove the first item from an array, use {{jsxref("Array.prototype.shift()","shift()")}}:
```js
const cities = ["Manchester", "Liverpool"];
cities.shift();
console.log(cities); // [ "Liverpool" ]
```
If you know the index of an item, you can remove it from the array using {{jsxref("Array.prototype.splice()","splice()")}}:
```js
const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
cities.splice(index, 1);
}
console.log(cities); // [ "Manchester", "Edinburgh", "Carlisle" ]
```
In this call to `splice()`, the first argument says where to start removing items, and the second argument says how many items should be removed. So you can remove more than one item:
```js
const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
cities.splice(index, 2);
}
console.log(cities); // [ "Manchester", "Carlisle" ]
```
## Accessing every item
Very often you will want to access every item in the array. You can do this using the {{jsxref("statements/for...of","for...of")}} statement:
```js
const birds = ["Parrot", "Falcon", "Owl"];
for (const bird of birds) {
console.log(bird);
}
```
Sometimes you will want to do the same thing to each item in an array, leaving you with an array containing the changed items. You can do this using {{jsxref("Array.prototype.map()","map()")}}. The code below takes an array of numbers and doubles each number:
```js
function double(number) {
return number * 2;
}
const numbers = [5, 2, 7, 6];
const doubled = numbers.map(double);
console.log(doubled); // [ 10, 4, 14, 12 ]
```
We give a function to the `map()`, and `map()` calls the function once for each item in the array, passing in the item. It then adds the return value from each function call to a new array, and finally returns the new array.
Sometimes you'll want to create a new array containing only the items in the original array that match some test. You can do that using {{jsxref("Array.prototype.filter()","filter()")}}. The code below takes an array of strings and returns an array containing just the strings that are greater than 8 characters long:
```js
function isLong(city) {
return city.length > 8;
}
const cities = ["London", "Liverpool", "Totnes", "Edinburgh"];
const longer = cities.filter(isLong);
console.log(longer); // [ "Liverpool", "Edinburgh" ]
```
Like `map()`, we give a function to the `filter()` method, and `filter()` calls this function for every item in the array, passing in the item. If the function returns `true`, then the item is added to a new array. Finally it returns the new array.
## Converting between strings and arrays
Often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then do things to them, like display them in a data table. To do this, we can use the {{jsxref("String.prototype.split()","split()")}} method. In its simplest form, this takes a single parameter, the character you want to separate the string at, and returns the substrings between the separator as items in an array.
> **Note:** Okay, this is technically a string method, not an array method, but we've put it in with arrays as it goes well here.
1. Let's play with this, to see how it works. First, create a string in your console:
```js
const data = "Manchester,London,Liverpool,Birmingham,Leeds,Carlisle";
```
2. Now let's split it at each comma:
```js
const cities = data.split(",");
cities;
```
3. Finally, try finding the length of your new array, and retrieving some items from it:
```js
cities.length;
cities[0]; // the first item in the array
cities[1]; // the second item in the array
cities[cities.length - 1]; // the last item in the array
```
4. You can also go the opposite way using the {{jsxref("Array.prototype.join()","join()")}} method. Try the following:
```js
const commaSeparated = cities.join(",");
commaSeparated;
```
5. Another way of converting an array to a string is to use the {{jsxref("Array.prototype.toString()","toString()")}} method. `toString()` is arguably simpler than `join()` as it doesn't take a parameter, but more limiting. With `join()` you can specify different separators, whereas `toString()` always uses a comma. (Try running Step 4 with a different character than a comma.)
```js
const dogNames = ["Rocket", "Flash", "Bella", "Slugger"];
dogNames.toString(); // Rocket,Flash,Bella,Slugger
```
## Active learning: Printing those products
Let's return to the example we described earlier β printing out product names and prices on an invoice, then totaling the prices and printing them at the bottom. In the editable example below there are comments containing numbers β each of these marks a place where you have to add something to the code. They are as follows:
1. Below the `// number 1` comment are a number of strings, each one containing a product name and price separated by a colon. We'd like you to turn this into an array and store it in an array called `products`.
2. Below the `// number 2` comment, start a `for...of()` loop to go through every item in the `products` array.
3. Below the `// number 3` comment we want you to write a line of code that splits the current array item (`name:price`) into two separate items, one containing just the name and one containing just the price. If you are not sure how to do this, consult the [Useful string methods](/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods) article for some help, or even better, look at the [Converting between strings and arrays](#converting_between_strings_and_arrays) section of this article.
4. As part of the above line of code, you'll also want to convert the price from a string to a number. If you can't remember how to do this, check out the [first strings article](/en-US/docs/Learn/JavaScript/First_steps/Strings#numbers_vs._strings).
5. There is a variable called `total` that is created and given a value of 0 at the top of the code. Inside the loop (below `// number 4`) we want you to add a line that adds the current item price to that total in each iteration of the loop, so that at the end of the code the correct total is printed onto the invoice. You might need an [assignment operator](/en-US/docs/Learn/JavaScript/First_steps/Math#assignment_operators) to do this.
6. We want you to change the line just below `// number 5` so that the `itemText` variable is made equal to "current item name β $current item price", for example "Shoes β $23.99" in each case, so the correct information for each item is printed on the invoice. This is just simple string concatenation, which should be familiar to you.
7. Finally, below the `// number 6` comment, you'll need to add a `}` to mark the end of the `for...of()` loop.
```html hidden
<h2>Live output</h2>
<div class="output" style="min-height: 150px;">
<ul></ul>
<p></p>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 410px;width: 95%">
const list = document.querySelector('.output ul');
const totalBox = document.querySelector('.output p');
let total = 0;
list.innerHTML = '';
totalBox.textContent = '';
// number 1
'Underpants:6.99'
'Socks:5.99'
'T-shirt:14.99'
'Trousers:31.99'
'Shoes:23.99';
// number 2
// number 3
// number 4
// number 5
let itemText = 0;
const listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
// number 6
totalBox.textContent = 'Total: $' + total.toFixed(2);
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```js hidden
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", () => {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const list = document.querySelector('.output ul');
const totalBox = document.querySelector('.output p');
let total = 0;
list.innerHTML = '';
totalBox.textContent = '';
const products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99',
];
for (const product of products) {
const subArray = product.split(':');
const name = subArray[0];
const price = Number(subArray[1]);
total += price;
const itemText = \`\${name} β $\${price}\`;
const listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
totalBox.textContent = \`Total: $\${total.toFixed(2)}\`;`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
const KEY_TAB = 9;
const KEY_ESC = 27;
textarea.onkeydown = (event) => {
if (event.keyCode === KEY_TAB) {
event.preventDefault();
insertAtCaret("\t");
}
if (event.keyCode === KEY_ESC) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = () => {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
```css hidden
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background-color: #f5f9fa;
}
```
{{ EmbedLiveSample('Active_learning_Printing_those_products', '100%', 750) }}
## Active learning: Top 5 searches
A good use for array methods like {{jsxref("Array.prototype.push()","push()")}} and {{jsxref("Array.prototype.pop()","pop()")}} is when you are maintaining a record of currently active items in a web app. In an animated scene for example, you might have an array of objects representing the background graphics currently displayed, and you might only want 50 displayed at once, for performance or clutter reasons. As new objects are created and added to the array, older ones can be deleted from the array to maintain the desired number.
In this example we're going to show a much simpler use β here we're giving you a fake search site, with a search box. The idea is that when terms are entered in the search box, the top 5 previous search terms are displayed in the list. When the number of terms goes over 5, the last term starts being deleted each time a new term is added to the top, so the 5 previous terms are always displayed.
> **Note:** In a real search app, you'd probably be able to click the previous search terms to return to previous searches, and it would display actual search results! We are just keeping it simple for now.
To complete the app, we need you to:
1. Add a line below the `// number 1` comment that adds the current value entered into the search input to the start of the array. This can be retrieved using `searchInput.value`.
2. Add a line below the `// number 2` comment that removes the value currently at the end of the array.
```html hidden
<h2>Live output</h2>
<div class="output" style="min-height: 150px;">
<input type="text" /><button>Search</button>
<ul></ul>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 370px; width: 95%">
const list = document.querySelector('.output ul');
const searchInput = document.querySelector('.output input');
const searchBtn = document.querySelector('.output button');
list.innerHTML = '';
const myHistory = [];
const MAX_HISTORY = 5;
searchBtn.onclick = () => {
// we will only allow a term to be entered if the search input isn't empty
if (searchInput.value !== '') {
// number 1
// empty the list so that we don't display duplicate entries
// the display is regenerated every time a search term is entered.
list.innerHTML = '';
// loop through the array, and display all the search terms in the list
for (const itemText of myHistory) {
const listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
// If the array length is 5 or more, remove the oldest search term
if (myHistory.length >= MAX_HISTORY) {
// number 2
}
// empty the search input and focus it, ready for the next term to be entered
searchInput.value = '';
searchInput.focus();
}
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css hidden
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```js hidden
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", () => {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const list = document.querySelector('.output ul');
const searchInput = document.querySelector('.output input');
const searchBtn = document.querySelector('.output button');
list.innerHTML = '';
const myHistory = [];
const MAX_HISTORY = 5;
searchBtn.onclick = () => {
// we will only allow a term to be entered if the search input isn't empty
if (searchInput.value !== '') {
myHistory.unshift(searchInput.value);
// empty the list so that we don't display duplicate entries
// the display is regenerated every time a search term is entered.
list.innerHTML = '';
// loop through the array, and display all the search terms in the list
for (const itemText of myHistory) {
const listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
// If the array length is 5 or more, remove the oldest search term
if (myHistory.length >= MAX_HISTORY) {
myHistory.pop();
}
// empty the search input and focus it, ready for the next term to be entered
searchInput.value = '';
searchInput.focus();
}
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
const KEY_TAB = 9;
const KEY_ESC = 27;
textarea.onkeydown = (event) => {
if (event.keyCode === KEY_TAB) {
event.preventDefault();
insertAtCaret("\t");
}
if (event.keyCode === KEY_ESC) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = () => {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
{{ EmbedLiveSample('Active_learning_Top_5_searches', '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: Arrays](/en-US/docs/Learn/JavaScript/First_steps/Test_your_skills:_Arrays).
## Conclusion
After reading through this article, we are sure you will agree that arrays seem pretty darn useful; you'll see them crop up everywhere in JavaScript, often in association with loops in order to do the same thing to every item in an array. We'll be teaching you all the useful basics there are to know about loops in the next module, but for now you should give yourself a clap and take a well-deserved break; you've worked through all the articles in this module!
The only thing left to do is work through this module's assessment, which will test your understanding of the articles that came before it.
## See also
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) β an advanced level guide to arrays and their cousins, typed arrays.
- {{jsxref("Array")}} β the `Array` object reference page β for a detailed reference guide to the features discussed in this page, and many more.
{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/Silly_story_generator", "Learn/JavaScript/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/test_your_skills_colon__arrays/index.md | ---
title: "Test your skills: Arrays"
slug: Learn/JavaScript/First_steps/Test_your_skills:_Arrays
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Arrays](/en-US/docs/Learn/JavaScript/First_steps/Arrays) 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).
## Arrays 1
Let's start off with some basic array practice. In this task we'd like you to create an array of three items, stored inside a variable called `myArray`. The items can be anything you want β how about your favorite foods or bands?
Next, modify the first two items in the array using simple bracket notation and assignment. Then add a new item to the beginning of the array.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/arrays/arrays1.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/arrays/arrays1-download.html) to work in your own editor or in an online editor.
## Arrays 2
Now let's move on to another task. Here you are provided with a string to work with. We'd like you to:
1. Convert the string into an array, removing the `+` characters in the process. Save the result in a variable called `myArray`.
2. Store the length of the array in a variable called `arrayLength`.
3. Store the last item in the array in a variable called `lastItem`.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/arrays/arrays2.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/arrays/arrays2-download.html) to work in your own editor or in an online editor.
## Arrays 3
For this array task, we provide you with a starting array, and you will work in somewhat the opposite direction. You need to:
1. Remove the last item in the array.
2. Add two new names to the end of the array.
3. Go over each item in the array and add its index number after the name inside parentheses, for example `Ryu (0)`. Note that we don't teach how to do this in the Arrays article, so you'll have to do some research.
4. Finally, join the array items together in a single string called `myString`, with a separator of "`-`".
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/arrays/arrays3.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/arrays/arrays3-download.html) to work in your own editor or in an online editor.
## Arrays 4
For this array task, we provide you with a starting array listing the names of some birds.
- Find the index of the `"Eagles"` item, and use that to remove the `"Eagles"` item.
- Make a new array from this one, called `eBirds`, that contains only birds from the original array whose names begin with the letter "E". Note that {{jsxref("String.prototype.startsWith()", "startsWith()")}} is a great way to check whether a string starts with a given character.
If it works, you should see `"Emus,Egrets"` appear in the page.
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/tasks/arrays/arrays4.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/tasks/arrays/arrays4-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/useful_string_methods/index.md | ---
title: Useful string methods
slug: Learn/JavaScript/First_steps/Useful_string_methods
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}
Now that we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand that strings are objects, and learn how to use some of the
basic methods available on those objects to manipulate strings.
</td>
</tr>
</tbody>
</table>
## Strings as objects
Most things are objects in JavaScript. When you create a string, for example by using
```js
const string = "This is my string";
```
your variable becomes a string object instance, and as a result has a large number of properties and methods available to it. You can see this if you go to the {{jsxref("String")}} object page and look down the list on the side of the page!
**Now, before your brain starts melting, don't worry!** You really don't need to know about most of these early on in your learning journey. But there are a few that you'll potentially use quite often that we'll look at here.
Let's enter some examples into the [browser developer console](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools).
## Finding the length of a string
This is easy β you use the {{jsxref("String.prototype.length", "length")}} property. Try entering the following lines:
```js
const browserType = "mozilla";
browserType.length;
```
This should return the number 7, because "mozilla" is 7 characters long. This is useful for many reasons; for example, you might want to find the lengths of a series of names so you can display them in order of length, or let a user know that a username they have entered into a form field is too long if it is over a certain length.
## Retrieving a specific string character
On a related note, you can return any character inside a string by using **square bracket notation** β this means you include square brackets (`[]`) on the end of your variable name. Inside the square brackets, you include the number of the character you want to return, so for example to retrieve the first letter you'd do this:
```js
browserType[0];
```
Remember: computers count from 0, not 1!
To retrieve the last character of _any_ string, we could use the following line, combining this technique with the `length` property we looked at above:
```js
browserType[browserType.length - 1];
```
The length of the string "mozilla" is 7, but because the count starts at 0, the last character's position is 6; using `length-1` gets us the last character.
## Testing if a string contains a substring
Sometimes you'll want to find if a smaller string is present inside a larger one (we generally say _if a substring is present inside a string_). This can be done using the {{jsxref("String.prototype.includes()", "includes()")}} method, which takes a single {{glossary("parameter")}} β the substring you want to search for.
It returns `true` if the string contains the substring, and `false` otherwise.
```js
const browserType = "mozilla";
if (browserType.includes("zilla")) {
console.log("Found zilla!");
} else {
console.log("No zilla here!");
}
```
Often you'll want to know if a string starts or ends with a particular substring. This is a common enough need that there are two special methods for this: {{jsxref("String.prototype.startsWith()", "startsWith()")}} and {{jsxref("String.prototype.endsWith()", "endsWith()")}}:
```js
const browserType = "mozilla";
if (browserType.startsWith("zilla")) {
console.log("Found zilla!");
} else {
console.log("No zilla here!");
}
```
```js
const browserType = "mozilla";
if (browserType.endsWith("zilla")) {
console.log("Found zilla!");
} else {
console.log("No zilla here!");
}
```
## Finding the position of a substring in a string
You can find the position of a substring inside a larger string using the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method. This method takes two {{glossary("parameter", "parameters")}} β the substring that you want to search for, and an optional parameter that specifies the starting point of the search.
If the string contains the substring, `indexOf()` returns the index of the first occurrence of the substring. If the string does not contain the substring, `indexOf()` returns `-1`.
```js
const tagline = "MDN - Resources for developers, by developers";
console.log(tagline.indexOf("developers")); // 20
```
Starting at `0`, if you count the number of characters (including the whitespace) from the beginning of the string, the first occurrence of the substring `"developers"` is at index `20`.
```js
console.log(tagline.indexOf("x")); // -1
```
This, on the other hand, returns `-1` because the character `x` is not present in the string.
So now that you know how to find the first occurrence of a substring, how do you go about finding subsequent occurrences? You can do that by passing in a value that's greater than the index of the previous occurrence as the second parameter to the method.
```js
const firstOccurrence = tagline.indexOf("developers");
const secondOccurrence = tagline.indexOf("developers", firstOccurrence + 1);
console.log(firstOccurrence); // 20
console.log(secondOccurrence); // 35
```
Here we're telling the method to search for the substring `"developers"` starting at index `21` (`firstOccurrence + 1`), and it returns the index `35`.
## Extracting a substring from a string
You can extract a substring from a string using the {{jsxref("String.prototype.slice()", "slice()")}} method. You pass it:
- the index at which to start extracting
- the index at which to stop extracting. This is exclusive, meaning that the character at this index is not included in the extracted substring.
For example:
```js
const browserType = "mozilla";
console.log(browserType.slice(1, 4)); // "ozi"
```
The character at index `1` is `"o"`, and the character at index 4 is `"l"`. So we extract all characters starting at `"o"` and ending just before `"l"`, giving us `"ozi"`.
If you know that you want to extract all of the remaining characters in a string after a certain character, you don't have to include the second parameter. Instead, you only need to include the character position from where you want to extract the remaining characters in a string. Try the following:
```js
browserType.slice(2); // "zilla"
```
This returns `"zilla"` β this is because the character position of 2 is the letter `"z"`, and because you didn't include a second parameter, the substring that was returned was all of the remaining characters in the string.
> **Note:** `slice()` has other options too; study the {{jsxref("String.prototype.slice()", "slice()")}} page to see what else you can find out.
## Changing case
The string methods {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} and {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}} take a string and convert all the characters to lower- or uppercase, respectively. This can be useful for example if you want to normalize all user-entered data before storing it in a database.
Let's try entering the following lines to see what happens:
```js
const radData = "My NaMe Is MuD";
console.log(radData.toLowerCase());
console.log(radData.toUpperCase());
```
## Updating parts of a string
You can replace one substring inside a string with another substring using the {{jsxref("String.prototype.replace()", "replace()")}} method.
In this example, we're providing two parameters β the string we want to replace, and the string we want to replace it with:
```js
const browserType = "mozilla";
const updated = browserType.replace("moz", "van");
console.log(updated); // "vanilla"
console.log(browserType); // "mozilla"
```
Note that `replace()`, like many string methods, doesn't change the string it was called on, but returns a new string. If you want to update the original `browserType` variable, you would have to do something like this:
```js
let browserType = "mozilla";
browserType = browserType.replace("moz", "van");
console.log(browserType); // "vanilla"
```
Also note that we now have to declare `browserType` using `let`, not `const`, because we are reassigning it.
Be aware that `replace()` in this form only changes the first occurrence of the substring. If you want to change all occurrences, you can use {{jsxref("String.prototype.replaceAll()", "replaceAll()")}}:
```js
let quote = "To be or not to be";
quote = quote.replaceAll("be", "code");
console.log(quote); // "To code or not to code"
```
## Active learning examples
In this section, we'll get you to try your hand at writing some string manipulation code. In each exercise below, we have an array of strings, and a loop that processes each value in the array and displays it in a bulleted list. You don't need to understand arrays or loops right now β these will be explained in future articles. All you need to do in each case is write the code that will output the strings in the format that we want them in.
Each example comes with a "Reset" button, which you can use to reset the code if you make a mistake and can't get it working again, and a "Show solution" button you can press to see a potential answer if you get really stuck.
### Filtering greeting messages
In the first exercise, we'll start you off simple β we have an array of greeting card messages, but we want to sort them to list just the Christmas messages. We want you to fill in a conditional test inside the `if ()` structure to test each string and only print it in the list if it is a Christmas message.
Think about how you could test whether the message in each case is a Christmas message. What string is present in all of those messages, and what method could you use to test whether it is present?
```html hidden
<h2>Live output</h2>
<div class="output" style="min-height: 125px;">
<ul></ul>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 290px; width: 95%">
const list = document.querySelector('.output ul');
list.innerHTML = '';
const greetings = ['Happy Birthday!',
'Merry Christmas my love',
'A happy Christmas to all the family',
'You\'re all I want for Christmas',
'Get well soon'];
for (const greeting of greetings) {
// Your conditional test needs to go inside the parentheses
// in the line below, replacing what's currently there
if (greeting) {
const listItem = document.createElement('li');
listItem.textContent = greeting;
list.appendChild(listItem);
}
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css hidden
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```js hidden
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", () => {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const list = document.querySelector('.output ul');
list.innerHTML = '';
const greetings = [
'Happy Birthday!',
'Merry Christmas my love',
'A happy Christmas to all the family',
'You\\'re all I want for Christmas',
'Get well soon',
];
for (const greeting of greetings) {
// Your conditional test needs to go inside the parentheses
// in the line below, replacing what's currently there
if (greeting.includes('Christmas')) {
const listItem = document.createElement('li');
listItem.textContent = greeting;
list.appendChild(listItem);
}
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = (e) => {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = () => {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
{{ EmbedLiveSample('Filtering_greeting_messages', '100%', 600) }}
### Fixing capitalization
In this exercise, we have the names of cities in the United Kingdom, but the capitalization is all messed up. We want you to change them so that they are all lowercase, except for a capital first letter. A good way to do this is to:
1. Convert the whole of the string contained in the `city` variable to lowercase and store it in a new variable.
2. Grab the first letter of the string in this new variable and store it in another variable.
3. Using this latest variable as a substring, replace the first letter of the lowercase string with the first letter of the lowercase string changed to upper case. Store the result of this replacement procedure in another new variable.
4. Change the value of the `result` variable to equal to the final result, not the `city`.
> **Note:** A hint β the parameters of the string methods don't have to be string literals; they can also be variables, or even variables with a method being invoked on them.
```html hidden
<h2>Live output</h2>
<div class="output" style="min-height: 125px;">
<ul></ul>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 250px; width: 95%">
const list = document.querySelector('.output ul');
list.innerHTML = '';
const cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOL'];
for (const city of cities) {
// write your code just below here
const result = city;
const listItem = document.createElement('li');
listItem.textContent = result;
list.appendChild(listItem);
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css hidden
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```js hidden
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", function () {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const list = document.querySelector('.output ul');
list.innerHTML = '';
const cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOL'];
for (const city of cities) {
// write your code just below here
const lower = city.toLowerCase();
const firstLetter = lower.slice(0,1);
const capitalized = lower.replace(firstLetter,firstLetter.toUpperCase());
const result = capitalized;
const listItem = document.createElement('li');
listItem.textContent = result;
list.appendChild(listItem);
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function (e) {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = function () {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
{{ EmbedLiveSample('Fixing_capitalization', '100%', 570) }}
### Making new strings from old parts
In this last exercise, the array contains a bunch of strings containing information about train stations in the North of England. The strings are data items that contain the three-letter station code, followed by some machine-readable data, followed by a semicolon, followed by the human-readable station name. For example:
```plain
MAN675847583748sjt567654;Manchester Piccadilly
```
We want to extract the station code and name, and put them together in a string with the following structure:
```plain
MAN: Manchester Piccadilly
```
We'd recommend doing it like this:
1. Extract the three-letter station code and store it in a new variable.
2. Find the character index number of the semicolon.
3. Extract the human-readable station name using the semicolon character index number as a reference point, and store it in a new variable.
4. Concatenate the two new variables and a string literal to make the final string.
5. Change the value of the `result` variable to the final string, not the `station`.
```html hidden
<h2>Live output</h2>
<div class="output" style="min-height: 125px;">
<ul></ul>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 285px; width: 95%">
const list = document.querySelector('.output ul');
list.innerHTML = '';
const stations = ['MAN675847583748sjt567654;Manchester Piccadilly',
'GNF576746573fhdg4737dh4;Greenfield',
'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street',
'SYB4f65hf75f736463;Stalybridge',
'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield'];
for (const station of stations) {
// write your code just below here
const result = station;
const listItem = document.createElement('li');
listItem.textContent = result;
list.appendChild(listItem);
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css hidden
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```js hidden
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", function () {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const list = document.querySelector('.output ul');
list.innerHTML = '';
const stations = ['MAN675847583748sjt567654;Manchester Piccadilly',
'GNF576746573fhdg4737dh4;Greenfield',
'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street',
'SYB4f65hf75f736463;Stalybridge',
'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield'];
for (const station of stations) {
// write your code just below here
const code = station.slice(0,3);
const semiColon = station.indexOf(';');
const name = station.slice(semiColon + 1);
const result = \`\${code}: \${name}\`;
const listItem = document.createElement('li');
listItem.textContent = result;
list.appendChild(listItem);
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function (e) {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = function () {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
{{ EmbedLiveSample('Making_new_strings_from_old_parts', '100%', 600) }}
## 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: Strings](/en-US/docs/Learn/JavaScript/First_steps/Test_your_skills:_Strings).
## Conclusion
You can't escape the fact that being able to handle words and sentences in programming is very important β particularly in JavaScript, as websites are all about communicating with people. This article has given you the basics that you need to know about manipulating strings for now. This should serve you well as you go into more complex topics in the future. Next, we're going to look at the last major type of data we need to focus on in the short term β arrays.
{{PreviousMenuNext("Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/math/index.md | ---
title: Basic math in JavaScript β numbers and operators
slug: Learn/JavaScript/First_steps/Math
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps")}}
At this point in the course, we discuss math in JavaScript β how we can use {{Glossary("Operator","operators")}} and other features to successfully manipulate numbers to do our bidding.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To gain familiarity with the basics of math in JavaScript.</td>
</tr>
</tbody>
</table>
## Everybody loves math
Okay, maybe not. Some of us like math, some of us have hated math ever since we had to learn multiplication tables and long division in school, and some of us sit somewhere in between the two. But none of us can deny that math is a fundamental part of life that we can't get very far without. This is especially true when we are learning to program JavaScript (or any other language for that matter) β so much of what we do relies on processing numerical data, calculating new values, and so on, that you won't be surprised to learn that JavaScript has a full-featured set of math functions available.
This article discusses only the basic parts that you need to know now.
### Types of numbers
In programming, even the humble decimal number system that we all know so well is more complicated than you might think. We use different terms to describe different types of decimal numbers, for example:
- **Integers** are floating-point numbers without a fraction. They can either be positive or negative, e.g. 10, 400, or -5.
- **Floating point numbers** (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.
- **Doubles** are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).
We even have different types of number systems! Decimal is base 10 (meaning it uses 0β9 in each column), but we also have things like:
- **Binary** β The lowest level language of computers; 0s and 1s.
- **Octal** β Base 8, uses 0β7 in each column.
- **Hexadecimal** β Base 16, uses 0β9 and then aβf in each column. You may have encountered these numbers before when setting [colors in CSS](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#hexadecimal_values).
**Before you start to get worried about your brain melting, stop right there!** For a start, we are just going to stick to decimal numbers throughout this course; you'll rarely come across a need to start thinking about other types, if ever.
The second bit of good news is that unlike some other programming languages, JavaScript only has one data type for numbers, both integers and decimals β you guessed it, {{jsxref("Number")}}. This means that whatever type of numbers you are dealing with in JavaScript, you handle them in exactly the same way.
> **Note:** Actually, JavaScript has a second number type, {{Glossary("BigInt")}}, used for very, very large integers. But for the purposes of this course, we'll just worry about `Number` values.
### It's all numbers to me
Let's quickly play with some numbers to reacquaint ourselves with the basic syntax we need. Enter the commands listed below into your [developer tools JavaScript console](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools).
1. First of all, let's declare a couple of variables and initialize them with an integer and a float, respectively, then type the variable names back in to check that everything is in order:
```js
const myInt = 5;
const myFloat = 6.667;
myInt;
myFloat;
```
2. Number values are typed in without quote marks β try declaring and initializing a couple more variables containing numbers before you move on.
3. Now let's check that both our original variables are of the same datatype. There is an operator called {{jsxref("Operators/typeof", "typeof")}} in JavaScript that does this. Enter the below two lines as shown:
```js
typeof myInt;
typeof myFloat;
```
You should get `"number"` returned in both cases β this makes things a lot easier for us than if different numbers had different data types, and we had to deal with them in different ways. Phew!
### Useful Number methods
The [`Number`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) object, an instance of which represents all standard numbers you'll use in your JavaScript, has a number of useful methods available on it for you to manipulate numbers. We don't cover these in detail in this article because we wanted to keep it as a simple introduction and only cover the real basic essentials for now; however, once you've read through this module a couple of times it is worth going to the object reference pages and learning more about what's available.
For example, to round your number to a fixed number of decimal places, use the [`toFixed()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) method. Type the following lines into your browser's [console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html):
```js
const lotsOfDecimal = 1.766584958675746364;
lotsOfDecimal;
const twoDecimalPlaces = lotsOfDecimal.toFixed(2);
twoDecimalPlaces;
```
### Converting to number data types
Sometimes you might end up with a number that is stored as a string type, which makes it difficult to perform calculations with it. This most commonly happens when data is entered into a [form](/en-US/docs/Learn/Forms) input, and the [input type is text](/en-US/docs/Web/HTML/Element/input/text). There is a way to solve this problem β passing the string value into the [`Number()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number) constructor to return a number version of the same value.
For example, try typing these lines into your console:
```js
let myNumber = "74";
myNumber += 3;
```
You end up with the result 743, not 77, because `myNumber` is actually defined as a string. You can test this by typing in the following:
```js
typeof myNumber;
```
To fix the calculation, you can do this:
```js
let myNumber = "74";
myNumber = Number(myNumber) + 3;
```
The result is then 77, as initially expected.
## Arithmetic operators
Arithmetic operators are used for performing mathematical calculations in JavaScript:
<table class="standard-table">
<thead>
<tr>
<th scope="col">Operator</th>
<th scope="col">Name</th>
<th scope="col">Purpose</th>
<th scope="col">Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>+</code></td>
<td>Addition</td>
<td>Adds two numbers together.</td>
<td><code>6 + 9</code></td>
</tr>
<tr>
<td><code>-</code></td>
<td>Subtraction</td>
<td>Subtracts the right number from the left.</td>
<td><code>20 - 15</code></td>
</tr>
<tr>
<td><code>*</code></td>
<td>Multiplication</td>
<td>Multiplies two numbers together.</td>
<td><code>3 * 7</code></td>
</tr>
<tr>
<td><code>/</code></td>
<td>Division</td>
<td>Divides the left number by the right.</td>
<td><code>10 / 5</code></td>
</tr>
<tr>
<td><code>%</code></td>
<td>Remainder (sometimes called modulo)</td>
<td>
<p>
Returns the remainder left over after you've divided the left number
into a number of integer portions equal to the right number.
</p>
</td>
<td>
<p>
<code>8 % 3</code> (returns 2, as three goes into 8 twice, leaving 2
left over).
</p>
</td>
</tr>
<tr>
<td><code>**</code></td>
<td>Exponent</td>
<td>
Raises a <code>base</code> number to the <code>exponent</code> power,
that is, the <code>base</code> number multiplied by itself,
<code>exponent</code> times.
</td>
<td>
<code>5 ** 2</code> (returns <code>25</code>, which is the same as
<code>5 * 5</code>).
</td>
</tr>
</tbody>
</table>
> **Note:** You'll sometimes see numbers involved in arithmetic referred to as {{Glossary("Operand", "operands")}}.
> **Note:** You may sometimes see exponents expressed using the older {{jsxref("Math.pow()")}} method, which works in a very similar way. For example, in `Math.pow(7, 3)`, `7` is the base and `3` is the exponent, so the result of the expression is `343`. `Math.pow(7, 3)` is equivalent to `7**3`.
We probably don't need to teach you how to do basic math, but we would like to test your understanding of the syntax involved. Try entering the examples below into your [developer tools JavaScript console](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools) to familiarize yourself with the syntax.
1. First try entering some simple examples of your own, such as
```js
10 + 7;
9 * 8;
60 % 3;
```
2. You can also try declaring and initializing some numbers inside variables, and try using those in the sums β the variables will behave exactly like the values they hold for the purposes of the sum. For example:
```js
const num1 = 10;
const num2 = 50;
9 * num1;
num1 ** 3;
num2 / num1;
```
3. Last for this section, try entering some more complex expressions, such as:
```js
5 + 10 * 3;
(num2 % 9) * num1;
num2 + num1 / 8 + 2;
```
Parts of this last set of calculations might not give you quite the result you were expecting; the section below might well give the answer as to why.
### Operator precedence
Let's look at the last example from above, assuming that `num2` holds the value 50 and `num1` holds the value 10 (as originally stated above):
```js
num2 + num1 / 8 + 2;
```
As a human being, you may read this as _"50 plus 10 equals 60"_, then _"8 plus 2 equals 10"_, and finally _"60 divided by 10 equals 6"_.
But the browser does _"10 divided by 8 equals 1.25"_, then _"50 plus 1.25 plus 2 equals 53.25"_.
This is because of **operator precedence** β some operators are applied before others when calculating the result of a calculation (referred to as an _expression_, in programming). Operator precedence in JavaScript is the same as is taught in math classes in school β multiply and divide are always done first, then add and subtract (the calculation is always evaluated from left to right).
If you want to override operator precedence, you can put parentheses around the parts that you want to be explicitly dealt with first. So to get a result of 6, we could do this:
```js
(num2 + num1) / (8 + 2);
```
Try it and see.
> **Note:** A full list of all JavaScript operators and their precedence can be found in [Operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence).
## Increment and decrement operators
Sometimes you'll want to repeatedly add or subtract one to or from a numeric variable value. This can be conveniently done using the increment (`++`) and decrement (`--`) operators. We used `++` in our "Guess the number" game back in our [first splash into JavaScript](/en-US/docs/Learn/JavaScript/First_steps/A_first_splash) article, when we added 1 to our `guessCount` variable to keep track of how many guesses the user has left after each turn.
```js
guessCount++;
```
Let's try playing with these in your console. For a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a new updated value, not operating on the value itself. The following will return an error:
```js example-bad
3++;
```
So, you can only increment an existing variable. Try this:
```js
let num1 = 4;
num1++;
```
Okay, strangeness number 2! When you do this, you'll see a value of 4 returned β this is because the browser returns the current value, _then_ increments the variable. You can see that it's been incremented if you return the variable value again:
```js
num1;
```
The same is true of `--` : try the following
```js
let num2 = 6;
num2--;
num2;
```
> **Note:** You can make the browser do it the other way round β increment/decrement the variable _then_ return the value β by putting the operator at the start of the variable instead of the end. Try the above examples again, but this time use `++num1` and `--num2`.
## Assignment operators
Assignment operators are operators that assign a value to a variable. We have already used the most basic one, `=`, loads of times β it assigns the variable on the left the value stated on the right:
```js
let x = 3; // x contains the value 3
let y = 4; // y contains the value 4
x = y; // x now contains the same value y contains, 4
```
But there are some more complex types, which provide useful shortcuts to keep your code neater and more efficient. The most common are listed below:
<table class="standard-table no-markdown">
<thead>
<tr>
<th scope="col">Operator</th>
<th scope="col">Name</th>
<th scope="col">Purpose</th>
<th scope="col">Example</th>
<th scope="col">Shortcut for</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>+=</code></td>
<td>Addition assignment</td>
<td>
Adds the value on the right to the variable value on the left, then
returns the new variable value
</td>
<td><code>x += 4;</code></td>
<td><code>x = x + 4;</code></td>
</tr>
<tr>
<td><code>-=</code></td>
<td>Subtraction assignment</td>
<td>
Subtracts the value on the right from the variable value on the left,
and returns the new variable value
</td>
<td><code>x -= 3;</code></td>
<td><code>x = x - 3;</code></td>
</tr>
<tr>
<td><code>*=</code></td>
<td>Multiplication assignment</td>
<td>
Multiplies the variable value on the left by the value on the right, and
returns the new variable value
</td>
<td><code>x *= 3;</code></td>
<td><code>x = x * 3;</code></td>
</tr>
<tr>
<td><code>/=</code></td>
<td>Division assignment</td>
<td>
Divides the variable value on the left by the value on the right, and
returns the new variable value
</td>
<td><code>x /= 5;</code></td>
<td><code>x = x / 5;</code></td>
</tr>
</tbody>
</table>
Try typing some of the above examples into your console, to get an idea of how they work. In each case, see if you can guess what the value is before you type in the second line.
Note that you can quite happily use other variables on the right-hand side of each expression, for example:
```js
let x = 3; // x contains the value 3
let y = 4; // y contains the value 4
x *= y; // x now contains the value 12
```
> **Note:** There are lots of [other assignment operators available](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators), but these are the basic ones you should learn now.
## Active learning: sizing a canvas box
In this exercise, you will manipulate some numbers and operators to change the size of a box. The box is drawn using a browser API called the {{domxref("Canvas API", "", "", "true")}}. There is no need to worry about how this works β just concentrate on the math for now. The width and height of the box (in pixels) are defined by the variables `x` and `y`, which are initially both given a value of 50.
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/maths/editable_canvas.html", '100%', 620)}}
**[Open in new window](https://mdn.github.io/learning-area/javascript/introduction-to-js-1/maths/editable_canvas.html)**
In the editable code box above, there are two lines marked with a comment that we'd like you to update to make the box grow/shrink to certain sizes, using certain operators and/or values in each case. Let's try the following:
- Change the line that calculates x so the box is still 50px wide, but the 50 is calculated using the numbers 43 and 7 and an arithmetic operator.
- Change the line that calculates y so the box is 75px high, but the 75 is calculated using the numbers 25 and 3 and an arithmetic operator.
- Change the line that calculates x so the box is 250px wide, but the 250 is calculated using two numbers and the remainder (modulo) operator.
- Change the line that calculates y so the box is 150px high, but the 150 is calculated using three numbers and the subtraction and division operators.
- Change the line that calculates x so the box is 200px wide, but the 200 is calculated using the number 4 and an assignment operator.
- Change the line that calculates y so the box is 200px high, but the 200 is calculated using the numbers 50 and 3, the multiplication operator, and the addition assignment operator.
Don't worry if you totally mess the code up. You can always press the Reset button to get things working again. After you've answered all the above questions correctly, feel free to play with the code some more or create your own challenges.
## Comparison operators
Sometimes we will want to run true/false tests, then act accordingly depending on the result of that test β to do this we use **comparison operators**.
| Operator | Name | Purpose | Example |
| -------- | ------------------------ | ---------------------------------------------------------------------------- | ------------- |
| `===` | Strict equality | Tests whether the left and right values are identical to one another | `5 === 2 + 4` |
| `!==` | Strict-non-equality | Tests whether the left and right values are **not** identical to one another | `5 !== 2 + 3` |
| `<` | Less than | Tests whether the left value is smaller than the right one. | `10 < 6` |
| `>` | Greater than | Tests whether the left value is greater than the right one. | `10 > 20` |
| `<=` | Less than or equal to | Tests whether the left value is smaller than or equal to the right one. | `3 <= 2` |
| `>=` | Greater than or equal to | Tests whether the left value is greater than or equal to the right one. | `5 >= 4` |
> **Note:** You may see some people using `==` and `!=` in their tests for equality and non-equality. These are valid operators in JavaScript, but they differ from `===`/`!==`. The former versions test whether the values are the same but not whether the values' datatypes are the same. The latter, strict versions test the equality of both the values and their datatypes. The strict versions tend to result in fewer errors, so we recommend you use them.
If you try entering some of these values in a console, you'll see that they all return `true`/`false` values β those booleans we mentioned in the last article. These are very useful, as they allow us to make decisions in our code, and they are used every time we want to make a choice of some kind. For example, booleans can be used to:
- Display the correct text label on a button depending on whether a feature is turned on or off
- Display a game over message if a game is over or a victory message if the game has been won
- Display the correct seasonal greeting depending on what holiday season it is
- Zoom a map in or out depending on what zoom level is selected
We'll look at how to code such logic when we look at conditional statements in a future article. For now, let's look at a quick example:
```html
<button>Start machine</button>
<p>The machine is stopped.</p>
```
```js
const btn = document.querySelector("button");
const txt = document.querySelector("p");
btn.addEventListener("click", updateBtn);
function updateBtn() {
if (btn.textContent === "Start machine") {
btn.textContent = "Stop machine";
txt.textContent = "The machine has started!";
} else {
btn.textContent = "Start machine";
txt.textContent = "The machine is stopped.";
}
}
```
{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/maths/conditional.html", '100%', 100)}}
**[Open in new window](https://mdn.github.io/learning-area/javascript/introduction-to-js-1/maths/conditional.html)**
You can see the equality operator being used just inside the `updateBtn()` function. In this case, we are not testing if two mathematical expressions have the same value β we are testing whether the text content of a button contains a certain string β but it is still the same principle at work. If the button is currently saying "Start machine" when it is pressed, we change its label to "Stop machine", and update the label as appropriate. If the button is currently saying "Stop machine" when it is pressed, we swap the display back again.
> **Note:** Such a control that swaps between two states is generally referred to as a **toggle**. It toggles between one state and another β light on, light off, etc.
## 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: Math](/en-US/docs/Learn/JavaScript/First_steps/Test_your_skills:_Math).
## Summary
In this article, we have covered the fundamental information you need to know about numbers in JavaScript, for now. You'll see numbers used again and again, all the way through your JavaScript learning, so it's a good idea to get this out of the way now. If you are one of those people that doesn't enjoy math, you can take comfort in the fact that this chapter was pretty short.
In the next article, we'll explore text and how JavaScript allows us to manipulate it.
> **Note:** If you do enjoy math and want to read more about how it is implemented in JavaScript, you can find a lot more detail in MDN's main JavaScript section. Great places to start are our [Numbers and dates](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates) and [Expressions and operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators) articles.
{{PreviousMenuNext("Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/silly_story_generator/index.md | ---
title: Silly story generator
slug: Learn/JavaScript/First_steps/Silly_story_generator
page-type: learn-module-assessment
---
{{LearnSidebar}}{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}
In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!
<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 JavaScript fundamentals, such as variables,
numbers, operators, strings, and arrays.
</td>
</tr>
</tbody>
</table>
## Starting point
To get this assessment started, you should:
- Go and [grab the HTML file](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/assessment-start/index.html) for the example, save a local copy of it as `index.html` in a new directory somewhere on your computer, and do the assessment locally to begin with. This also has the CSS to style the example contained within it.
- Go to the [page containing the raw text](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/assessment-start/raw-text.txt) and keep this open in a separate browser tab somewhere. You'll need it later.
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, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have a separate JavaScript panel, feel free to put it inline in a `<script>` element inside the HTML page.
> **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/CSS and a few text strings and JavaScript functions; you need to write the necessary JavaScript to turn this into a working program, which does the following:
- Generates a silly story when the "Generate random story" button is pressed.
- Replaces the default name "Bob" in the story with a custom name, only if a custom name is entered into the "Enter custom name" text field before the generate button is pressed.
- Converts the default US weight and temperature quantities and units in the story into UK equivalents if the UK radio button is checked before the generate button is pressed.
- Generates a new random silly story every time the button is pressed.
The following screenshot shows an example of what the finished program should output:

To give you more of an idea, [have a look at the finished example](https://mdn.github.io/learning-area/javascript/introduction-to-js-1/assessment-finished/) (no peeking at the source code!)
## Steps to complete
The following sections describe what you need to do.
Basic setup:
1. Create a new file called `main.js`, in the same directory as your `index.html` file.
2. Apply the external JavaScript file to your HTML by inserting a {{htmlelement("script")}} element into your HTML referencing `main.js`. Put it just before the closing `</body>` tag.
Initial variables and functions:
1. In the raw text file, copy all of the code underneath the heading "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" and paste it into the top of the `main.js` file. This gives you three variables that store references to the "Enter custom name" text field (`customName`), the "Generate random story" button (`randomize`), and the {{htmlelement("p")}} element at the bottom of the HTML body that the story will be copied into (`story`), respectively. In addition you've got a function called `randomValueFromArray()` that takes an array, and returns one of the items stored inside the array at random.
2. Now look at the second section of the raw text file β "2. RAW TEXT STRINGS". This contains text strings that will act as input into our program. We'd like you to contain these inside variables inside `main.js`:
1. Store the first, big long, string of text inside a variable called `storyText`.
2. Store the first set of three strings inside an array called `insertX`.
3. Store the second set of three strings inside an array called `insertY`.
4. Store the third set of three strings inside an array called `insertZ`.
Placing the event handler and incomplete function:
1. Now return to the raw text file.
2. Copy the code found underneath the heading "3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" and paste it into the bottom of your `main.js` file. This:
- Adds a click event listener to the `randomize` variable so that when the button it represents is clicked, the `result()` function is run.
- Adds a partially-completed `result()` function definition to your code. For the remainder of the assessment, you'll be filling in lines inside this function to complete it and make it work properly.
Completing the `result()` function:
1. Create a new variable called `newStory`, and set its value to equal `storyText`. This is needed so we can create a new random story each time the button is pressed and the function is run. If we made changes directly to `storyText`, we'd only be able to generate a new story once.
2. Create three new variables called `xItem`, `yItem`, and `zItem`, and make them equal to the result of calling `randomValueFromArray()` on your three arrays (the result in each case will be a random item out of each array it is called on). For example you can call the function and get it to return one random string out of `insertX` by writing `randomValueFromArray(insertX)`.
3. Next we want to replace the three placeholders in the `newStory` string β `:insertx:`, `:inserty:`, and `:insertz:` β with the strings stored in `xItem`, `yItem`, and `zItem`. There are two possible string methods that will help you here β in each case, make the call to the method equal to `newStory`, so each time it is called, `newStory` is made equal to itself, but with substitutions made. So each time the button is pressed, these placeholders are each replaced with a random silly string. As a further hint, depending on the method you choose, you might need to make one of the calls twice.
4. Inside the first `if` block, add another string replacement method call to replace the name 'Bob' found in the `newStory` string with the `name` variable. In this block we are saying "If a value has been entered into the `customName` text input, replace Bob in the story with that custom name."
5. Inside the second `if` block, we are checking to see if the `uk` radio button has been selected. If so, we want to convert the weight and temperature values in the story from pounds and Fahrenheit into stones and centigrade. What you need to do is as follows:
1. Look up the formulas for converting pounds to stone, and Fahrenheit to centigrade.
2. Inside the line that defines the `weight` variable, replace 300 with a calculation that converts 300 pounds into stones. Concatenate `' stone'` onto the end of the result of the overall `Math.round()` call.
3. Inside the line that defines the `temperature` variable, replace 94 with a calculation that converts 94 Fahrenheit into centigrade. Concatenate `' centigrade'` onto the end of the result of the overall `Math.round()` call.
4. Just under the two variable definitions, add two more string replacement lines that replace '94 fahrenheit' with the contents of the `temperature` variable, and '300 pounds' with the contents of the `weight` variable.
6. Finally, in the second-to-last line of the function, make the `textContent` property of the `story` variable (which references the paragraph) equal to `newStory`.
## Hints and tips
- You don't need to edit the HTML in any way, except to apply the JavaScript to your HTML.
- If you are unsure whether the JavaScript is applied to your HTML properly, try removing everything else from the JavaScript file temporarily, adding in a simple bit of JavaScript that you know will create an obvious effect, then saving and refreshing. The following for example turns the background of the {{htmlelement("html")}} element red β so the entire browser window should go red if the JavaScript is applied properly:
```js
document.querySelector("html").style.backgroundColor = "red";
```
- [`Math.round()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) is a built-in JavaScript method that rounds the result of a calculation to the nearest whole number.
- There are three instances of strings that need to be replaced. You may repeat the `replace()` method multiple times, or you can use `replaceAll()`. Remember, Strings are immutable!
{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/first_steps | data/mdn-content/files/en-us/learn/javascript/first_steps/variables/index.md | ---
title: Storing the information you need β Variables
slug: Learn/JavaScript/First_steps/Variables
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps")}}
After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of JavaScript β Variables.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML and CSS, an
understanding of what JavaScript is.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To gain familiarity with the basics of JavaScript variables.</td>
</tr>
</tbody>
</table>
## Tools you need
Throughout this article, you'll be asked to type in lines of code to test your understanding of the content. If you are using a desktop browser, the best place to type your sample code is your browser's JavaScript console (see [What are browser developer tools](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools) for more information on how to access this tool).
## What is a variable?
A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence.
### Variable example
Let's look at a simple example:
```html
<button id="button_A">Press me</button>
<h3 id="heading_A"></h3>
```
```js
const buttonA = document.querySelector("#button_A");
const headingA = document.querySelector("#heading_A");
buttonA.onclick = () => {
const name = prompt("What is your name?");
alert(`Hello ${name}, nice to see you!`);
headingA.textContent = `Welcome ${name}`;
};
```
{{ EmbedLiveSample('Variable_example', '100%', 120) }}
In this example pressing the button runs some code. The first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that includes their name, taken from the variable value and the third line displays that name on the page.
### Without a variable
To understand why this is so useful, let's think about how we'd write this example without using a variable. It would end up looking something like this:
```html example-bad
<button id="button_B">Press me</button>
<h3 id="heading_B"></h3>
```
```js example-bad
const buttonB = document.querySelector("#button_B");
const headingB = document.querySelector("#heading_B");
buttonB.onclick = () => {
alert(`Hello ${prompt("What is your name?")}, nice to see you!`);
headingB.textContent = `Welcome ${prompt("What is your name?")}`;
};
```
{{ EmbedLiveSample('Without_a_variable', '100%', 120) }}
You may not fully understand the syntax we are using (yet!), but you should be able to get the idea. If we didn't have variables available, we'd have to ask the reader for their name every time we needed to use it!
Variables just make sense, and as you learn more about JavaScript they will start to become second nature.
One special thing about variables is that they can contain just about anything β not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.
> **Note:** We say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.

## Declaring a variable
To use a variable, you've first got to create it β more accurately, we call this declaring the variable. To do this, we type the keyword `let` followed by the name you want to call your variable:
```js
let myName;
let myAge;
```
Here we're creating two variables called `myName` and `myAge`. Try typing these lines into your web browser's console. After that, try creating a variable (or two) with your own name choices.
> **Note:** In JavaScript, all code instructions should end with a semicolon (`;`) β your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.
You can test whether these values now exist in the execution environment by typing just the variable's name, e.g.
```js
myName;
myAge;
```
They currently have no value; they are empty containers. When you enter the variable names, you should get a value of `undefined` returned. If they don't exist, you'll get an error message β try typing in
```js
scoobyDoo;
```
> **Note:** Don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all β they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there is a box, but it has no value inside it.
## Initializing a variable
Once you've declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign (`=`), followed by the value you want to give it. For example:
```js
myName = "Chris";
myAge = 37;
```
Try going back to the console now and typing in these lines. You should see the value you've assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by typing their name into the console β try these again:
```js
myName;
myAge;
```
You can declare and initialize a variable at the same time, like this:
```js
let myDog = "Rover";
```
This is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines.
## A note about var
You'll probably also see a different way to declare variables, using the `var` keyword:
```js
var myName;
var myAge;
```
Back when JavaScript was first created, this was the only way to declare variables. The design of `var` is confusing and error-prone. So `let` was created in modern versions of JavaScript, a new keyword for creating variables that works somewhat differently to `var`, fixing its issues in the process.
A couple of simple differences are explained below. We won't go into all the differences now, but you'll start to discover them as you learn more about JavaScript (if you really want to read about them now, feel free to check out our [let reference page](/en-US/docs/Web/JavaScript/Reference/Statements/let)).
For a start, if you write a multiline JavaScript program that declares and initializes a variable, you can actually declare a variable with `var` after you initialize it and it will still work. For example:
```js
myName = "Chris";
function logName() {
console.log(myName);
}
logName();
var myName;
```
> **Note:** This won't work when typing individual lines into a JavaScript console, just when running multiple lines of JavaScript in a web document.
This works because of **hoisting** β read [var hoisting](/en-US/docs/Web/JavaScript/Reference/Statements/var#hoisting) for more detail on the subject.
Hoisting no longer works with `let`. If we changed `var` to `let` in the above example, it would fail with an error. This is a good thing β declaring a variable after you initialize it results in confusing, harder to understand code.
Secondly, when you use `var`, you can declare the same variable as many times as you like, but with `let` you can't. The following would work:
```js
var myName = "Chris";
var myName = "Bob";
```
But the following would throw an error on the second line:
```js example-bad
let myName = "Chris";
let myName = "Bob";
```
You'd have to do this instead:
```js
let myName = "Chris";
myName = "Bob";
```
Again, this is a sensible language decision. There is no reason to redeclare variables β it just makes things more confusing.
For these reasons and more, we recommend that you use `let` in your code, rather than `var`. Unless you are explicitly writing support for ancient browsers, there is no longer any reason to use `var` as all modern browsers have supported `let` since 2015.
> **Note:** If you are trying this code in your browser's console, prefer to copy & paste each of the code blocks here as a whole. There's a [feature in Chrome's console](https://goo.gle/devtools-const-repl) where variable re-declarations with `let` and `const` are allowed:
>
> ```plain
> > let myName = "Chris";
> let myName = "Bob";
> // As one input: SyntaxError: Identifier 'myName' has already been declared
>
> > let myName = "Chris";
> > let myName = "Bob";
> // As two inputs: both succeed
> ```
## Updating a variable
Once a variable has been initialized with a value, you can change (or update) that value by giving it a different value. Try entering the following lines into your console:
```js
myName = "Bob";
myAge = 40;
```
### An aside on variable naming rules
You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.
- You shouldn't use other characters because they may cause errors or be hard to understand for an international audience.
- Don't use underscores at the start of variable names β this is used in certain JavaScript constructs to mean specific things, so may get confusing.
- Don't use numbers at the start of variables. This isn't allowed and causes an error.
- A safe convention to stick to is {{Glossary("camel_case", "lower camel case")}}, where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've been using this for our variable names in the article so far.
- Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.
- Variables are case sensitive β so `myage` is a different variable from `myAge`.
- One last point: you also need to avoid using JavaScript reserved words as your variable names β by this, we mean the words that make up the actual syntax of JavaScript! So, you can't use words like `var`, `function`, `let`, and `for` as variable names. Browsers recognize them as different code items, and so you'll get errors.
> **Note:** You can find a fairly complete list of reserved keywords to avoid at [Lexical grammar β keywords](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords).
Good name examples:
```plain example-good
age
myAge
init
initialColor
finalOutputValue
audio1
audio2
```
Bad name examples:
```plain example-bad
1
a
_12
myage
MYAGE
var
Document
skjfndskjfnbdskjfb
thisisareallylongvariablenameman
```
Try creating a few more variables now, with the above guidance in mind.
## Variable types
There are a few different types of data we can store in variables. In this section we'll describe these in brief, then in future articles, you'll learn about them in more detail.
### Numbers
You can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). You don't need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don't include quotes:
```js
let myAge = 17;
```
### Strings
Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks; otherwise, JavaScript tries to interpret it as another variable name.
```js
let dolphinGoodbye = "So long and thanks for all the fish";
```
### Booleans
Booleans are true/false values β they can have two values, `true` or `false`. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:
```js
let iAmAlive = true;
```
Whereas in reality it would be used more like this:
```js
let test = 6 < 3;
```
This is using the "less than" operator (`<`) to test whether 6 is less than 3. As you might expect, it returns `false`, because 6 is not less than 3! You will learn a lot more about such operators later on in the course.
### Arrays
An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:
```js
let myNameArray = ["Chris", "Bob", "Jim"];
let myNumberArray = [10, 15, 40];
```
Once these arrays are defined, you can access each value by their location within the array. Try these lines:
```js
myNameArray[0]; // should return 'Chris'
myNumberArray[2]; // should return 40
```
The square brackets specify an index value corresponding to the position of the value you want returned. You might have noticed that arrays in JavaScript are zero-indexed: the first element is at index 0.
You'll learn a lot more about arrays in [a future article](/en-US/docs/Learn/JavaScript/First_steps/Arrays).
### Objects
In programming, an object is a structure of code that models a real-life object. You can have a simple object that represents a box and contains information about its width, length, and height, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.
Try entering the following line into your console:
```js
let dog = { name: "Spot", breed: "Dalmatian" };
```
To retrieve the information stored in the object, you can use the following syntax:
```js
dog.name;
```
We won't be looking at objects any more for now β you can learn more about those in [a future module](/en-US/docs/Learn/JavaScript/Objects).
## Dynamic typing
JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (numbers, strings, arrays, etc.).
For example, if you declare a variable and give it a value enclosed in quotes, the browser treats the variable as a string:
```js
let myString = "Hello";
```
Even if the value enclosed in quotes is just digits, it is still a string β not a number β so be careful:
```js
let myNumber = "500"; // oops, this is still a string
typeof myNumber;
myNumber = 500; // much better β now this is a number
typeof myNumber;
```
Try entering the four lines above into your console one by one, and see what the results are. You'll notice that we are using a special operator called [`typeof`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof) β this returns the data type of the variable you type after it. The first time it is called, it should return `string`, as at that point the `myNumber` variable contains a string, `'500'`. Have a look and see what it returns the second time you call it.
## Constants in JavaScript
As well as variables, you can declare constants. These are like variables, except that:
- you must initialize them when you declare them
- you can't assign them a new value after you've initialized them.
For example, using `let` you can declare a variable without initializing it:
```js
let count;
```
If you try to do this using `const` you will see an error:
```js example-bad
const count;
```
Similarly, with `let` you can initialize a variable, and then assign it a new value (this is also called _reassigning_ the variable):
```js
let count = 1;
count = 2;
```
If you try to do this using `const` you will see an error:
```js example-bad
const count = 1;
count = 2;
```
Note that although a constant in JavaScript must always name the same value, you can change the content of the value that it names. This isn't a useful distinction for simple types like numbers or booleans, but consider an object:
```js
const bird = { species: "Kestrel" };
console.log(bird.species); // "Kestrel"
```
You can update, add, or remove properties of an object declared using `const`, because even though the content of the object has changed, the constant is still pointing to the same object:
```js
bird.species = "Striated Caracara";
console.log(bird.species); // "Striated Caracara"
```
## When to use const and when to use let
If you can't do as much with `const` as you can with `let`, why would you prefer to use it rather than `let`? In fact `const` is very useful. If you use `const` to name a value, it tells anyone looking at your code that this name will never be assigned to a different value. Any time they see this name, they will know what it refers to.
In this course, we adopt the following principle about when to use `let` and when to use `const`:
_Use `const` when you can, and use `let` when you have to._
This means that if you can initialize a variable when you declare it, and don't need to reassign it later, make it a constant.
## 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: variables](/en-US/docs/Learn/JavaScript/First_steps/Test_your_skills:_variables).
## Summary
By now you should know a reasonable amount about JavaScript variables and how to create them. In the next article, we'll focus on numbers in more detail, looking at how to do basic math in JavaScript.
{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Maths", "Learn/JavaScript/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript | data/mdn-content/files/en-us/learn/javascript/building_blocks/index.md | ---
title: JavaScript building blocks
slug: Learn/JavaScript/Building_blocks
page-type: learn-module
---
{{LearnSidebar}}
In this module, we continue our coverage of all JavaScript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events. You've seen this stuff already in the course, but only in passing β here we'll discuss it all explicitly.
> **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 some familiarity with the basics of [HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) and [CSS](/en-US/docs/Learn/CSS/First_steps), and you should have also worked through our previous module, [JavaScript first steps](/en-US/docs/Learn/JavaScript/First_steps).
> **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
- [Making decisions in your code β conditionals](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals)
- : In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is night. In this article we'll explore how conditional structures work in JavaScript.
- [Looping code](/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code)
- : Sometimes you need a task done more than once in a row. For example, looking through a list of names. In programming, loops perform this job very well. Here we will look at loop structures in JavaScript.
- [Functions β reusable blocks of code](/en-US/docs/Learn/JavaScript/Building_blocks/Functions)
- : Another essential concept in coding is **functions. Functions** allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command β rather than having to type out the same code multiple times. In this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define functions, scope, and parameters.
- [Build your own function](/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function)
- : With most of the essential theory dealt with previously, this article provides a practical experience. Here you'll get some practice with building up your own custom function. Along the way, we'll also explain some further useful details of dealing with functions.
- [Function return values](/en-US/docs/Learn/JavaScript/Building_blocks/Return_values)
- : The last essential concept you must know about a function is return values. Some functions don't return a significant value after completion, but others do. It's important to understand what their values are, how to make use of them in your code, and how to make your own custom functions return useful values.
- [Introduction to events](/en-US/docs/Learn/JavaScript/Building_blocks/Events)
- : Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. For example if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box. In this final article we will discuss some important concepts surrounding events, and look at how they work in browsers.
## Assessments
The following assessment will test your understanding of the JavaScript basics covered in the guides above.
- [Image gallery](/en-US/docs/Learn/JavaScript/Building_blocks/Image_gallery)
- : Now that we've looked at the fundamental building blocks of JavaScript, we'll test your knowledge of loops, functions, conditionals and events by building a fairly common item you'll see on a lot of websites β a JavaScript-powered image gallery.
## See also
- [Learn JavaScript](https://learnjavascript.online/)
- : An excellent resource for aspiring web developers β Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment.
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/test_your_skills_colon__loops/index.md | ---
title: "Test your skills: Loops"
slug: Learn/JavaScript/Building_blocks/Test_your_skills:_Loops
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Looping code](/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code) article.
> **Note:** You can try solutions by downloading the code and putting it 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).
## DOM manipulation: considered useful
Some of the questions below require you to write some [DOM](/en-US/docs/Glossary/DOM) manipulation code to complete them β such as creating new HTML elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page β all via JavaScript.
We haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what DOM APIs you need to successfully answer the questions. A good starting place is our [Manipulating documents](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents) tutorial.
## Loops 1
In our first looping task we want you to start by creating a simple loop that goes through all the items in the provided `myArray` and prints them out on the screen inside list items (i.e., [`<li>`](/en-US/docs/Web/HTML/Element/li) elements), which are appended to the provided `list`.
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/loops/loops1-download.html) to work in your own editor or in an online editor.
## Loops 2
In this next task, we want you to write a simple program that, given a name, searches an array of [objects](/en-US/docs/Glossary/Object) containing names and phone numbers (`phonebook`) and, if it finds the name, outputs the name and phone number into the paragraph (`para`) and then exits the loop before it has run its course.
If you haven't read about objects yet, don't worry! For now, all you need to know is how to access a member-value pair. You can read up on objects in the [JavaScript object basics](/en-US/docs/Learn/JavaScript/Objects/Basics) tutorial.
You are given three variables to begin with:
- `name` β contains a name to search for
- `para` β contains a reference to a paragraph, which will be used to report the results
- `phonebook` - contains the phonebook entries to search.
You should use a type of loop that you've not used in the previous task.
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/loops/loops2-download.html) to work in your own editor or in an online editor.
## Loops 3
In this final task, you are provided with the following:
- `i` β starts off with a value of 500; intended to be used as an iterator.
- `para` β contains a reference to a paragraph, which will be used to report the results.
- `isPrime()` β a function that, when passed a number, returns `true` if the number is a prime number, and `false` if not.
You need to use a loop to go through the numbers 2 to 500 backwards (1 is not counted as a prime number), and run the provided `isPrime()` function on them. For each number that isn't a prime number, continue on to the next loop iteration. For each one that is a prime number, add it to the paragraph's `textContent` along with some kind of separator.
You should use a type of loop that you've not used in the previous two tasks.
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/loops/loops3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/events/index.md | ---
title: Introduction to events
slug: Learn/JavaScript/Building_blocks/Events
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}
Events are things that happen in the system you are programming, which the system tells you about so your code can react to them.
For example, if the user clicks a button on a webpage, you might want to react to that action by displaying an information box.
In this article, we discuss some important concepts surrounding events, and look at how they work in browsers.
This won't be an exhaustive study; just what you need to know at this stage.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML, CSS, and
<a href="/en-US/docs/Learn/JavaScript/First_steps"
>JavaScript first steps</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the fundamental theory of events, how they work in
browsers, and how events may differ in different programming
environments.
</td>
</tr>
</tbody>
</table>
## What is an event?
Events are things that happen in the system you are programming β the system produces (or "fires") a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken (that is, some code running) when the event occurs.
Events are fired inside the browser window, and tend to be attached to a specific item that resides in it. This might be a single element, a set of elements, the HTML document loaded in the current tab, or the entire browser window.
There are many different types of events that can occur.
For example:
- The user selects, clicks, or hovers the cursor over a certain element.
- The user chooses a key on the keyboard.
- The user resizes or closes the browser window.
- A web page finishes loading.
- A form is submitted.
- A video is played, paused, or ends.
- An error occurs.
You can gather from this (and from glancing at the MDN [event reference](/en-US/docs/Web/Events)) that there are **a lot** of events that can be fired.
To react to an event, you attach an **event handler** to it. This is a block of code (usually a JavaScript function that you as a programmer create) that runs when the event fires.
When such a block of code is defined to run in response to an event, we say we are **registering an event handler**.
Note: Event handlers are sometimes called **event listeners** β they are pretty much interchangeable for our purposes, although strictly speaking, they work together.
The listener listens out for the event happening, and the handler is the code that is run in response to it happening.
> **Note:** Web events are not part of the core JavaScript language β they are defined as part of the APIs built into the browser.
### An example: handling a click event
In the following example, we have a single {{htmlelement("button")}} in the page:
```html
<button>Change color</button>
```
```css hidden
button {
margin: 10px;
}
```
Then we have some JavaScript. We'll look at this in more detail in the next section, but for now we can just say: it adds an event handler to the button's `"click"` event, and the handler reacts to the event by setting the page background to a random color:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() * (number + 1));
}
btn.addEventListener("click", () => {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
});
```
The example output is as follows. Try clicking the button:
{{ EmbedLiveSample('An example: handling a click event', '100%', 200, "", "") }}
## Using addEventListener()
As we saw in the last example, objects that can fire events have an {{domxref("EventTarget/addEventListener", "addEventListener()")}} method, and this is the recommended mechanism for adding event handlers.
Let's take a closer look at the code from the last example:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() * (number + 1));
}
btn.addEventListener("click", () => {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
});
```
The HTML {{HTMLElement("button")}} element will fire an event when the user clicks the button. So it defines an `addEventListener()` function, which we are calling here. We're passing in two parameters:
- the string `"click"`, to indicate that we want to listen to the click event. Buttons can fire lots of other events, such as [`"mouseover"`](/en-US/docs/Web/API/Element/mouseover_event) when the user moves their mouse over the button, or [`"keydown"`](/en-US/docs/Web/API/Element/keydown_event) when the user presses a key and the button is focused.
- a function to call when the event happens. In our case, the function generates a random RGB color and sets the [`background-color`](/en-US/docs/Web/CSS/background-color) of the page [`<body>`](/en-US/docs/Web/HTML/Element/body) to that color.
It is fine to make the handler function a separate named function, like this:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() * (number + 1));
}
function changeBackground() {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
}
btn.addEventListener("click", changeBackground);
```
### Listening for other events
There are many different events that can be fired by a button element. Let's experiment.
First, make a local copy of [random-color-addeventlistener.html](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/events/random-color-addeventlistener.html), and open it in your browser.
It's just a copy of the simple random color example we've played with already. Now try changing `click` to the following different values in turn, and observing the results in the example:
- [`focus`](/en-US/docs/Web/API/Element/focus_event) and [`blur`](/en-US/docs/Web/API/Element/blur_event) β The color changes when the button is focused and unfocused; try pressing the tab to focus on the button and press the tab again to focus away from the button.
These are often used to display information about filling in form fields when they are focused, or to display an error message if a form field is filled with an incorrect value.
- [`dblclick`](/en-US/docs/Web/API/Element/dblclick_event) β The color changes only when the button is double-clicked.
- [`mouseover`](/en-US/docs/Web/API/Element/mouseover_event) and [`mouseout`](/en-US/docs/Web/API/Element/mouseout_event) β The color changes when the mouse pointer hovers over the button, or when the pointer moves off the button, respectively.
Some events, such as `click`, are available on nearly any element. Others are more specific and only useful in certain situations: for example, the [`play`](/en-US/docs/Web/API/HTMLMediaElement/play_event) event is only available on some elements, such as {{htmlelement("video")}}.
### Removing listeners
If you've added an event handler using `addEventListener()`, you can remove it again using the [`removeEventListener()`](/en-US/docs/Web/API/EventTarget/removeEventListener) method. For example, this would remove the `changeBackground()` event handler:
```js
btn.removeEventListener("click", changeBackground);
```
Event handlers can also be removed by passing an {{domxref("AbortSignal")}} to {{domxref("EventTarget/addEventListener()", "addEventListener()")}} and then later calling {{domxref("AbortController/abort()", "abort()")}} on the controller owning the `AbortSignal`.
For example, to add an event handler that we can remove with an `AbortSignal`:
```js-nolint
const controller = new AbortController();
btn.addEventListener("click",
() => {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
},
{ signal: controller.signal } // pass an AbortSignal to this handler
);
```
Then the event handler created by the code above can be removed like this:
```js
controller.abort(); // removes any/all event handlers associated with this controller
```
For simple, small programs, cleaning up old, unused event handlers isn't necessary, but for larger, more complex programs, it can improve efficiency.
Also, the ability to remove event handlers allows you to have the same button performing different actions in different circumstances: all you have to do is add or remove handlers.
### Adding multiple listeners for a single event
By making more than one call to {{domxref("EventTarget/addEventListener()", "addEventListener()")}}, providing different handlers, you can have multiple handlers for a single event:
```js
myElement.addEventListener("click", functionA);
myElement.addEventListener("click", functionB);
```
Both functions would now run when the element is clicked.
### Learn more
There are other powerful features and options available with `addEventListener()`.
These are a little out of scope for this article, but if you want to read them, visit the [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) and [`removeEventListener()`](/en-US/docs/Web/API/EventTarget/removeEventListener) reference pages.
## Other event listener mechanisms
We recommend that you use `addEventListener()` to register event handlers. It's the most powerful method and scales best with more complex programs. However, there are two other ways of registering event handlers that you might see: _event handler properties_ and _inline event handlers_.
### Event handler properties
Objects (such as buttons) that can fire events also usually have properties whose name is `on` followed by the name of the event. For example, elements have a property `onclick`.
This is called an _event handler property_. To listen for the event, you can assign the handler function to the property.
For example, we could rewrite the random-color example like this:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() * (number + 1));
}
btn.onclick = () => {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
};
```
You can also set the handler property to a named function:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() * (number + 1));
}
function bgChange() {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
}
btn.onclick = bgChange;
```
With event handler properties, you can't add more than one handler for a single event. For example, you can call `addEventListener('click', handler)` on an element multiple times, with different functions specified in the second argument:
```js
element.addEventListener("click", function1);
element.addEventListener("click", function2);
```
This is impossible with event handler properties because any subsequent attempts to set the property will overwrite earlier ones:
```js
element.onclick = function1;
element.onclick = function2;
```
### Inline event handlers β don't use these
You might also see a pattern like this in your code:
```html
<button onclick="bgChange()">Press me</button>
```
```js
function bgChange() {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
document.body.style.backgroundColor = rndCol;
}
```
The earliest method of registering event handlers found on the Web involved [_event handler HTML attributes_](/en-US/docs/Web/HTML/Attributes#event_handler_attributes) (or _inline event handlers_) like the one shown above β the attribute value is literally the JavaScript code you want to run when the event occurs.
The above example invokes a function defined inside a {{htmlelement("script")}} element on the same page, but you could also insert JavaScript directly inside the attribute, for example:
```html
<button onclick="alert('Hello, this is my old-fashioned event handler!');">
Press me
</button>
```
You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these β they are considered bad practice.
It might seem easy to use an event handler attribute if you are doing something really quick, but they quickly become unmanageable and inefficient.
For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to read. Keeping your JavaScript separate is a good practice, and if it is in a separate file you can apply it to multiple HTML documents.
Even in a single file, inline event handlers are not a good idea.
One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would quickly turn into a maintenance nightmare.
With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:
```js
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", bgChange);
}
```
Finally, many common server configurations will disallow inline JavaScript, as a security measure.
**You should never use the HTML event handler attributes** β those are outdated, and using them is bad practice.
## Event objects
Sometimes, inside an event handler function, you'll see a parameter specified with a name such as `event`, `evt`, or `e`.
This is called the **event object**, and it is automatically passed to event handlers to provide extra features and information.
For example, let's rewrite our random color example again slightly:
```js
const btn = document.querySelector("button");
function random(number) {
return Math.floor(Math.random() * (number + 1));
}
function bgChange(e) {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
e.target.style.backgroundColor = rndCol;
console.log(e);
}
btn.addEventListener("click", bgChange);
```
> **Note:** You can find the [full source code](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/events/random-color-eventobject.html) for this example on GitHub (also [see it running live](https://mdn.github.io/learning-area/javascript/building-blocks/events/random-color-eventobject.html)).
Here you can see we are including an event object, **e**, in the function, and in the function setting a background color style on `e.target` β which is the button itself.
The `target` property of the event object is always a reference to the element the event occurred upon.
So, in this example, we are setting a random background color on the button, not the page.
> **Note:** See the [Event delegation](#event_delegation) section below for an example where we use `event.target`.
> **Note:** You can use any name you like for the event object β you just need to choose a name that you can then use to reference it inside the event handler function.
> `e`/`evt`/`event` is most commonly used by developers because they are short and easy to remember.
> It's always good to be consistent β with yourself, and with others if possible.
### Extra properties of event objects
Most event objects have a standard set of properties and methods available on the event object; see the {{domxref("Event")}} object reference for a full list.
Some event objects add extra properties that are relevant to that particular type of event. For example, the {{domxref("Element/keydown_event", "keydown")}} event fires when the user presses a key. Its event object is a {{domxref("KeyboardEvent")}}, which is a specialized `Event` object with a `key` property that tells you which key was pressed:
```html
<input id="textBox" type="text" />
<div id="output"></div>
```
```js
const textBox = document.querySelector("#textBox");
const output = document.querySelector("#output");
textBox.addEventListener("keydown", (event) => {
output.textContent = `You pressed "${event.key}".`;
});
```
```css hidden
div {
margin: 0.5rem 0;
}
```
Try typing into the text box and see the output:
{{EmbedLiveSample("Extra_properties_of_event_objects", 100, 100)}}
## Preventing default behavior
Sometimes, you'll come across a situation where you want to prevent an event from doing what it does by default.
The most common example is that of a web form, for example, a custom registration form.
When you fill in the details and click the submit button, the natural behavior is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified).
The trouble comes when the user has not submitted the data correctly β as a developer, you want to prevent the submission to the server and give an error message saying what's wrong and what needs to be done to put things right.
Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks.
Let's look at a simple example.
First, a simple HTML form that requires you to enter your first and last name:
```html
<form>
<div>
<label for="fname">First name: </label>
<input id="fname" type="text" />
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" type="text" />
</div>
<div>
<input id="submit" type="submit" />
</div>
</form>
<p></p>
```
```css hidden
div {
margin-bottom: 10px;
}
```
Now some JavaScript β here we implement a very simple check inside a handler for the [`submit`](/en-US/docs/Web/API/HTMLFormElement/submit_event) event (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty.
If they are, we call the [`preventDefault()`](/en-US/docs/Web/API/Event/preventDefault) function on the event object β which stops the form submission β and then display an error message in the paragraph below our form to tell the user what's wrong:
```js
const form = document.querySelector("form");
const fname = document.getElementById("fname");
const lname = document.getElementById("lname");
const para = document.querySelector("p");
form.addEventListener("submit", (e) => {
if (fname.value === "" || lname.value === "") {
e.preventDefault();
para.textContent = "You need to fill in both names!";
}
});
```
Obviously, this is pretty weak form validation β it wouldn't stop the user from validating the form with spaces or numbers entered into the fields, for example β but it is OK for example purposes.
The output is as follows:
{{ EmbedLiveSample('Preventing_default_behavior', '100%', 180, "", "") }}
> **Note:** For the full source code, see [preventdefault-validation.html](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/events/preventdefault-validation.html) (also see it [running live](https://mdn.github.io/learning-area/javascript/building-blocks/events/preventdefault-validation.html) here).
## Event bubbling
Event bubbling describes how the browser handles events targeted at nested elements.
### Setting a listener on a parent element
Consider a web page like this:
```html
<div id="container">
<button>Click me!</button>
</div>
<pre id="output"></pre>
```
Here the button is inside another element, a {{HTMLElement("div")}} element. We say that the `<div>` element here is the **parent** of the element it contains. What happens if we add a click event handler to the parent, then click the button?
```js
const output = document.querySelector("#output");
function handleClick(e) {
output.textContent += `You clicked on a ${e.currentTarget.tagName} element\n`;
}
const container = document.querySelector("#container");
container.addEventListener("click", handleClick);
```
{{ EmbedLiveSample('Setting a listener on a parent element', '100%', 200, "", "") }}
You'll see that the parent fires a click event when the user clicks the button:
```plain
You clicked on a DIV element
```
This makes sense: the button is inside the `<div>`, so when you click the button you're also implicitly clicking the element it is inside.
### Bubbling example
What happens if we add event listeners to the button _and_ the parent?
```html
<body>
<div id="container">
<button>Click me!</button>
</div>
<pre id="output"></pre>
</body>
```
Let's try adding click event handlers to the button, its parent (the `<div>`), and the {{HTMLElement("body")}} element that contains both of them:
```js
const output = document.querySelector("#output");
function handleClick(e) {
output.textContent += `You clicked on a ${e.currentTarget.tagName} element\n`;
}
const container = document.querySelector("#container");
const button = document.querySelector("button");
document.body.addEventListener("click", handleClick);
container.addEventListener("click", handleClick);
button.addEventListener("click", handleClick);
```
{{ EmbedLiveSample('Bubbling example', '100%', 200, "", "") }}
You'll see that all three elements fire a click event when the user clicks the button:
```plain
You clicked on a BUTTON element
You clicked on a DIV element
You clicked on a BODY element
```
In this case:
- the click on the button fires first
- followed by the click on its parent (the `<div>` element)
- followed by the `<div>` element's parent (the `<body>` element).
We describe this by saying that the event **bubbles up** from the innermost element that was clicked.
This behavior can be useful and can also cause unexpected problems. In the next sections, we'll see a problem that it causes, and find the solution.
### Video player example
In this example our page contains a video, which is hidden initially, and a button labeled "Display video". We want the following interaction:
- When the user clicks the "Display video" button, show the box containing the video, but don't start playing the video yet.
- When the user clicks on the video, start playing the video.
- When the user clicks anywhere in the box outside the video, hide the box.
The HTML looks like this:
```html
<button>Display video</button>
<div class="hidden">
<video>
<source
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm"
type="video/webm" />
<p>
Your browser doesn't support HTML video. Here is a
<a href="rabbit320.mp4">link to the video</a> instead.
</p>
</video>
</div>
```
It includes:
- a `<button>` element
- a `<div>` element which initially has a `class="hidden"` attribute
- a `<video>` element nested inside the `<div>` element.
We're using CSS to hide elements with the `"hidden"` class set.
```css hidden
div {
width: 100%;
height: 100%;
background-color: #eee;
}
.hidden {
display: none;
}
div video {
padding: 40px;
display: block;
width: 400px;
margin: 40px auto;
}
```
The JavaScript looks like this:
```js
const btn = document.querySelector("button");
const box = document.querySelector("div");
const video = document.querySelector("video");
btn.addEventListener("click", () => box.classList.remove("hidden"));
video.addEventListener("click", () => video.play());
box.addEventListener("click", () => box.classList.add("hidden"));
```
This adds three `'click'` event listeners:
- one on the `<button>`, which shows the `<div>` that contains the `<video>`
- one on the `<video>`, which starts playing the video
- one on the `<div>`, which hides the video
Let's see how this works:
{{ EmbedLiveSample('Video_player_example', '100%', 500) }}
You should see that when you click the button, the box and the video it contains are shown. But then when you click the video, the video starts to play, but the box is hidden again!
The video is inside the `<div>` β it is part of it β so clicking the video runs _both_ the event handlers, causing this behavior.
### Fixing the problem with stopPropagation()
As we saw in the last section, event bubbling can sometimes create problems, but there is a way to prevent it.
The [`Event`](/en-US/docs/Web/API/Event) object has a function available on it called [`stopPropagation()`](/en-US/docs/Web/API/Event/stopPropagation) which, when called inside an event handler, prevents the event from bubbling up to any other elements.
We can fix our current problem by changing the JavaScript to this:
```js
const btn = document.querySelector("button");
const box = document.querySelector("div");
const video = document.querySelector("video");
btn.addEventListener("click", () => box.classList.remove("hidden"));
video.addEventListener("click", (event) => {
event.stopPropagation();
video.play();
});
box.addEventListener("click", () => box.classList.add("hidden"));
```
All we're doing here is calling `stopPropagation()` on the event object in the handler for the `<video>` element's `'click'` event. This will stop that event from bubbling up to the box. Now try clicking the button and then the video:
{{EmbedLiveSample("Fixing the problem with stopPropagation()", '100%', 500)}}
```html hidden
<button>Display video</button>
<div class="hidden">
<video>
<source
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm"
type="video/webm" />
<p>
Your browser doesn't support HTML video. Here is a
<a href="rabbit320.mp4">link to the video</a> instead.
</p>
</video>
</div>
```
```css hidden
div {
width: 100%;
height: 100%;
background-color: #eee;
}
.hidden {
display: none;
}
div video {
padding: 40px;
display: block;
width: 400px;
margin: 40px auto;
}
```
### Event capture
An alternative form of event propagation is _event capture_. This is like event bubbling but the order is reversed: so instead of the event firing first on the innermost element targeted, and then on successively less nested elements, the event fires first on the _least nested_ element, and then on successively more nested elements, until the target is reached.
Event capture is disabled by default. To enable it you have to pass the `capture` option in `addEventListener()`.
This example is just like the [bubbling example](#bubbling_example) we saw earlier, except that we have used the `capture` option:
```html
<body>
<div id="container">
<button>Click me!</button>
</div>
<pre id="output"></pre>
</body>
```
```js
const output = document.querySelector("#output");
function handleClick(e) {
output.textContent += `You clicked on a ${e.currentTarget.tagName} element\n`;
}
const container = document.querySelector("#container");
const button = document.querySelector("button");
document.body.addEventListener("click", handleClick, { capture: true });
container.addEventListener("click", handleClick, { capture: true });
button.addEventListener("click", handleClick);
```
{{ EmbedLiveSample('Event capture', '100%', 200, "", "") }}
In this case, the order of messages is reversed: the `<body>` event handler fires first, followed by the `<div>` event handler, followed by the `<button>` event handler:
```plain
You clicked on a BODY element
You clicked on a DIV element
You clicked on a BUTTON element
```
Why bother with both capturing and bubbling? In the bad old days, when browsers were much less cross-compatible than now, Netscape only used event capturing, and Internet Explorer used only event bubbling. When the W3C decided to try to standardize the behavior and reach a consensus, they ended up with this system that included both, which is what modern browsers implement.
By default almost all event handlers are registered in the bubbling phase, and this makes more sense most of the time.
## Event delegation
In the last section, we looked at a problem caused by event bubbling and how to fix it. Event bubbling isn't just annoying, though: it can be very useful. In particular, it enables **event delegation**. In this practice, when we want some code to run when the user interacts with any one of a large number of child elements, we set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually.
Let's go back to our first example, where we set the background color of the whole page when the user clicked a button. Suppose that instead, the page is divided into 16 tiles, and we want to set each tile to a random color when the user clicks that tile.
Here's the HTML:
```html
<div id="container">
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
</div>
```
We have a little CSS, to set the size and position of the tiles:
```css
.tile {
height: 100px;
width: 25%;
float: left;
}
```
Now in JavaScript, we could add a click event handler for every tile. But a much simpler and more efficient option is to set the click event handler on the parent, and rely on event bubbling to ensure that the handler is executed when the user clicks on a tile:
```js
function random(number) {
return Math.floor(Math.random() * number);
}
function bgChange() {
const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;
return rndCol;
}
const container = document.querySelector("#container");
container.addEventListener("click", (event) => {
event.target.style.backgroundColor = bgChange();
});
```
The output is as follows (try clicking around on it):
{{ EmbedLiveSample('Event delegation', '100%', 430, "", "") }}
> **Note:** In this example, we're using `event.target` to get the element that was the target of the event (that is, the innermost element). If we wanted to access the element that handled this event (in this case the container) we could use `event.currentTarget`.
> **Note:** See [useful-eventtarget.html](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/events/useful-eventtarget.html) for the full source code; also see it [running live](https://mdn.github.io/learning-area/javascript/building-blocks/events/useful-eventtarget.html) here.
## It's not just web pages
Events are not unique to JavaScript β most programming languages have some kind of event model, and the way the model works often differs from JavaScript's way.
In fact, the event model in JavaScript for web pages differs from the event model for JavaScript as it is used in other environments.
For example, [Node.js](/en-US/docs/Learn/Server-side/Express_Nodejs) is a very popular JavaScript runtime that enables developers to use JavaScript to build network and server-side applications.
The [Node.js event model](https://nodejs.org/api/events.html) relies on listeners to listen for events and emitters to emit events periodically β it doesn't sound that different, but the code is quite different, making use of functions like `on()` to register an event listener, and `once()` to register an event listener that unregisters after it has run once.
The [HTTP connect event docs](https://nodejs.org/api/http.html#event-connect) provide a good example.
You can also use JavaScript to build cross-browser add-ons β browser functionality enhancements β using a technology called [WebExtensions](/en-US/docs/Mozilla/Add-ons/WebExtensions).
The event model is similar to the web events model, but a bit different β event listeners' properties are written in {{Glossary("camel_case", "camel case")}} (such as `onMessage` rather than `onmessage`), and need to be combined with the `addListener` function.
See the [`runtime.onMessage`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage#examples) page for an example.
You don't need to understand anything about other such environments at this stage in your learning; we just wanted to make it clear that events can differ in different programming environments.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? To verify you've retained this information before you move on β see [Test your skills: Events](/en-US/docs/Learn/JavaScript/Building_blocks/Test_your_skills:_Events).
## Conclusion
You should now know all you need to know about web events at this early stage.
As mentioned, events are not really part of the core JavaScript β they are defined in browser Web APIs.
Also, it is important to understand that the different contexts in which JavaScript is used have different event models β from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript).
We are not expecting you to understand all of these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development.
> **Note:** If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## See also
- [domevents.dev](https://domevents.dev/) β a very useful interactive playground app that enables learning about the behavior of the DOM Event system through exploration.
- [Event reference](/en-US/docs/Web/Events)
- [Event order](https://www.quirksmode.org/js/events_order.html) (discussion of capturing and bubbling) β an excellently detailed piece by Peter-Paul Koch.
- [Event accessing](https://www.quirksmode.org/js/events_access.html) (discussion of the event object) β another excellently detailed piece by Peter-Paul Koch.
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/image_gallery/index.md | ---
title: Image gallery
slug: Learn/JavaScript/Building_blocks/Image_gallery
page-type: learn-module-assessment
---
{{LearnSidebar}}{{PreviousMenu("Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}
Now that we've looked at the fundamental building blocks of JavaScript, we'll test your knowledge of loops, functions, conditionals and events by getting you to build a fairly common item you'll see on a lot of websites β a JavaScript-powered image gallery.
<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 JavaScript loops, functions, conditionals, and
events.
</td>
</tr>
</tbody>
</table>
## Starting point
To get this assessment started, you should go and [grab the ZIP](https://raw.githubusercontent.com/mdn/learning-area/main/javascript/building-blocks/gallery/gallery-start.zip) file for the example, unzip it somewhere on your computer, and do the exercise locally to begin with.
Alternatively, you could use an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
> **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 HTML, CSS and image assets and a few lines of JavaScript code; you need to write the necessary JavaScript to turn this into a working program. The HTML body looks like this:
```html
<h1>Image gallery example</h1>
<div class="full-img">
<img
class="displayed-img"
src="images/pic1.jpg"
alt="Closeup of a blue human eye" />
<div class="overlay"></div>
<button class="dark">Darken</button>
</div>
<div class="thumb-bar"></div>
```
The example looks like this:

The most interesting parts of the example's CSS file:
- It absolutely positions the three elements inside the `full-img <div>` β the `<img>` in which the full-sized image is displayed, an empty `<div>` that is sized to be the same size as the `<img>` and put right over the top of it (this is used to apply a darkening effect to the image via a semi-transparent background color), and a `<button>` that is used to control the darkening effect.
- It sets the width of any images inside the `thumb-bar <div>` (so-called "thumbnail" images) to 20%, and floats them to the left so they sit next to one another on a line.
Your JavaScript needs to:
- Declare a `const` array listing the filenames of each image, such as `'pic1.jpg'`.
- Declare a `const` object listing the alternative text for each image.
- Loop through the array of filenames, and for each one, insert an `<img>` element inside the `thumb-bar <div>` that embeds that image in the page along with its alternative text.
- Add a click event listener to each `<img>` inside the `thumb-bar <div>` so that, when they are clicked, the corresponding image and alternative text are displayed in the `displayed-img <img>` element.
- Add a click event listener to the `<button>` so that when it is clicked, a darken effect is applied to the full-size image. When it is clicked again, the darken effect is removed again.
To give you more of an idea, have a look at the [finished example](https://mdn.github.io/learning-area/javascript/building-blocks/gallery/) (no peeking at the source code!)
## Steps to complete
The following sections describe what you need to do.
## Declare an array of image filenames
You need to create an array listing the filenames of all the images to include in the gallery. The array should be declared as a constant.
### Looping through the images
We've already provided you with lines that store a reference to the `thumb-bar <div>` inside a constant called `thumbBar`, create a new `<img>` element, set its `src` and `alt` attributes to a placeholder value `xxx`, and append this new `<img>` element inside `thumbBar`.
You need to:
1. Put the section of code below the "Looping through images" comment inside a loop that loops through all the filenames in the array.
2. In each loop iteration, replace the `xxx` placeholder values with a string that will equal the path to the image and alt attributes in each case. Set the value of the `src` and `alt` attributes to these values in each case. Remember that the image is inside the images directory, and its name is `pic1.jpg`, `pic2.jpg`, etc.
### Adding a click event listener to each thumbnail image
In each loop iteration, you need to add a click event listener to the current `newImage` β this listener should find the value of the `src` attribute of the current image. Set the `src` attribute value of the `displayed-img <img>` to the `src` value passed in as a parameter. Then do the same for the `alt` attribute.
Alternatively, you can add one event listener to the thumb bar.
### Writing a handler that runs the darken/lighten button
That just leaves our darken/lighten `<button>` β we've already provided a line that stores a reference to the `<button>` in a constant called `btn`. You need to add a click event listener that:
1. Checks the current class name set on the `<button>` β you can again achieve this by using `getAttribute()`.
2. If the class name is `"dark"`, changes the `<button>` class to `"light"` (using [`setAttribute()`](/en-US/docs/Web/API/Element/setAttribute)), its text content to "Lighten", and the {{cssxref("background-color")}} of the overlay `<div>` to `"rgb(0 0 0 / 50%)"`.
3. If the class name is not `"dark"`, changes the `<button>` class to `"dark"`, its text content back to "Darken", and the {{cssxref("background-color")}} of the overlay `<div>` to `"rgb(0 0 0 / 0%)"`.
The following lines provide a basis for achieving the changes stipulated in points 2 and 3 above.
```js
btn.setAttribute("class", xxx);
btn.textContent = xxx;
overlay.style.backgroundColor = xxx;
```
## Hints and tips
- You don't need to edit the HTML or CSS in any way.
{{PreviousMenu("Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/test_your_skills_colon__events/index.md | ---
title: "Test your skills: Events"
slug: Learn/JavaScript/Building_blocks/Test_your_skills:_Events
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Introduction to events](/en-US/docs/Learn/JavaScript/Building_blocks/Events) article.
> **Note:** You can try solutions by downloading the code and putting it in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
> If there is an error, it will be logged in the results panel on the page or into the browser's JavaScript console to help you.
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## DOM manipulation: considered useful
Some of the questions below require you to write some [DOM](/en-US/docs/Glossary/DOM) manipulation code to complete them β such as creating new HTML elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page β all via JavaScript.
We haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what DOM APIs you need to successfully answer the questions. A good starting place is our [Manipulating documents](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents) tutorial.
## Events 1
In our first events-related task, you need to create a simple event handler that causes the text inside the button (`btn`) to change when it is clicked on, and change back when it is clicked again.
The HTML should not be changed; just the JavaScript.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/building-blocks/tasks/events/events1.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/events/events1-download.html) to work in your own editor or in an online editor.
## Events 2
Now we'll look at keyboard events. To pass this assessment you need to build an event handler that moves the circle around the provided canvas when the WASD keys are pressed on the keyboard. The circle is drawn with the function `drawCircle()`, which takes the following parameters as inputs:
- `x` β the x coordinate of the circle.
- `y` β the y coordinate of the circle.
- `size` β the radius of the circle.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/building-blocks/tasks/events/events2.html", '100%', 650)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/events/events2-download.html) to work in your own editor or in an online editor.
## Events 3
In the next events-related task, you need to set an event listener on the `<button>`s' parent element (`<div class="button-bar"> β¦ </div>`), which when invoked by clicking any of the buttons will set the background of the `button-bar` to the color contained in the button's `data-color` attribute.
We want you to solve this without looping through all the buttons and giving each one their own event listener.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/building-blocks/tasks/events/events3.html", '100%', 600)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/events/events3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/test_your_skills_colon__conditionals/index.md | ---
title: "Test your skills: Conditionals"
slug: Learn/JavaScript/Building_blocks/Test_your_skills:_Conditionals
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Making decisions in your code β conditionals](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals) article.
> **Note:** You can try solutions by downloading the code and putting it in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
> If there is an error, it will be logged in the results panel on the page or into the browser's JavaScript console to help you.
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## Conditionals 1
In this task you are provided with two variables:
- `season` β contains a string that says what the current season is.
- `response` β begins uninitialized, but is later used to store a response that will be printed to the output panel.
We want you to create a conditional that checks whether `season` contains the string "summer", and if so assigns a string to `response` that gives the user an appropriate message about the season. If not, it should assign a generic string to `response` that tells the user we don't know what season it is.
To finish off, you should then add another test that checks whether `season` contains the string "winter", and again assigns an appropriate string to `response`.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/building-blocks/tasks/conditionals/conditionals1.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/conditionals/conditionals1-download.html) to work in your own editor or in an online editor.
## Conditionals 2
For this task you are given three variables:
- `machineActive` β contains an indicator of whether the answer machine is switched on or not (`true`/`false`)
- `score` β Contains your score in an imaginary game. This score is fed into the answer machine, which provides a response to indicate how well you did.
- `response` β begins uninitialized, but is later used to store a response that will be printed to the output panel.
You need to create an `if...else` structure that checks whether the machine is switched on and puts a message into the `response` variable if it isn't, telling the user to switch the machine on.
Inside the first `if...else`, you need to nest another `if...else` that puts appropriate messages into the `response` variable depending on what the value of score is β if the machine is turned on. The different conditional tests (and resulting responses) are as follows:
- Score of less than 0 or more than 100 β "This is not possible, an error has occurred."
- Score of 0 to 19 β "That was a terrible score β total fail!"
- Score of 20 to 39 β "You know some things, but it\\'s a pretty bad score. Needs improvement."
- Score of 40 to 69 β "You did a passable job, not bad!"
- Score of 70 to 89 β "That\\'s a great score, you really know your stuff."
- Score of 90 to 100 β "What an amazing score! Did you cheat? Are you for real?"
Try updating the live code below to recreate the finished example. After you've entered your code, try changing `machineActive` to `true`, to see if it works.
{{EmbedGHLiveSample("learning-area/javascript/building-blocks/tasks/conditionals/conditionals2.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/conditionals/conditionals2-download.html) to work in your own editor or in an online editor.
## Conditionals 3
For the final task you are given four variables:
- `machineActive` β contains an indicator of whether the login machine is switched on or not (`true`/`false`).
- `pwd` β Contains the user's login password.
- `machineResult` β begins uninitialized, but is later used to store a response that will be printed to the output panel, letting the user know whether the machine is switched on.
- `pwdResult` β begins uninitialized, but is later used to store a response that will be printed to the output panel, letting the user know whether their login attempt was successful.
We'd like you to create an `if...else` structure that checks whether the machine is switched on and puts a message into the `machineResult` variable telling the user whether it is on or off.
If the machine is on, we also want a second conditional to run that checks whether the `pwd` is equal to `cheese`. If so, it should assign a string to `pwdResult` telling the user they logged in successfully. If not, it should assign a different string to `pwdResult` telling the user their login attempt was not successful. We'd like you to do this in a single line, using something that isn't an `if...else` structure.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/building-blocks/tasks/conditionals/conditionals3.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/conditionals/conditionals3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/conditionals/index.md | ---
title: Making decisions in your code β conditionals
slug: Learn/JavaScript/Building_blocks/conditionals
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/JavaScript/Building_blocks/Looping_code", "Learn/JavaScript/Building_blocks")}}
In any programming language, the code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. In this article, we'll explore how so-called conditional statements work in JavaScript.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML, CSS, and
<a href="/en-US/docs/Learn/JavaScript/First_steps"
>JavaScript first steps</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To understand how to use conditional structures in JavaScript.</td>
</tr>
</tbody>
</table>
## You can have it on one condition!
Human beings (and other animals) make decisions all the time that affect their lives, from small ("should I eat one cookie or two?") to large ("should I stay in my home country and work on my father's farm, or should I move to America and study astrophysics?")
Conditional statements allow us to represent such decision making in JavaScript, from the choice that must be made (for example, "one cookie or two"), to the resulting outcome of those choices (perhaps the outcome of "ate one cookie" might be "still felt hungry", and the outcome of "ate two cookies" might be "felt full, but mom scolded me for eating all the cookies".)

## if...else statements
Let's look at by far the most common type of conditional statement you'll use in JavaScript β the humble [`if...else` statement](/en-US/docs/Web/JavaScript/Reference/Statements/if...else).
### Basic if...else syntax
Basic `if...else` syntax looks like this:
```js
if (condition) {
/* code to run if condition is true */
} else {
/* run some other code instead */
}
```
Here we've got:
1. The keyword `if` followed by some parentheses.
2. A condition to test, placed inside the parentheses (typically "is this value bigger than this other value?", or "does this value exist?"). The condition makes use of the [comparison operators](/en-US/docs/Learn/JavaScript/First_steps/Math#comparison_operators) we discussed in the last module and returns `true` or `false`.
3. A set of curly braces, inside which we have some code β this can be any code we like, and it only runs if the condition returns `true`.
4. The keyword `else`.
5. Another set of curly braces, inside which we have some more code β this can be any code we like, and it only runs if the condition is not `true` β or in other words, the condition is `false`.
This code is pretty human-readable β it is saying "**if** the **condition** returns `true`, run code A, **else** run code B"
You should note that you don't have to include the `else` and the second curly brace block β the following is also perfectly legal code:
```js
if (condition) {
/* code to run if condition is true */
}
/* run some other code */
```
However, you need to be careful here β in this case, the second block of code is not controlled by the conditional statement, so it **always** runs, regardless of whether the condition returns `true` or `false`. This is not necessarily a bad thing, but it might not be what you want β often you want to run one block of code _or_ the other, not both.
As a final point, while not recommended, you may sometimes see `if...else` statements written without the curly braces:
```js example-bad
if (condition) /* code to run if condition is true */
else /* run some other code instead */
```
This syntax is perfectly valid, but it is much easier to understand the code if you use the curly braces to delimit the blocks of code, and use multiple lines and indentation.
### A real example
To understand this syntax better, let's consider a real example. Imagine a child being asked for help with a chore by their mother or father. The parent might say "Hey sweetheart! If you help me by going and doing the shopping, I'll give you some extra allowance so you can afford that toy you wanted." In JavaScript, we could represent this like so:
```js
let shoppingDone = false;
let childsAllowance;
if (shoppingDone === true) {
childsAllowance = 10;
} else {
childsAllowance = 5;
}
```
This code as shown always results in the `shoppingDone` variable returning `false`, meaning disappointment for our poor child. It'd be up to us to provide a mechanism for the parent to set the `shoppingDone` variable to `true` if the child did the shopping.
> **Note:** You can see a more [complete version of this example on GitHub](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/allowance-updater.html) (also see it [running live](https://mdn.github.io/learning-area/javascript/building-blocks/allowance-updater.html).)
### else if
The last example provided us with two choices, or outcomes β but what if we want more than two?
There is a way to chain on extra choices/outcomes to your `if...else` β using `else if`. Each extra choice requires an additional block to put in between `if () { }` and `else { }` β check out the following more involved example, which could be part of a simple weather forecast application:
```html
<label for="weather">Select the weather type today: </label>
<select id="weather">
<option value="">--Make a choice--</option>
<option value="sunny">Sunny</option>
<option value="rainy">Rainy</option>
<option value="snowing">Snowing</option>
<option value="overcast">Overcast</option>
</select>
<p></p>
```
```js
const select = document.querySelector("select");
const para = document.querySelector("p");
select.addEventListener("change", setWeather);
function setWeather() {
const choice = select.value;
if (choice === "sunny") {
para.textContent =
"It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.";
} else if (choice === "rainy") {
para.textContent =
"Rain is falling outside; take a rain coat and an umbrella, and don't stay out for too long.";
} else if (choice === "snowing") {
para.textContent =
"The snow is coming down β it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.";
} else if (choice === "overcast") {
para.textContent =
"It isn't raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.";
} else {
para.textContent = "";
}
}
```
{{ EmbedLiveSample('else_if', '100%', 100, "", "") }}
1. Here we've got an HTML {{htmlelement("select")}} element allowing us to make different weather choices, and a simple paragraph.
2. In the JavaScript, we are storing a reference to both the {{htmlelement("select")}} and {{htmlelement("p")}} elements, and adding an event listener to the `<select>` element so that when its value is changed, the `setWeather()` function is run.
3. When this function is run, we first set a variable called `choice` to the current value selected in the `<select>` element. We then use a conditional statement to show different text inside the paragraph depending on what the value of `choice` is. Notice how all the conditions are tested in `else if () { }` blocks, except for the first one, which is tested in an `if () { }` block.
4. The very last choice, inside the `else { }` block, is basically a "last resort" option β the code inside it will be run if none of the conditions are `true`. In this case, it serves to empty the text out of the paragraph if nothing is selected, for example, if a user decides to re-select the "--Make a choice--" placeholder option shown at the beginning.
> **Note:** You can also [find this example on GitHub](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/simple-else-if.html) ([see it running live](https://mdn.github.io/learning-area/javascript/building-blocks/simple-else-if.html) on there also.)
### A note on comparison operators
Comparison operators are used to test the conditions inside our conditional statements. We first looked at comparison operators back in our [Basic math in JavaScript β numbers and operators](/en-US/docs/Learn/JavaScript/First_steps/Math#comparison_operators) article. Our choices are:
- `===` and `!==` β test if one value is identical to, or not identical to, another.
- `<` and `>` β test if one value is less than or greater than another.
- `<=` and `>=` β test if one value is less than or equal to, or greater than or equal to, another.
We wanted to make a special mention of testing boolean (`true`/`false`) values, and a common pattern you'll come across again and again. Any value that is not `false`, `undefined`, `null`, `0`, `NaN`, or an empty string (`''`) actually returns `true` when tested as a conditional statement, therefore you can use a variable name on its own to test whether it is `true`, or even that it exists (that is, it is not undefined.) So for example:
```js
let cheese = "Cheddar";
if (cheese) {
console.log("Yay! Cheese available for making cheese on toast.");
} else {
console.log("No cheese on toast for you today.");
}
```
And, returning to our previous example about the child doing a chore for their parent, you could write it like this:
```js
let shoppingDone = false;
let childsAllowance;
// We don't need to explicitly specify 'shoppingDone === true'
if (shoppingDone) {
childsAllowance = 10;
} else {
childsAllowance = 5;
}
```
### Nesting if...else
It is perfectly OK to put one `if...else` statement inside another one β to nest them. For example, we could update our weather forecast application to show a further set of choices depending on what the temperature is:
```js
if (choice === "sunny") {
if (temperature < 86) {
para.textContent = `It is ${temperature} degrees outside β nice and sunny. Let's go out to the beach, or the park, and get an ice cream.`;
} else if (temperature >= 86) {
para.textContent = `It is ${temperature} degrees outside β REALLY HOT! If you want to go outside, make sure to put some sunscreen on.`;
}
}
```
Even though the code all works together, each `if...else` statement works completely independently of the other one.
### Logical operators: AND, OR and NOT
If you want to test multiple conditions without writing nested `if...else` statements, [logical operators](/en-US/docs/Web/JavaScript/Reference/Operators) can help you. When used in conditions, the first two do the following:
- `&&` β AND; allows you to chain together two or more expressions so that all of them have to individually evaluate to `true` for the whole expression to return `true`.
- `||` β OR; allows you to chain together two or more expressions so that one or more of them have to individually evaluate to `true` for the whole expression to return `true`.
To give you an AND example, the previous example snippet can be rewritten to this:
```js
if (choice === "sunny" && temperature < 86) {
para.textContent = `It is ${temperature} degrees outside β nice and sunny. Let's go out to the beach, or the park, and get an ice cream.`;
} else if (choice === "sunny" && temperature >= 86) {
para.textContent = `It is ${temperature} degrees outside β REALLY HOT! If you want to go outside, make sure to put some sunscreen on.`;
}
```
So for example, the first code block will only be run if `choice === 'sunny'` _and_ `temperature < 86` return `true`.
Let's look at a quick OR example:
```js
if (iceCreamVanOutside || houseStatus === "on fire") {
console.log("You should leave the house quickly.");
} else {
console.log("Probably should just stay in then.");
}
```
The last type of logical operator, NOT, expressed by the `!` operator, can be used to negate an expression. Let's combine it with OR in the above example:
```js
if (!(iceCreamVanOutside || houseStatus === "on fire")) {
console.log("Probably should just stay in then.");
} else {
console.log("You should leave the house quickly.");
}
```
In this snippet, if the OR statement returns `true`, the NOT operator will negate it so that the overall expression returns `false`.
You can combine as many logical statements together as you want, in whatever structure. The following example executes the code inside only if both OR statements return true, meaning that the overall AND statement will return true:
```js
if ((x === 5 || y > 3 || z <= 10) && (loggedIn || userName === "Steve")) {
// run the code
}
```
A common mistake when using the logical OR operator in conditional statements is to try to state the variable whose value you are checking once, and then give a list of values it could be to return true, separated by `||` (OR) operators. For example:
```js example-bad
if (x === 5 || 7 || 10 || 20) {
// run my code
}
```
In this case, the condition inside `if ()` will always evaluate to true since 7 (or any other non-zero value) always evaluates to `true`. This condition is actually saying "if x equals 5, or 7 is true β which it always is". This is logically not what we want! To make this work you've got to specify a complete test on either side of each OR operator:
```js
if (x === 5 || x === 7 || x === 10 || x === 20) {
// run my code
}
```
## switch statements
`if...else` statements do the job of enabling conditional code well, but they are not without their downsides. They are mainly good for cases where you've got a couple of choices, and each one requires a reasonable amount of code to be run, and/or the conditions are complex (for example, multiple logical operators). For cases where you just want to set a variable to a certain choice of value or print out a particular statement depending on a condition, the syntax can be a bit cumbersome, especially if you've got a large number of choices.
In such a case, [`switch` statements](/en-US/docs/Web/JavaScript/Reference/Statements/switch) are your friend β they take a single expression/value as an input, and then look through several choices until they find one that matches that value, executing the corresponding code that goes along with it. Here's some more pseudocode, to give you an idea:
```js
switch (expression) {
case choice1:
// run this code
break;
case choice2:
// run this code instead
break;
// include as many cases as you like
default:
// actually, just run this code
break;
}
```
Here we've got:
1. The keyword `switch`, followed by a set of parentheses.
2. An expression or value inside the parentheses.
3. The keyword `case`, followed by a choice that the expression/value could be, followed by a colon.
4. Some code to run if the choice matches the expression.
5. A `break` statement, followed by a semicolon. If the previous choice matches the expression/value, the browser stops executing the code block here, and moves on to any code that appears below the switch statement.
6. As many other cases (bullets 3β5) as you like.
7. The keyword `default`, followed by exactly the same code pattern as one of the cases (bullets 3β5), except that `default` does not have a choice after it, and you don't need the `break` statement as there is nothing to run after this in the block anyway. This is the default option that runs if none of the choices match.
> **Note:** You don't have to include the `default` section β you can safely omit it if there is no chance that the expression could end up equaling an unknown value. If there is a chance of this, however, you need to include it to handle unknown cases.
### A switch example
Let's have a look at a real example β we'll rewrite our weather forecast application to use a switch statement instead:
```html
<label for="weather">Select the weather type today: </label>
<select id="weather">
<option value="">--Make a choice--</option>
<option value="sunny">Sunny</option>
<option value="rainy">Rainy</option>
<option value="snowing">Snowing</option>
<option value="overcast">Overcast</option>
</select>
<p></p>
```
```js
const select = document.querySelector("select");
const para = document.querySelector("p");
select.addEventListener("change", setWeather);
function setWeather() {
const choice = select.value;
switch (choice) {
case "sunny":
para.textContent =
"It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.";
break;
case "rainy":
para.textContent =
"Rain is falling outside; take a rain coat and an umbrella, and don't stay out for too long.";
break;
case "snowing":
para.textContent =
"The snow is coming down β it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.";
break;
case "overcast":
para.textContent =
"It isn't raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.";
break;
default:
para.textContent = "";
}
}
```
{{ EmbedLiveSample('A_switch_example', '100%', 100, "", "") }}
> **Note:** You can also [find this example on GitHub](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/simple-switch.html) (see it [running live](https://mdn.github.io/learning-area/javascript/building-blocks/simple-switch.html) on there also.)
## Ternary operator
There is one final bit of syntax we want to introduce you to before we get you to play with some examples. The [ternary or conditional operator](/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator) is a small bit of syntax that tests a condition and returns one value/expression if it is `true`, and another if it is `false` β this can be useful in some situations, and can take up a lot less code than an `if...else` block if you have two choices that are chosen between via a `true`/`false` condition. The pseudocode looks like this:
```js-nolint
condition ? run this code : run this code instead
```
So let's look at a simple example:
```js
const greeting = isBirthday
? "Happy birthday Mrs. Smith β we hope you have a great day!"
: "Good morning Mrs. Smith.";
```
Here we have a variable called `isBirthday` β if this is `true`, we give our guest a happy birthday message; if not, we give her the standard daily greeting.
### Ternary operator example
The ternary operator is not just for setting variable values; you can also run functions, or lines of code β anything you like. The following live example shows a simple theme chooser where the styling for the site is applied using a ternary operator.
```html
<label for="theme">Select theme: </label>
<select id="theme">
<option value="white">White</option>
<option value="black">Black</option>
</select>
<h1>This is my website</h1>
```
```js
const select = document.querySelector("select");
const html = document.querySelector("html");
document.body.style.padding = "10px";
function update(bgColor, textColor) {
html.style.backgroundColor = bgColor;
html.style.color = textColor;
}
select.addEventListener("change", () =>
select.value === "black"
? update("black", "white")
: update("white", "black"),
);
```
{{ EmbedLiveSample('Ternary_operator_example', '100%', 300, "", "") }}
Here we've got a {{htmlelement('select')}} element to choose a theme (black or white), plus a simple {{htmlelement("Heading_Elements", "h1")}} to display a website title. We also have a function called `update()`, which takes two colors as parameters (inputs). The website's background color is set to the first provided color, and its text color is set to the second provided color.
Finally, we've also got an [onchange](/en-US/docs/Web/API/HTMLElement/change_event) event listener that serves to run a function containing a ternary operator. It starts with a test condition β `select.value === 'black'`. If this returns `true`, we run the `update()` function with parameters of black and white, meaning that we end up with a background color of black and a text color of white. If it returns `false`, we run the `update()` function with parameters of white and black, meaning that the site colors are inverted.
> **Note:** You can also [find this example on GitHub](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/simple-ternary.html) (see it [running live](https://mdn.github.io/learning-area/javascript/building-blocks/simple-ternary.html) on there also.)
## Active learning: A simple calendar
In this example, you are going to help us finish a simple calendar application. In the code you've got:
- A {{htmlelement("select")}} element to allow the user to choose between different months.
- An `onchange` event handler to detect when the value selected in the `<select>` menu is changed.
- A function called `createCalendar()` that draws the calendar and displays the correct month in the {{htmlelement("Heading_Elements", "h1")}} element.
We need you to write a conditional statement inside the `onchange` handler function, just below the `// ADD CONDITIONAL HERE` comment. It should:
1. Look at the selected month (stored in the `choice` variable. This will be the `<select>` element value after the value changes, so "January" for example.)
2. Set a variable called `days` to be equal to the number of days in the selected month. To do this you'll have to look up the number of days in each month of the year. You can ignore leap years for the purposes of this example.
Hints:
- You are advised to use logical OR to group multiple months together into a single condition; many of them share the same number of days.
- Think about which number of days is the most common, and use that as a default value.
If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.
```html hidden
<h2>Live output</h2>
<iframe id="output" width="100%" height="600px"></iframe>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 400px;width: 95%">
const select = document.querySelector('select');
const list = document.querySelector('ul');
const h1 = document.querySelector('h1');
select.addEventListener('change', () => {
const choice = select.value;
// ADD CONDITIONAL HERE
createCalendar(days, choice);
});
function createCalendar(days, choice) {
list.innerHTML = '';
h1.textContent = choice;
for (let i = 1; i <= days; i++) {
const listItem = document.createElement('li');
listItem.textContent = i;
list.appendChild(listItem);
}
}
createCalendar(31, 'January');
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css hidden
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```js hidden
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const outputIFrame = document.querySelector("#output");
const textarea = document.getElementById("code");
const initialCode = textarea.value;
let userCode = textarea.value;
const solutionCode = `const select = document.querySelector("select");
const list = document.querySelector("ul");
const h1 = document.querySelector("h1");
select.addEventListener("change", () => {
const choice = select.value;
let days = 31;
if (choice === "February") {
days = 28;
} else if (
choice === "April" ||
choice === "June" ||
choice === "September" ||
choice === "November"
) {
days = 30;
}
createCalendar(days, choice);
});
function createCalendar(days, choice) {
list.innerHTML = "";
h1.textContent = choice;
for (let i = 1; i <= days; i++) {
const listItem = document.createElement("li");
listItem.textContent = i;
list.appendChild(listItem);
}
}
createCalendar(31, "January");`;
function outputDocument(code) {
const outputBody = `
<div class="output" style="height: 500px; overflow: auto">
<label for="month">Select month: </label>
<select id="month">
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<h1></h1>
<ul></ul>
</div>`;
const outputStyle = `
.output * {
box-sizing: border-box;
}
.output ul {
padding-left: 0;
}
.output li {
display: block;
float: left;
width: 25%;
border: 2px solid white;
padding: 5px;
height: 40px;
background-color: #4a2db6;
color: white;
}
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}`;
return `
<!doctype html>
<html>
<head>
<style>${outputStyle}</style>
</head>
<body>
${outputBody}
<script>${code}</script>
</body>
</html>`;
}
function update() {
output.setAttribute("srcdoc", outputDocument(textarea.value));
}
update();
textarea.addEventListener("input", update);
reset.addEventListener("click", () => {
textarea.value = initialCode;
userEntry = textarea.value;
solution.value = "Show solution";
update();
});
solution.addEventListener("click", () => {
if (solution.value === "Show solution") {
// remember the state of the user's code
// so we can restore it
userCode = textarea.value;
textarea.value = solutionCode;
solution.value = "Hide solution";
} else {
textarea.value = userCode;
solution.value = "Show solution";
}
update();
});
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = (e) => {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
```
{{ EmbedLiveSample('Active_learning_A_simple_calendar', '100%', 1210) }}
## Active learning: More color choices
In this example, you are going to take the ternary operator example we saw earlier and convert the ternary operator into a switch statement to allow us to apply more choices to the simple website. Look at the {{htmlelement("select")}} β this time you'll see that it has not two theme options, but five. You need to add a switch statement just underneath the `// ADD SWITCH STATEMENT` comment:
- It should accept the `choice` variable as its input expression.
- For each case, the choice should equal one of the possible `<option>` values that can be selected, that is, `white`, `black`, `purple`, `yellow`, or `psychedelic`.
- For each case, the `update()` function should be run, and be passed two color values, the first one for the background color, and the second one for the text color. Remember that color values are strings, so they need to be wrapped in quotes.
If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.
```html hidden
<h2>Live output</h2>
<div class="output" style="height: 300px;">
<label for="theme">Select theme: </label>
<select id="theme">
<option value="white">White</option>
<option value="black">Black</option>
<option value="purple">Purple</option>
<option value="yellow">Yellow</option>
<option value="psychedelic">Psychedelic</option>
</select>
<h1>This is my website</h1>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 450px;width: 95%">
const select = document.querySelector('select');
const html = document.querySelector('.output');
select.addEventListener('change', () => {
const choice = select.value;
// ADD SWITCH STATEMENT
});
function update(bgColor, textColor) {
html.style.backgroundColor = bgColor;
html.style.color = textColor;
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css hidden
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```js hidden
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", function () {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `const select = document.querySelector('select');
const html = document.querySelector('.output');
select.addEventListener('change', () => {
const choice = select.value;
switch(choice) {
case 'black':
update('black','white');
break;
case 'white':
update('white','black');
break;
case 'purple':
update('purple','white');
break;
case 'yellow':
update('yellow','purple');
break;
case 'psychedelic':
update('lime','purple');
break;
}
});
function update(bgColor, textColor) {
html.style.backgroundColor = bgColor;
html.style.color = textColor;
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function (e) {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = function () {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
{{ EmbedLiveSample('Active_learning_More_color_choices', '100%', 950) }}
## 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: Conditionals](/en-US/docs/Learn/JavaScript/Building_blocks/Test_your_skills:_Conditionals).
## Conclusion
And that's all you really need to know about conditional structures in JavaScript right now! If there is anything you didn't understand, feel free to read through the article again, or [contact us](/en-US/docs/Learn#contact_us) to ask for help.
## See also
- [Comparison operators](/en-US/docs/Learn/JavaScript/First_steps/Math#comparison_operators)
- [Conditional statements in detail](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#conditional_statements)
- [if...else reference](/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
- [Conditional (ternary) operator reference](/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator)
{{NextMenu("Learn/JavaScript/Building_blocks/Looping_code", "Learn/JavaScript/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/looping_code/index.md | ---
title: Looping code
slug: Learn/JavaScript/Building_blocks/Looping_code
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}
Programming languages are very useful for rapidly completing repetitive tasks, from multiple basic calculations to just about any other situation where you've got a lot of similar items of work to complete. Here we'll look at the loop structures available in JavaScript that handle such needs.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML, CSS, and
<a href="/en-US/docs/Learn/JavaScript/First_steps"
>JavaScript first steps</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To understand how to use loops in JavaScript.</td>
</tr>
</tbody>
</table>
## Why are loops useful?
Loops are all about doing the same thing over and over again. Often, the code will be slightly different each time round the loop, or the same code will run but with different variables.
### Looping code example
Suppose we wanted to draw 100 random circles on a {{htmlelement("canvas")}} element (press the _Update_ button to run the example again and again to see different random sets):
```html hidden
<button>Update</button> <canvas></canvas>
```
```css hidden
html {
width: 100%;
height: inherit;
background: #ddd;
}
canvas {
display: block;
}
body {
margin: 0;
}
button {
position: absolute;
top: 5px;
left: 5px;
}
```
{{ EmbedLiveSample('Looping_code_example', '100%', 400) }}
Here's the JavaScript code that implements this example:
```js
const btn = document.querySelector("button");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
document.addEventListener("DOMContentLoaded", () => {
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
});
function random(number) {
return Math.floor(Math.random() * number);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(
random(canvas.width),
random(canvas.height),
random(50),
0,
2 * Math.PI,
);
ctx.fill();
}
}
btn.addEventListener("click", draw);
```
### With and without a loop
You don't have to understand all the code for now, but let's look at the part of the code that actually draws the 100 circles:
```js
for (let i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(
random(canvas.width),
random(canvas.height),
random(50),
0,
2 * Math.PI,
);
ctx.fill();
}
```
- `random(x)`, defined earlier in the code, returns a whole number between `0` and `x-1`.
You should get the basic idea β we are using a loop to run 100 iterations of this code, each one of which draws a circle in a random position on the page.
The amount of code needed would be the same whether we were drawing 100 circles, 1000, or 10,000.
Only one number has to change.
If we weren't using a loop here, we'd have to repeat the following code for every circle we wanted to draw:
```js
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(
random(canvas.width),
random(canvas.height),
random(50),
0,
2 * Math.PI,
);
ctx.fill();
```
This would get very boring and difficult to maintain.
## Looping through a collection
Most of the time when you use a loop, you will have a collection of items and want to do something with every item.
One type of collection is the {{jsxref("Array")}}, which we met in the [Arrays](/en-US/docs/Learn/JavaScript/First_steps/Arrays) chapter of this course.
But there are other collections in JavaScript as well, including {{jsxref("Set")}} and {{jsxref("Map")}}.
### The for...of loop
The basic tool for looping through a collection is the {{jsxref("statements/for...of","for...of")}} loop:
```js
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
for (const cat of cats) {
console.log(cat);
}
```
In this example, `for (const cat of cats)` says:
1. Given the collection `cats`, get the first item in the collection.
2. Assign it to the variable `cat` and then run the code between the curly braces `{}`.
3. Get the next item, and repeat (2) until you've reached the end of the collection.
### map() and filter()
JavaScript also has more specialized loops for collections, and we'll mention two of them here.
You can use `map()` to do something to each item in a collection and create a new collection containing the changed items:
```js
function toUpper(string) {
return string.toUpperCase();
}
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
const upperCats = cats.map(toUpper);
console.log(upperCats);
// [ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]
```
Here we pass a function into {{jsxref("Array.prototype.map()","cats.map()")}}, and `map()` calls the function once for each item in the array, passing in the item. It then adds the return value from each function call to a new array, and finally returns the new array. In this case the function we provide converts the item to uppercase, so the resulting array contains all our cats in uppercase:
```js-nolint
[ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]
```
You can use {{jsxref("Array.prototype.filter()","filter()")}} to test each item in a collection, and create a new collection containing only items that match:
```js
function lCat(cat) {
return cat.startsWith("L");
}
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
const filtered = cats.filter(lCat);
console.log(filtered);
// [ "Leopard", "Lion" ]
```
This looks a lot like `map()`, except the function we pass in returns a [boolean](/en-US/docs/Learn/JavaScript/First_steps/Variables#booleans): if it returns `true`, then the item is included in the new array.
Our function tests that the item starts with the letter "L", so the result is an array containing only cats whose names start with "L":
```js-nolint
[ "Leopard", "Lion" ]
```
Note that `map()` and `filter()` are both often used with _function expressions_, which we will learn about in the [Functions](/en-US/docs/Learn/JavaScript/Building_blocks/Functions) module.
Using function expressions we could rewrite the example above to be much more compact:
```js
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
const filtered = cats.filter((cat) => cat.startsWith("L"));
console.log(filtered);
// [ "Leopard", "Lion" ]
```
## The standard for loop
In the "drawing circles" example above, you don't have a collection of items to loop through: you really just want to run the same code 100 times.
In a case like that, you should use the {{jsxref("statements/for","for")}} loop.
This has the following syntax:
```js-nolint
for (initializer; condition; final-expression) {
// code to run
}
```
Here we have:
1. The keyword `for`, followed by some parentheses.
2. Inside the parentheses we have three items, separated by semicolons:
1. An **initializer** β this is usually a variable set to a number, which is incremented to count the number of times the loop has run.
It is also sometimes referred to as a **counter variable**.
2. A **condition** β this defines when the loop should stop looping.
This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met.
3. A **final-expression** β this is always evaluated (or run) each time the loop has gone through a full iteration.
It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the point where the condition is no longer `true`.
3. Some curly braces that contain a block of code β this code will be run each time the loop iterates.
### Calculating squares
Let's look at a real example so we can visualize what these do more clearly.
```html hidden
<button id="calculate">Calculate</button>
<button id="clear">Clear</button>
<pre id="results"></pre>
```
```js
const results = document.querySelector("#results");
function calculate() {
for (let i = 1; i < 10; i++) {
const newResult = `${i} x ${i} = ${i * i}`;
results.textContent += `${newResult}\n`;
}
results.textContent += "\nFinished!";
}
const calculateBtn = document.querySelector("#calculate");
const clearBtn = document.querySelector("#clear");
calculateBtn.addEventListener("click", calculate);
clearBtn.addEventListener("click", () => (results.textContent = ""));
```
This gives us the following output:
{{ EmbedLiveSample('Calculating squares', '100%', 250) }}
This code calculates squares for the numbers from 1 to 9, and writes out the result. The core of the code is the `for` loop that performs the calculation.
Let's break down the `for (let i = 1; i < 10; i++)` line into its three pieces:
1. `let i = 1`: the counter variable, `i`, starts at `1`. Note that we have to use `let` for the counter, because we're reassigning it each time we go round the loop.
2. `i < 10`: keep going round the loop for as long as `i` is smaller than `10`.
3. `i++`: add one to `i` each time round the loop.
Inside the loop, we calculate the square of the current value of `i`, that is: `i * i`. We create a string expressing the calculation we made and the result, and add this string to the output text. We also add `\n`, so the next string we add will begin on a new line. So:
1. During the first run, `i = 1`, so we will add `1 x 1 = 1`.
2. During the second run, `i = 2`, so we will add `2 x 2 = 4`.
3. And so onβ¦
4. When `i` becomes equal to `10` we will stop running the loop and move straight to the next bit of code below the loop, printing out the `Finished!` message on a new line.
### Looping through collections with a for loop
You can use a `for` loop to iterate through a collection, instead of a `for...of` loop.
Let's look again at our `for...of` example above:
```js
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
for (const cat of cats) {
console.log(cat);
}
```
We could rewrite that code like this:
```js
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];
for (let i = 0; i < cats.length; i++) {
console.log(cats[i]);
}
```
In this loop we're starting `i` at `0`, and stopping when `i` reaches the length of the array.
Then inside the loop, we're using `i` to access each item in the array in turn.
This works just fine, and in early versions of JavaScript, `for...of` didn't exist, so this was the standard way to iterate through an array.
However, it offers more chances to introduce bugs into your code. For example:
- you might start `i` at `1`, forgetting that the first array index is zero, not 1.
- you might stop at `i <= cats.length`, forgetting that the last array index is at `length - 1`.
For reasons like this, it's usually best to use `for...of` if you can.
Sometimes you still need to use a `for` loop to iterate through an array.
For example, in the code below we want to log a message listing our cats:
```js
const cats = ["Pete", "Biggles", "Jasmine"];
let myFavoriteCats = "My cats are called ";
for (const cat of cats) {
myFavoriteCats += `${cat}, `;
}
console.log(myFavoriteCats); // "My cats are called Pete, Biggles, Jasmine, "
```
The final output sentence isn't very well-formed:
```plain
My cats are called Pete, Biggles, Jasmine,
```
We'd prefer it to handle the last cat differently, like this:
```plain
My cats are called Pete, Biggles, and Jasmine.
```
But to do this we need to know when we are on the final loop iteration, and to do that we can use a `for` loop and examine the value of `i`:
```js
const cats = ["Pete", "Biggles", "Jasmine"];
let myFavoriteCats = "My cats are called ";
for (let i = 0; i < cats.length; i++) {
if (i === cats.length - 1) {
// We are at the end of the array
myFavoriteCats += `and ${cats[i]}.`;
} else {
myFavoriteCats += `${cats[i]}, `;
}
}
console.log(myFavoriteCats); // "My cats are called Pete, Biggles, and Jasmine."
```
## Exiting loops with break
If you want to exit a loop before all the iterations have been completed, you can use the [break](/en-US/docs/Web/JavaScript/Reference/Statements/break) statement.
We already met this in the previous article when we looked at [switch statements](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#switch_statements) β when a case is met in a switch statement that matches the input expression, the `break` statement immediately exits the switch statement and moves on to the code after it.
It's the same with loops β a `break` statement will immediately exit the loop and make the browser move on to any code that follows it.
Say we wanted to search through an array of contacts and telephone numbers and return just the number we wanted to find?
First, some simple HTML β a text {{htmlelement("input")}} allowing us to enter a name to search for, a {{htmlelement("button")}} element to submit a search, and a {{htmlelement("p")}} element to display the results in:
```html
<label for="search">Search by contact name: </label>
<input id="search" type="text" />
<button>Search</button>
<p></p>
```
Now on to the JavaScript:
```js
const contacts = [
"Chris:2232322",
"Sarah:3453456",
"Bill:7654322",
"Mary:9998769",
"Dianne:9384975",
];
const para = document.querySelector("p");
const input = document.querySelector("input");
const btn = document.querySelector("button");
btn.addEventListener("click", () => {
const searchName = input.value.toLowerCase();
input.value = "";
input.focus();
para.textContent = "";
for (const contact of contacts) {
const splitContact = contact.split(":");
if (splitContact[0].toLowerCase() === searchName) {
para.textContent = `${splitContact[0]}'s number is ${splitContact[1]}.`;
break;
}
}
if (para.textContent === "") {
para.textContent = "Contact not found.";
}
});
```
{{ EmbedLiveSample('Exiting_loops_with_break', '100%', 100) }}
1. First of all, we have some variable definitions β we have an array of contact information, with each item being a string containing a name and phone number separated by a colon.
2. Next, we attach an event listener to the button (`btn`) so that when it is pressed some code is run to perform the search and return the results.
3. We store the value entered into the text input in a variable called `searchName`, before then emptying the text input and focusing it again, ready for the next search.
Note that we also run the [`toLowerCase()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) method on the string, so that searches will be case-insensitive.
4. Now on to the interesting part, the `for...of` loop:
1. Inside the loop, we first split the current contact at the colon character, and store the resulting two values in an array called `splitContact`.
2. We then use a conditional statement to test whether `splitContact[0]` (the contact's name, again lower-cased with [`toLowerCase()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase)) is equal to the inputted `searchName`.
If it is, we enter a string into the paragraph to report what the contact's number is, and use `break` to end the loop.
5. After the loop, we check whether we set a contact, and if not we set the paragraph text to "Contact not found.".
> **Note:** You can view the [full source code on GitHub](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/loops/contact-search.html) too (also [see it running live](https://mdn.github.io/learning-area/javascript/building-blocks/loops/contact-search.html)).
## Skipping iterations with continue
The [continue](/en-US/docs/Web/JavaScript/Reference/Statements/continue) statement works similarly to `break`, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop.
Let's look at another example that takes a number as an input, and returns only the numbers that are squares of integers (whole numbers).
The HTML is basically the same as the last example β a simple numeric input, and a paragraph for output.
```html
<label for="number">Enter number: </label>
<input id="number" type="number" />
<button>Generate integer squares</button>
<p>Output:</p>
```
The JavaScript is mostly the same too, although the loop itself is a bit different:
```js
const para = document.querySelector("p");
const input = document.querySelector("input");
const btn = document.querySelector("button");
btn.addEventListener("click", () => {
para.textContent = "Output: ";
const num = input.value;
input.value = "";
input.focus();
for (let i = 1; i <= num; i++) {
let sqRoot = Math.sqrt(i);
if (Math.floor(sqRoot) !== sqRoot) {
continue;
}
para.textContent += `${i} `;
}
});
```
Here's the output:
{{ EmbedLiveSample('Skipping_iterations_with_continue', '100%', 100) }}
1. In this case, the input should be a number (`num`). The `for` loop is given a counter starting at 1 (as we are not interested in 0 in this case), an exit condition that says the loop will stop when the counter becomes bigger than the input `num`, and an iterator that adds 1 to the counter each time.
2. Inside the loop, we find the square root of each number using [Math.sqrt(i)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt), then check whether the square root is an integer by testing whether it is the same as itself when it has been rounded down to the nearest integer (this is what [Math.floor()](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor) does to the number it is passed).
3. If the square root and the rounded down square root do not equal one another (`!==`), it means that the square root is not an integer, so we are not interested in it. In such a case, we use the `continue` statement to skip on to the next loop iteration without recording the number anywhere.
4. If the square root is an integer, we skip past the `if` block entirely, so the `continue` statement is not executed; instead, we concatenate the current `i` value plus a space at the end of the paragraph content.
> **Note:** You can view the [full source code on GitHub](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/loops/integer-squares.html) too (also [see it running live](https://mdn.github.io/learning-area/javascript/building-blocks/loops/integer-squares.html)).
## while and do...while
`for` is not the only type of loop available in JavaScript. There are actually many others and, while you don't need to understand all of these now, it is worth having a look at the structure of a couple of others so that you can recognize the same features at work in a slightly different way.
First, let's have a look at the [while](/en-US/docs/Web/JavaScript/Reference/Statements/while) loop. This loop's syntax looks like so:
```js-nolint
initializer
while (condition) {
// code to run
final-expression
}
```
This works in a very similar way to the `for` loop, except that the initializer variable is set before the loop, and the final-expression is included inside the loop after the code to run, rather than these two items being included inside the parentheses.
The condition is included inside the parentheses, which are preceded by the `while` keyword rather than `for`.
The same three items are still present, and they are still defined in the same order as they are in the for loop.
This is because you must have an initializer defined before you can check whether or not the condition is true.
The final-expression is then run after the code inside the loop has run (an iteration has been completed), which will only happen if the condition is still true.
Let's have a look again at our cats list example, but rewritten to use a while loop:
```js
const cats = ["Pete", "Biggles", "Jasmine"];
let myFavoriteCats = "My cats are called ";
let i = 0;
while (i < cats.length) {
if (i === cats.length - 1) {
myFavoriteCats += `and ${cats[i]}.`;
} else {
myFavoriteCats += `${cats[i]}, `;
}
i++;
}
console.log(myFavoriteCats); // "My cats are called Pete, Biggles, and Jasmine."
```
> **Note:** This still works just the same as expected β have a look at it [running live on GitHub](https://mdn.github.io/learning-area/javascript/building-blocks/loops/while.html) (also view the [full source code](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/loops/while.html)).
The [do...while](/en-US/docs/Web/JavaScript/Reference/Statements/do...while) loop is very similar, but provides a variation on the while structure:
```js-nolint
initializer
do {
// code to run
final-expression
} while (condition)
```
In this case, the initializer again comes first, before the loop starts. The keyword directly precedes the curly braces containing the code to run and the final expression.
The main difference between a `do...while` loop and a `while` loop is that _the code inside a `do...while` loop is always executed at least once_. That's because the condition comes after the code inside the loop. So we always run that code, then check to see if we need to run it again. In `while` and `for` loops, the check comes first, so the code might never be executed.
Let's rewrite our cat listing example again to use a `do...while` loop:
```js
const cats = ["Pete", "Biggles", "Jasmine"];
let myFavoriteCats = "My cats are called ";
let i = 0;
do {
if (i === cats.length - 1) {
myFavoriteCats += `and ${cats[i]}.`;
} else {
myFavoriteCats += `${cats[i]}, `;
}
i++;
} while (i < cats.length);
console.log(myFavoriteCats); // "My cats are called Pete, Biggles, and Jasmine."
```
> **Note:** Again, this works just the same as expected β have a look at it [running live on GitHub](https://mdn.github.io/learning-area/javascript/building-blocks/loops/do-while.html) (also view the [full source code](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/loops/do-while.html)).
> **Warning:** With while and do...while β as with all loops β you must make sure that the initializer is incremented or, depending on the case, decremented, so the condition eventually becomes false.
> If not, the loop will go on forever, and either the browser will force it to stop, or it will crash. This is called an **infinite loop**.
## Active learning: Launch countdown
In this exercise, we want you to print out a simple launch countdown to the output box, from 10 down to Blastoff.
Specifically, we want you to:
- Loop from 10 down to 0. We've provided you with an initializer β `let i = 10;`.
- For each iteration, create a new paragraph and append it to the output `<div>`, which we've selected using `const output = document.querySelector('.output');`.
In comments, we've provided you with three code lines that need to be used somewhere inside the loop:
- `const para = document.createElement('p');` β creates a new paragraph.
- `output.appendChild(para);` β appends the paragraph to the output `<div>`.
- `para.textContent =` β makes the text inside the paragraph equal to whatever you put on the right-hand side, after the equals sign.
- Different iteration numbers require different text to be put in the paragraph for that iteration (you'll need a conditional statement and multiple `para.textContent =` lines):
- If the number is 10, print "Countdown 10" to the paragraph.
- If the number is 0, print "Blast off!" to the paragraph.
- For any other number, print just the number to the paragraph.
- Remember to include an iterator! However, in this example we are counting down after each iteration, not up, so you **don't** want `i++` β how do you iterate downwards?
> **Note:** If you start typing the loop (for example (while(i>=0)), the browser might get stuck because you have not yet entered the end condition. So be careful with this. You can start writing your code in a comment to deal with this issue and remove the comment after you finish.
If you make a mistake, you can always reset the example with the "Reset" button.
If you get really stuck, press "Show solution" to see a solution.
```html hidden
<h2>Live output</h2>
<div class="output" style="height: 410px;overflow: auto;"></div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 300px;width: 95%">
let output = document.querySelector('.output');
output.innerHTML = '';
// let i = 10;
// const para = document.createElement('p');
// para.textContent = ;
// output.appendChild(para);
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```js hidden
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", function () {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
let jsSolution = `const output = document.querySelector('.output');
output.innerHTML = '';
let i = 10;
while (i >= 0) {
const para = document.createElement('p');
if (i === 10) {
para.textContent = \`Countdown \${i}\`;
} else if (i === 0) {
para.textContent = 'Blast off!';
} else {
para.textContent = i;
}
output.appendChild(para);
i--;
}`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function (e) {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = () => {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
{{ EmbedLiveSample('Active_learning_Launch_countdown', '100%', 900) }}
## Active learning: Filling in a guest list
In this exercise, we want you to take a list of names stored in an array and put them into a guest list. But it's not quite that easy β we don't want to let Phil and Lola in because they are greedy and rude, and always eat all the food! We have two lists, one for guests to admit, and one for guests to refuse.
Specifically, we want you to:
- Write a loop that will iterate through the `people` array.
- During each loop iteration, check if the current array item is equal to "Phil" or "Lola" using a conditional statement:
- If it is, concatenate the array item to the end of the `refused` paragraph's `textContent`, followed by a comma and a space.
- If it isn't, concatenate the array item to the end of the `admitted` paragraph's `textContent`, followed by a comma and a space.
We've already provided you with:
- `refused.textContent +=` β the beginnings of a line that will concatenate something at the end of `refused.textContent`.
- `admitted.textContent +=` β the beginnings of a line that will concatenate something at the end of `admitted.textContent`.
Extra bonus question β after completing the above tasks successfully, you will be left with two lists of names, separated by commas, but they will be untidy β there will be a comma at the end of each one.
Can you work out how to write lines that slice the last comma off in each case, and add a full stop to the end?
Have a look at the [Useful string methods](/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods) article for help.
If you make a mistake, you can always reset the example with the "Reset" button.
If you get really stuck, press "Show solution" to see a solution.
```html hidden
<h2>Live output</h2>
<div class="output" style="height: 100px;overflow: auto;">
<p class="admitted">Admit:</p>
<p class="refused">Refuse:</p>
</div>
<h2>Editable code</h2>
<p class="a11y-label">
Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>
<textarea id="code" class="playable-code" style="height: 400px;width: 95%">
const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];
const admitted = document.querySelector('.admitted');
const refused = document.querySelector('.refused');
admitted.textContent = 'Admit: ';
refused.textContent = 'Refuse: ';
// loop starts here
// refused.textContent += ;
// admitted.textContent += ;
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css hidden
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```js hidden
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = "Show solution";
updateCode();
});
solution.addEventListener("click", function () {
if (solution.value === "Show solution") {
textarea.value = solutionEntry;
solution.value = "Hide solution";
} else {
textarea.value = userEntry;
solution.value = "Show solution";
}
updateCode();
});
const jsSolution = `
const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];
const admitted = document.querySelector('.admitted');
const refused = document.querySelector('.refused');
admitted.textContent = 'Admit: ';
refused.textContent = 'Refuse: ';
for (const person of people) {
if (person === 'Phil' || person === 'Lola') {
refused.textContent += \`\${person}, \`;
} else {
admitted.textContent += \`\${person}, \`;
}
}
refused.textContent = refused.textContent.slice(0,refused.textContent.length-2) + '.';
admitted.textContent = admitted.textContent.slice(0,admitted.textContent.length-2) + '.';`;
let solutionEntry = jsSolution;
textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function (e) {
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret("\t");
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
const scrollPos = textarea.scrollTop;
let caretPos = textarea.selectionStart;
const front = textarea.value.substring(0, caretPos);
const back = textarea.value.substring(
textarea.selectionEnd,
textarea.value.length,
);
textarea.value = front + text + back;
caretPos += text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = () => {
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if (solution.value === "Show solution") {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
```
{{ EmbedLiveSample('Active_learning_Filling_in_a_guest_list', '100%', 680) }}
## Which loop type should you use?
If you're iterating through an array or some other object that supports it, and don't need access to the index position of each item, then `for...of` is the best choice. It's easier to read and there's less to go wrong.
For other uses, `for`, `while`, and `do...while` loops are largely interchangeable.
They can all be used to solve the same problems, and which one you use will largely depend on your personal preference β which one you find easiest to remember or most intuitive.
We would recommend `for`, at least to begin with, as it is probably the easiest for remembering everything β the initializer, condition, and final-expression all have to go neatly into the parentheses, so it is easy to see where they are and check that you aren't missing them.
Let's have a look at them all again.
First `for...of`:
```js-nolint
for (const item of array) {
// code to run
}
```
`for`:
```js-nolint
for (initializer; condition; final-expression) {
// code to run
}
```
`while`:
```js-nolint
initializer
while (condition) {
// code to run
final-expression
}
```
and finally `do...while`:
```js-nolint
initializer
do {
// code to run
final-expression
} while (condition)
```
> **Note:** There are other loop types/features too, which are useful in advanced/specialized situations and beyond the scope of this article. If you want to go further with your loop learning, read our advanced [Loops and iteration guide](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration).
## 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: Loops](/en-US/docs/Learn/JavaScript/Building_blocks/Test_your_skills:_Loops).
## Conclusion
This article has revealed to you the basic concepts behind, and different options available when looping code in JavaScript.
You should now be clear on why loops are a good mechanism for dealing with repetitive code and raring to use them in your own examples!
If there is anything you didn't understand, feel free to read through the article again, or [contact us](/en-US/docs/Learn#contact_us) to ask for help.
## See also
- [Loops and iteration in detail](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
- [for...of reference](/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
- [for statement reference](/en-US/docs/Web/JavaScript/Reference/Statements/for)
- [while](/en-US/docs/Web/JavaScript/Reference/Statements/while) and [do...while](/en-US/docs/Web/JavaScript/Reference/Statements/do...while) references
- [break](/en-US/docs/Web/JavaScript/Reference/Statements/break) and [continue](/en-US/docs/Web/JavaScript/Reference/Statements/continue) references
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/build_your_own_function/index.md | ---
title: Build your own function
slug: Learn/JavaScript/Building_blocks/Build_your_own_function
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Functions","Learn/JavaScript/Building_blocks/Return_values", "Learn/JavaScript/Building_blocks")}}
With most of the essential theory dealt with in the previous article, this article provides practical experience. Here you will get some practice building your own, custom function. Along the way, we'll also explain some useful details of dealing with functions.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML, CSS, and
<a href="/en-US/docs/Learn/JavaScript/First_steps"
>JavaScript first steps</a
>. Also, <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions"
>Functions β reusable blocks of code</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To provide some practice in building a custom function, and explain a
few more useful associated details.
</td>
</tr>
</tbody>
</table>
## Active learning: Let's build a function
The custom function we are going to build will be called `displayMessage()`. It will display a custom message box on a web page and will act as a customized replacement for a browser's built-in [alert()](/en-US/docs/Web/API/Window/alert) function. We've seen this before, but let's just refresh our memories. Type the following in your browser's JavaScript console, on any page you like:
```js
alert("This is a message");
```
The `alert` function takes a single argument β the string that is displayed in the alert box. Try varying the string to change the message.
The `alert` function is limited: you can alter the message, but you can't easily vary anything else, such as the color, icon, or anything else. We'll build one that will prove to be more fun.
> **Note:** This example should work in all modern browsers fine, but the styling might look a bit funny in slightly older browsers. We'd recommend you do this exercise in a modern browser like Firefox, Opera, or Chrome.
## The basic function
To begin with, let's put together a basic function.
> **Note:** For function naming conventions, you should follow the same rules as [variable naming conventions](/en-US/docs/Learn/JavaScript/First_steps/Variables#an_aside_on_variable_naming_rules). This is fine, as you can tell them apart β function names appear with parentheses after them, and variables don't.
1. Start by accessing the [function-start.html](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/functions/function-start.html) file and making a local copy. You'll see that the HTML is simple β the body contains just a single button. We've also provided some basic CSS to style the custom message box, and an empty {{htmlelement("script")}} element to put our JavaScript in.
2. Next, add the following inside the `<script>` element:
```js-nolint
function displayMessage() {
...
}
```
We start off with the keyword `function`, which means we are defining a function. This is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. Any parameters we want to give to our function go inside the parentheses, and the code that runs when we call the function goes inside the curly braces.
3. Finally, add the following code inside the curly braces:
```js
const body = document.body;
const panel = document.createElement("div");
panel.setAttribute("class", "msgBox");
body.appendChild(panel);
const msg = document.createElement("p");
msg.textContent = "This is a message box";
panel.appendChild(msg);
const closeBtn = document.createElement("button");
closeBtn.textContent = "x";
panel.appendChild(closeBtn);
closeBtn.addEventListener("click", () =>
panel.parentNode.removeChild(panel),
);
```
This is quite a lot of code to go through, so we'll walk you through it bit by bit.
The first line selects the {{htmlelement("body")}} element by using the [DOM API](/en-US/docs/Web/API/Document_Object_Model) to get the [`body`](/en-US/docs/Web/API/Document/body) property of the global [`document`](/en-US/docs/Web/API/Document/body) object, and assigning that to a constant called `body`, so we can do things to it later on:
```js
const body = document.body;
```
The next section uses a DOM API function called {{domxref("document.createElement()")}} to create a {{htmlelement("div")}} element and store a reference to it in a constant called `panel`. This element will be the outer container of our message box.
We then use yet another DOM API function called {{domxref("Element.setAttribute()")}} to set a `class` attribute on our panel with a value of `msgBox`. This is to make it easier to style the element β if you look at the CSS on the page, you'll see that we are using a `.msgBox` class selector to style the message box and its contents.
Finally, we call a DOM function called {{domxref("Node.appendChild()")}} on the `body` constant we stored earlier, which nests one element inside the other as a child of it. We specify the panel `<div>` as the child we want to append inside the `<body>` element. We need to do this as the element we created won't just appear on the page on its own β we need to specify where to put it.
```js
const panel = document.createElement("div");
panel.setAttribute("class", "msgBox");
body.appendChild(panel);
```
The next two sections make use of the same `createElement()` and `appendChild()` functions we've already seen to create two new elements β a {{htmlelement("p")}} and a {{htmlelement("button")}} β and insert them in the page as children of the panel `<div>`. We use their {{domxref("Node.textContent")}} property β which represents the text content of an element β to insert a message inside the paragraph, and an "x" inside the button. This button will be what needs to be clicked/activated when the user wants to close the message box.
```js
const msg = document.createElement("p");
msg.textContent = "This is a message box";
panel.appendChild(msg);
const closeBtn = document.createElement("button");
closeBtn.textContent = "x";
panel.appendChild(closeBtn);
```
Finally, we call {{domxref("EventTarget/addEventListener", "addEventListener()")}} to add a function that will be called when the user clicks the "close" button. The code will delete the whole panel from the page β to close the message box.
Briefly, the `addEventListener()` method is provided by the button (or in fact, any element on the page) that can be passed a function and the name of an event. In this case, the name of the event is 'click', meaning that when the user clicks the button, the function will run. You'll learn a lot more about events in our [events article](/en-US/docs/Learn/JavaScript/Building_blocks/Events). The line inside the function uses the {{domxref("Node.removeChild()")}} DOM API function to specify that we want to remove a specific child element of the HTML element β in this case, the panel `<div>`.
```js
closeBtn.addEventListener("click", () => panel.parentNode.removeChild(panel));
```
Basically, this whole block of code is generating a block of HTML that looks like so, and inserting it into the page:
```html
<div class="msgBox">
<p>This is a message box</p>
<button>x</button>
</div>
```
That was a lot of code to work through β don't worry too much if you don't remember exactly how every bit of it works right now! The main part we want to focus on here is the function's structure and usage, but we wanted to show something interesting for this example.
## Calling the function
You've now got your function definition written into your `<script>` element just fine, but it will do nothing as it stands.
1. Try including the following line below your function to call it:
```js
displayMessage();
```
This line invokes the function, making it run immediately. When you save your code and reload it in the browser, you'll see the little message box appear immediately, only once. We are only calling it once, after all.
2. Now open your browser developer tools on the example page, go to the JavaScript console and type the line again there, you'll see it appear again! So this is fun β we now have a reusable function that we can call any time we like.
But we probably want it to appear in response to user and system actions. In a real application, such a message box would probably be called in response to new data being available, or an error having occurred, or the user trying to delete their profile ("are you sure about this?"), or the user adding a new contact and the operation completing successfully, etc.
In this demo, we'll get the message box to appear when the user clicks the button.
3. Delete the previous line you added.
4. Next, we'll select the button and store a reference to it in a constant. Add the following line to your code, above the function definition:
```js
const btn = document.querySelector("button");
```
5. Finally, add the following line below the previous one:
```js
btn.addEventListener("click", displayMessage);
```
In a similar way to our closeBtn's click event handler, here we are calling some code in response to a button being clicked. But in this case, instead of calling an anonymous function containing some code, we are calling our `displayMessage()` function by name.
6. Try saving and refreshing the page β now you should see the message box appear when you click the button.
You might be wondering why we haven't included the parentheses after the function name. This is because we don't want to call the function immediately β only after the button has been clicked. If you try changing the line to
```js
btn.addEventListener("click", displayMessage());
```
and saving and reloading, you'll see that the message box appears without the button being clicked! The parentheses in this context are sometimes called the "function invocation operator". You only use them when you want to run the function immediately in the current scope. In the same respect, the code inside the anonymous function is not run immediately, as it is inside the function scope.
If you tried the last experiment, make sure to undo the last change before carrying on.
## Improving the function with parameters
As it stands, the function is still not very useful β we don't want to just show the same default message every time. Let's improve our function by adding some parameters, allowing us to call it with some different options.
1. First of all, update the first line of the function:
```js
function displayMessage() {
```
to this:
```js
function displayMessage(msgText, msgType) {
```
Now when we call the function, we can provide two variable values inside the parentheses to specify the message to display in the message box, and the type of message it is.
2. To make use of the first parameter, update the following line inside your function:
```js
msg.textContent = "This is a message box";
```
to
```js
msg.textContent = msgText;
```
3. Last but not least, you now need to update your function call to include some updated message text. Change the following line:
```js
btn.addEventListener("click", displayMessage);
```
to this block:
```js
btn.addEventListener("click", () =>
displayMessage("Woo, this is a different message!"),
);
```
If we want to specify parameters inside parentheses for the function we are calling, then we can't call it directly β we need to put it inside an anonymous function so that it isn't in the immediate scope and therefore isn't called immediately. Now it will not be called until the button is clicked.
4. Reload and try the code again and you'll see that it still works just fine, except that now you can also vary the message inside the parameter to get different messages displayed in the box!
### A more complex parameter
On to the next parameter. This one is going to involve slightly more work β we are going to set it so that depending on what the `msgType` parameter is set to, the function will display a different icon and a different background color.
1. First of all, download the icons needed for this exercise ([warning](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/functions/icons/warning.png) and [chat](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/functions/icons/chat.png)) from GitHub. Save them in a new folder called `icons` in the same location as your HTML file.
> **Note:** The warning and chat icons were originally found on [iconfinder.com](https://www.iconfinder.com/), and designed by [Nazarrudin Ansyari](https://www.iconfinder.com/nazarr) β Thanks! (The actual icon pages were since moved or removed.)
2. Next, find the CSS inside your HTML file. We'll make a few changes to make way for the icons. First, update the `.msgBox` width from:
```css
width: 200px;
```
to
```css
width: 242px;
```
3. Next, add the following lines inside the `.msgBox p { }` rule:
```css
padding-left: 82px;
background-position: 25px center;
background-repeat: no-repeat;
```
4. Now we need to add code to our `displayMessage()` function to handle displaying the icons. Add the following block just above the closing curly brace (`}`) of your function:
```js
if (msgType === "warning") {
msg.style.backgroundImage = "url(icons/warning.png)";
panel.style.backgroundColor = "red";
} else if (msgType === "chat") {
msg.style.backgroundImage = "url(icons/chat.png)";
panel.style.backgroundColor = "aqua";
} else {
msg.style.paddingLeft = "20px";
}
```
Here, if the `msgType` parameter is set as `'warning'`, the warning icon is displayed and the panel's background color is set to red. If it is set to `'chat'`, the chat icon is displayed and the panel's background color is set to aqua blue. If the `msgType` parameter is not set at all (or to something different), then the `else { }` part of the code comes into play, and the paragraph is given default padding and no icon, with no background panel color set either. This provides a default state if no `msgType` parameter is provided, meaning that it is an optional parameter!
5. Let's test out our updated function, try updating the `displayMessage()` call from this:
```js
displayMessage("Woo, this is a different message!");
```
to one of these:
```js
displayMessage("Your inbox is almost full β delete some mails", "warning");
displayMessage("Brian: Hi there, how are you today?", "chat");
```
You can see how useful our (now not so) little function is becoming.
> **Note:** If you have trouble getting the example to work, feel free to check your code against the [finished version on GitHub](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/functions/function-stage-4.html) ([see it running live](https://mdn.github.io/learning-area/javascript/building-blocks/functions/function-stage-4.html) also), or ask us for help.
## 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: Functions](/en-US/docs/Learn/JavaScript/Building_blocks/Test_your_skills:_Functions). These tests require skills that are covered in the next article, so you might want to read that first before trying the test.
## Conclusion
Congratulations on reaching the end! This article took you through the entire process of building up a practical custom function, which with a bit more work could be transplanted into a real project. In the next article, we'll wrap up functions by explaining another essential related concept β return values.
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Functions","Learn/JavaScript/Building_blocks/Return_values", "Learn/JavaScript/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/functions/index.md | ---
title: Functions β reusable blocks of code
slug: Learn/JavaScript/Building_blocks/Functions
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Looping_code","Learn/JavaScript/Building_blocks/Build_your_own_function", "Learn/JavaScript/Building_blocks")}}
Another essential concept in coding is **functions**, which allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command β rather than having to type out the same code multiple times. In this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML, CSS, and
<a href="/en-US/docs/Learn/JavaScript/First_steps"
>JavaScript first steps</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the fundamental concepts behind JavaScript functions.
</td>
</tr>
</tbody>
</table>
## Where do I find functions?
In JavaScript, you'll find functions everywhere. In fact, we've been using functions all the way through the course so far; we've just not been talking about them very much. Now is the time, however, for us to start talking about functions explicitly, and really exploring their syntax.
Pretty much anytime you make use of a JavaScript structure that features a pair of parentheses β `()` β and you're **not** using a common built-in language structure like a [for loop](/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#the_standard_for_loop), [while or do...while loop](/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#while_and_do_..._while), or [if...else statement](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#if...else_statements), you are making use of a function.
## Built-in browser functions
We've used functions built into the browser a lot in this course.
Every time we manipulated a text string, for example:
```js
const myText = "I am a string";
const newString = myText.replace("string", "sausage");
console.log(newString);
// the replace() string function takes a source string,
// and a target string and replaces the source string,
// with the target string, and returns the newly formed string
```
Or every time we manipulated an array:
```js
const myArray = ["I", "love", "chocolate", "frogs"];
const madeAString = myArray.join(" ");
console.log(madeAString);
// the join() function takes an array, joins
// all the array items together into a single
// string, and returns this new string
```
Or every time we generate a random number:
```js
const myNumber = Math.random();
// the random() function generates a random number between
// 0 and up to but not including 1, and returns that number
```
We were using a _function_!
> **Note:** Feel free to enter these lines into your browser's JavaScript console to re-familiarize yourself with their functionality, if needed.
The JavaScript language has many built-in functions to allow you to do useful things without having to write all that code yourself. In fact, some of the code you are calling when you **invoke** (a fancy word for run, or execute) a built-in browser function couldn't be written in JavaScript β many of these functions are calling parts of the background browser code, which is written largely in low-level system languages like C++, not web languages like JavaScript.
Bear in mind that some built-in browser functions are not part of the core JavaScript language β some are defined as part of browser APIs, which build on top of the default language to provide even more functionality (refer to [this early section of our course](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#so_what_can_it_really_do) for more descriptions). We'll look at using browser APIs in more detail in a later module.
## Functions versus methods
**Functions** that are part of objects are called **methods**. You don't need to learn about the inner workings of structured JavaScript objects yet β you can wait until our later module that will teach you all about the inner workings of objects, and how to create your own. For now, we just wanted to clear up any possible confusion about method versus function β you are likely to meet both terms as you look at the available related resources across the Web.
The built-in code we've made use of so far comes in both forms: **functions** and **methods.** You can check the full list of the built-in functions, as well as the built-in objects and their corresponding methods [here](/en-US/docs/Web/JavaScript/Reference/Global_Objects).
You've also seen a lot of **custom functions** in the course so far β functions defined in your code, not inside the browser. Anytime you saw a custom name with parentheses straight after it, you were using a custom function. In our [random-canvas-circles.html](https://mdn.github.io/learning-area/javascript/building-blocks/loops/random-canvas-circles.html) example (see also the full [source code](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/loops/random-canvas-circles.html)) from our [loops article](/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code), we included a custom `draw()` function that looked like this:
```js
function draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (let i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
ctx.fill();
}
}
```
This function draws 100 random circles inside a {{htmlelement("canvas")}} element. Every time we want to do that, we can just invoke the function with this:
```js
draw();
```
rather than having to write all that code out again every time we want to repeat it. Functions can contain whatever code you like β you can even call other functions from inside functions. The above function for example calls the `random()` function three times, which is defined by the following code:
```js
function random(number) {
return Math.floor(Math.random() * number);
}
```
We needed this function because the browser's built-in [Math.random()](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) function only generates a random decimal number between 0 and 1. We wanted a random whole number between 0 and a specified number.
## Invoking functions
You are probably clear on this by now, but just in case, to actually use a function after it has been defined, you've got to run β or invoke β it. This is done by including the name of the function in the code somewhere, followed by parentheses.
```js
function myFunction() {
alert("hello");
}
myFunction();
// calls the function once
```
> **Note:** This form of creating a function is also known as _function declaration_. It is always hoisted so that you can call the function above the function definition and it will work fine.
## Function parameters
Some functions require **parameters** to be specified when you are invoking them β these are values that need to be included inside the function parentheses, which it needs to do its job properly.
> **Note:** Parameters are sometimes called arguments, properties, or even attributes.
As an example, the browser's built-in [Math.random()](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) function doesn't require any parameters. When called, it always returns a random number between 0 and 1:
```js
const myNumber = Math.random();
```
The browser's built-in string [replace()](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) function however needs two parameters β the substring to find in the main string, and the substring to replace that string with:
```js
const myText = "I am a string";
const newString = myText.replace("string", "sausage");
```
> **Note:** When you need to specify multiple parameters, they are separated by commas.
### Optional parameters
Sometimes parameters are optional β you don't have to specify them. If you don't, the function will generally adopt some kind of default behavior. As an example, the array [join()](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) function's parameter is optional:
```js
const myArray = ["I", "love", "chocolate", "frogs"];
const madeAString = myArray.join(" ");
console.log(madeAString);
// returns 'I love chocolate frogs'
const madeAnotherString = myArray.join();
console.log(madeAnotherString);
// returns 'I,love,chocolate,frogs'
```
If no parameter is included to specify a joining/delimiting character, a comma is used by default.
### Default parameters
If you're writing a function and want to support optional parameters, you can specify default values by adding `=` after the name of the parameter, followed by the default value:
```js
function hello(name = "Chris") {
console.log(`Hello ${name}!`);
}
hello("Ari"); // Hello Ari!
hello(); // Hello Chris!
```
## Anonymous functions and arrow functions
So far we have just created a function like so:
```js
function myFunction() {
alert("hello");
}
```
But you can also create a function that doesn't have a name:
```js
(function () {
alert("hello");
});
```
This is called an **anonymous function**, because it has no name. You'll often see anonymous functions when a function expects to receive another function as a parameter. In this case, the function parameter is often passed as an anonymous function.
> **Note:** This form of creating a function is also known as _function expression_. Unlike function declarations, function expressions are not hoisted.
### Anonymous function example
For example, let's say you want to run some code when the user types into a text box. To do this you can call the {{domxref("EventTarget/addEventListener", "addEventListener()")}} function of the text box. This function expects you to pass it (at least) two parameters:
- the name of the event to listen for, which in this case is {{domxref("Element/keydown_event", "keydown")}}
- a function to run when the event happens.
When the user presses a key, the browser will call the function you provided, and will pass it a parameter containing information about this event, including the particular key that the user pressed:
```js
function logKey(event) {
console.log(`You pressed "${event.key}".`);
}
textBox.addEventListener("keydown", logKey);
```
Instead of defining a separate `logKey()` function, you can pass an anonymous function into `addEventListener()`:
```js
textBox.addEventListener("keydown", function (event) {
console.log(`You pressed "${event.key}".`);
});
```
### Arrow functions
If you pass an anonymous function like this, there's an alternative form you can use, called an **arrow function**. Instead of `function(event)`, you write `(event) =>`:
```js
textBox.addEventListener("keydown", (event) => {
console.log(`You pressed "${event.key}".`);
});
```
If the function only takes one parameter, you can omit the parentheses around the parameter:
```js-nolint
textBox.addEventListener("keydown", event => {
console.log(`You pressed "${event.key}".`);
});
```
Finally, if your function contains only one line that's a `return` statement, you can also omit the braces and the `return` keyword and implicitly return the expression. In the following example, we're using the {{jsxref("Array.prototype.map()","map()")}} method of `Array` to double every value in the original array:
```js-nolint
const originals = [1, 2, 3];
const doubled = originals.map(item => item * 2);
console.log(doubled); // [2, 4, 6]
```
The `map()` method takes each item in the array in turn, passing it into the given function. It then takes the value returned by that function and adds it to a new array.
So in the example above, `item => item * 2` is the arrow function equivalent of:
```js
function doubleItem(item) {
return item * 2;
}
```
You can use the same concise syntax to rewrite the `addEventListener` example.
```js
textBox.addEventListener("keydown", (event) =>
console.log(`You pressed "${event.key}".`),
);
```
In this case, the value of `console.log()`, which is `undefined`, is implicitly returned from the callback function.
We recommend that you use arrow functions, as they can make your code shorter and more readable. To learn more, see the [section on arrow functions in the JavaScript guide](/en-US/docs/Web/JavaScript/Guide/Functions#arrow_functions), and our [reference page on arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
> **Note:** There are some subtle differences between arrow functions and normal functions. They're outside the scope of this introductory guide and are unlikely to make a difference in the cases we've discussed here. To learn more, see the [arrow function reference documentation](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
### Arrow function live sample
Here's a complete working example of the "keydown" example we discussed above:
The HTML:
```html
<input id="textBox" type="text" />
<div id="output"></div>
```
The JavaScript:
```js
const textBox = document.querySelector("#textBox");
const output = document.querySelector("#output");
textBox.addEventListener("keydown", (event) => {
output.textContent = `You pressed "${event.key}".`;
});
```
```css hidden
div {
margin: 0.5rem 0;
}
```
The result - try typing into the text box and see the output:
{{EmbedLiveSample("Arrow function live sample", 100, 100)}}
## Function scope and conflicts
Let's talk a bit about {{glossary("scope")}} β a very important concept when dealing with functions. When you create a function, the variables and other things defined inside the function are inside their own separate **scope**, meaning that they are locked away in their own separate compartments, unreachable from code outside the functions.
The top-level outside all your functions is called the **global scope**. Values defined in the global scope are accessible from everywhere in the code.
JavaScript is set up like this for various reasons β but mainly because of security and organization. Sometimes you don't want variables to be accessible from everywhere in the code β external scripts that you call in from elsewhere could start to mess with your code and cause problems because they happen to be using the same variable names as other parts of the code, causing conflicts. This might be done maliciously, or just by accident.
For example, say you have an HTML file that is calling in two external JavaScript files, and both of them have a variable and a function defined that use the same name:
```html
<!-- Excerpt from my HTML -->
<script src="first.js"></script>
<script src="second.js"></script>
<script>
greeting();
</script>
```
```js
// first.js
const name = "Chris";
function greeting() {
alert(`Hello ${name}: welcome to our company.`);
}
```
```js
// second.js
const name = "Zaptec";
function greeting() {
alert(`Our company is called ${name}.`);
}
```
Both functions you want to call are called `greeting()`, but you can only ever access the `first.js` file's `greeting()` function (the second one is ignored). In addition, an error results when attempting (in the `second.js` file) to assign a new value to the `name` variable β because it was already declared with `const`, and so can't be reassigned.
> **Note:** You can see this example [running live on GitHub](https://mdn.github.io/learning-area/javascript/building-blocks/functions/conflict.html) (see also the [source code](https://github.com/mdn/learning-area/tree/main/javascript/building-blocks/functions)).
Keeping parts of your code locked away in functions avoids such problems, and is considered the best practice.
It is a bit like a zoo. The lions, zebras, tigers, and penguins are kept in their own enclosures and only have access to the things inside their enclosures β in the same manner as the function scopes. If they were able to get into other enclosures, problems would occur. At best, different animals would feel really uncomfortable inside unfamiliar habitats β a lion or tiger would feel terrible inside the penguins' watery, icy domain. At worst, the lions and tigers might try to eat the penguins!

The zoo keeper is like the global scope β they have the keys to access every enclosure, restock food, tend to sick animals, etc.
### Active learning: Playing with scope
Let's look at a real example to demonstrate scoping.
1. First, make a local copy of our [function-scope.html](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/functions/function-scope.html) example. This contains two functions called `a()` and `b()`, and three variables β `x`, `y`, and `z` β two of which are defined inside the functions, and one in the global scope. It also contains a third function called `output()`, which takes a single parameter and outputs it in a paragraph on the page.
2. Open the example up in a browser and in your text editor.
3. Open the JavaScript console in your browser developer tools. In the JavaScript console, enter the following command:
```js
output(x);
```
You should see the value of variable `x` printed to the browser viewport.
4. Now try entering the following in your console
```js
output(y);
output(z);
```
Both of these should throw an error into the console along the lines of "[ReferenceError: y is not defined](/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined)". Why is that? Because of function scope, `y` and `z` are locked inside the `a()` and `b()` functions, so `output()` can't access them when called from the global scope.
5. However, what about when it's called from inside another function? Try editing `a()` and `b()` so they look like this:
```js
function a() {
const y = 2;
output(y);
}
function b() {
const z = 3;
output(z);
}
```
Save the code and reload it in your browser, then try calling the `a()` and `b()` functions from the JavaScript console:
```js
a();
b();
```
You should see the `y` and `z` values printed in the browser viewport. This works fine, as the `output()` function is being called inside the other functions β in the same scope as the variables it is printing are defined in, in each case. `output()` itself is available from anywhere, as it is defined in the global scope.
6. Now try updating your code like this:
```js
function a() {
const y = 2;
output(x);
}
function b() {
const z = 3;
output(x);
}
```
7. Save and reload again, and try this again in your JavaScript console:
```js
a();
b();
```
Both the `a()` and `b()` call should print the value of x to the browser viewport. These work fine because even though the `output()` calls are not in the same scope as `x` is defined in, `x` is a global variable so is available inside all code, everywhere.
8. Finally, try updating your code like this:
```js
function a() {
const y = 2;
output(z);
}
function b() {
const z = 3;
output(y);
}
```
9. Save and reload again, and try this again in your JavaScript console:
```js
a();
b();
```
This time the `a()` and `b()` calls will throw that annoying [ReferenceError: _variable name_ is not defined](/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined) error into the console β this is because the `output()` calls and the variables they are trying to print are not in the same function scopes β the variables are effectively invisible to those function calls.
> **Note:** The same scoping rules do not apply to loop (e.g. `for() { }`) and conditional blocks (e.g. `if () { }`) β they look very similar, but they are not the same thing! Take care not to get these confused.
> **Note:** The [ReferenceError: "x" is not defined](/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined) error is one of the most common you'll encounter. If you get this error and you are sure that you have defined the variable in question, check what scope it is in.
## 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: Functions](/en-US/docs/Learn/JavaScript/Building_blocks/Test_your_skills:_Functions). These tests require skills that are covered in the next two articles, so you might want to read those first before trying them.
## Conclusion
This article has explored the fundamental concepts behind functions, paving the way for the next one in which we get practical and take you through the steps to building up your own custom function.
## See also
- [Functions detailed guide](/en-US/docs/Web/JavaScript/Guide/Functions) β covers some advanced features not included here.
- [Functions reference](/en-US/docs/Web/JavaScript/Reference/Functions)
- [Default parameters](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters), [Arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) β advanced concept references
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Looping_code","Learn/JavaScript/Building_blocks/Build_your_own_function", "Learn/JavaScript/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/return_values/index.md | ---
title: Function return values
slug: Learn/JavaScript/Building_blocks/Return_values
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Build_your_own_function","Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}
There's one last essential concept about functions for us to discuss β return values. Some functions don't return a significant value, but others do. It's important to understand what their values are, how to use them in your code, and how to make functions return useful values. We'll cover all of these below.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
A basic understanding of HTML and CSS,
<a href="/en-US/docs/Learn/JavaScript/First_steps"
>JavaScript first steps</a
>,
<a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions"
>Functions β reusable blocks of code</a
>.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand function return values, and how to make use of them.
</td>
</tr>
</tbody>
</table>
## What are return values?
**Return values** are just what they sound like β the values that a function returns when it completes. You've already met return values several times, although you may not have thought about them explicitly.
Let's return to a familiar example (from a [previous article](/en-US/docs/Learn/JavaScript/Building_blocks/Functions#built-in_browser_functions) in this series):
```js
const myText = "The weather is cold";
const newString = myText.replace("cold", "warm");
console.log(newString); // Should print "The weather is warm"
// the replace() string function takes a string,
// replaces one substring with another, and returns
// a new string with the replacement made
```
The [`replace()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) function is invoked on the `myText` string, and is passed two parameters:
- The substring to find ('cold')
- The string to replace it with ('warm')
When the function completes (finishes running), it returns a value, which is a new string with the replacement made. In the code above, the result of this return value is saved in the variable `newString`.
If you look at the [`replace()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) function MDN reference page, you'll see a section called [return value](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#return_value). It is very useful to know and understand what values are returned by functions, so we try to include this information wherever possible.
Some functions don't return any value. (In these cases, our reference pages list the return value as [`void`](/en-US/docs/Web/JavaScript/Reference/Operators/void) or [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).) For example, in the [`displayMessage()`](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/functions/function-stage-4.html#L50) function we built in the previous article, no specific value is returned when the function is invoked. It just makes a box appear somewhere on the screen β that's it!
Generally, a return value is used where the function is an intermediate step in a calculation of some kind. You want to get to a final result, which involves some values that need to be calculated by a function. After the function calculates the value, it can return the result so it can be stored in a variable; and you can use this variable in the next stage of the calculation.
### Using return values in your own functions
To return a value from a custom function, you need to use the [return](/en-US/docs/Web/JavaScript/Reference/Statements/return) keyword. We saw this in action recently in our [random-canvas-circles.html](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/loops/random-canvas-circles.html) example. Our `draw()` function draws 100 random circles somewhere on an HTML {{htmlelement("canvas")}}:
```js
function draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (let i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
ctx.fill();
}
}
```
Inside each loop iteration, three calls are made to the `random()` function, to generate a random value for the current circle's _x-coordinate_, _y-coordinate_, and _radius_, respectively. The `random()` function takes one parameter β a whole number β and returns a whole random number between `0` and that number. It looks like this:
```js
function random(number) {
return Math.floor(Math.random() * number);
}
```
This could be written as follows:
```js
function random(number) {
const result = Math.floor(Math.random() * number);
return result;
}
```
But the first version is quicker to write, and more compact.
We are returning the result of the calculation `Math.floor(Math.random() * number)` each time the function is called. This return value appears at the point the function was called, and the code continues.
So when you execute the following:
```js
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
```
If the three `random()` calls return the values `500`, `200`, and `35`, respectively, the line would actually be run as if it were this:
```js
ctx.arc(500, 200, 35, 0, 2 * Math.PI);
```
The function calls on the line are run first, and their return values are substituted for the function calls, before the line itself is then executed.
## Active learning: our own return value function
Let's have a go at writing our own functions featuring return values.
1. Make a local copy of the [function-library.html](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/functions/function-library.html) file from GitHub. This is a simple HTML page containing a text {{htmlelement("input")}} field and a paragraph. There's also a {{htmlelement("script")}} element, in which we have stored a reference to both HTML elements in two variables. This page will allow you to enter a number into the text box, and display different numbers related to it below.
2. Add some useful functions to this `<script>` element below the two existing lines:
```js
function squared(num) {
return num * num;
}
function cubed(num) {
return num * num * num;
}
function factorial(num) {
if (num < 0) return undefined;
if (num === 0) return 1;
let x = num - 1;
while (x > 1) {
num *= x;
x--;
}
return num;
}
```
The `squared()` and `cubed()` functions are fairly obvious β they return the square or cube of the number that was given as a parameter. The `factorial()` function returns the [factorial](https://en.wikipedia.org/wiki/Factorial) of the given number.
3. Include a way to print out information about the number entered into the text input by adding the following event handler below the existing functions:
```js
input.addEventListener("change", () => {
const num = parseFloat(input.value);
if (isNaN(num)) {
para.textContent = "You need to enter a number!";
} else {
para.textContent = `${num} squared is ${squared(num)}. `;
para.textContent += `${num} cubed is ${cubed(num)}. `;
para.textContent += `${num} factorial is ${factorial(num)}. `;
}
});
```
4. Save your code, load it in a browser, and try it out.
Here are some explanations for the `addEventListener` function in step 3 above:
- By adding a listener to the `change` event, this function runs whenever the `change` event fires on the text input β that is when a new value is entered into the text `input`, and submitted (e.g., enter a value, then un-focus the input by pressing <kbd>Tab</kbd> or <kbd>Return</kbd>). When this anonymous function runs, the value in the `input` is stored in the `num` constant.
- The if statement prints an error message if the entered value is not a number. The condition checks if the expression `isNaN(num)` returns `true`. The [`isNaN()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN) function tests whether the `num` value is not a number β if so, it returns `true`, and if not, it returns `false`.
- If the condition returns `false`, the `num` value is a number and the function prints out a sentence inside the paragraph element that states the square, cube, and factorial values of the number. The sentence calls the `squared()`, `cubed()`, and `factorial()` functions to calculate the required values.
> **Note:** If you have trouble getting the example to work, check your code against the [finished version on GitHub](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/functions/function-library-finished.html) ([see it running live](https://mdn.github.io/learning-area/javascript/building-blocks/functions/function-library-finished.html) also), or ask us for help.
## Now it's your turn!
At this point, we'd like you to have a go at writing out a couple of functions of your own and adding them to the library. How about the square or cube root of the number? Or the circumference of a circle with a given radius?
Some extra function-related tips:
- Look at another example of writing _error handling_ into functions. It is generally a good idea to check that any necessary parameters are validated, and that any optional parameters have some kind of default value provided. This way, your program will be less likely to throw errors.
- Think about the idea of creating a _function library_. As you go further into your programming career, you'll start doing the same kinds of things over and over again. It is a good idea to create your own library of utility functions to do these sorts of things. You can copy them over to new code, or even just apply them to HTML pages wherever you need them.
## 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: Functions](/en-US/docs/Learn/JavaScript/Building_blocks/Test_your_skills:_Functions).
## Conclusion
So there we have it β functions are fun, very useful, and although there's a lot to talk about in regards to their syntax and functionality, they are fairly understandable.
If there is anything you didn't understand, feel free to read through the article again, or [contact us](/en-US/docs/Learn#contact_us) to ask for help.
## See also
- [Functions in-depth](/en-US/docs/Web/JavaScript/Reference/Functions) β a detailed guide covering more advanced functions-related information.
- [Callback functions in JavaScript](https://www.impressivewebs.com/callback-functions-javascript/) β a common JavaScript pattern is to pass a function into another function _as an argument_. It is then called inside the first function. This is a little beyond the scope of this course, but worth studying before too long.
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Build_your_own_function","Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/building_blocks | data/mdn-content/files/en-us/learn/javascript/building_blocks/test_your_skills_colon__functions/index.md | ---
title: "Test your skills: Functions"
slug: Learn/JavaScript/Building_blocks/Test_your_skills:_Functions
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [Functions β reusable blocks of code](/en-US/docs/Learn/JavaScript/Building_blocks/Functions), [Build your own function](/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function), and [Function return values](/en-US/docs/Learn/JavaScript/Building_blocks/Return_values) articles.
> **Note:** You can try solutions by downloading the code and putting it in an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
> If there is an error, it will be logged in the results panel on the page or into the browser's JavaScript console to help you.
>
> If you get stuck, you can reach out to us in one of our [communication channels](/en-US/docs/MDN/Community/Communication_channels).
## DOM manipulation: considered useful
Some of the questions below require you to write some [DOM](/en-US/docs/Glossary/DOM) manipulation code to complete them β such as creating new HTML elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page β all via JavaScript.
We haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what DOM APIs you need to successfully answer the questions. A good starting place is our [Manipulating documents](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents) tutorial.
## Functions 1
For the first task, you have to create a simple function β `chooseName()` β that prints a random name from the provided array (`names`) to the provided paragraph (`para`), and then run it once.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/building-blocks/tasks/functions/functions1.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/functions/functions1-download.html) to work in your own editor or in an online editor.
## Functions 2
For our second functions-related task, you need to create a function that draws a rectangle on the provided `<canvas>` (reference variable `canvas`, context available in `ctx`), based on the five provided input variables:
- `x` β the x coordinate of the rectangle.
- `y` β the y coordinate of the rectangle.
- `width` β the width of the rectangle.
- `height` β the height of the rectangle.
- `color` β the color of the rectangle.
You'll want to clear the canvas before drawing, so that when the code is updated in the case of the live version, you don't get lots of rectangles drawn on top of one another.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/building-blocks/tasks/functions/functions2.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/functions/functions2-download.html) to work in your own editor or in an online editor.
## Functions 3
In this task, you return to the problem posed in Task 1, with the aim of improving it. The three improvements we want you to make are:
1. Refactor the code that generates the random number into a separate function called `random()`, which takes as parameters two generic bounds that the random number should be between, and returns the result.
2. Update the `chooseName()` function so that it makes use of the random number function, takes the array to choose from as a parameter (making it more flexible), and returns the result.
3. Print the returned result into the paragraph (`para`)'s `textContent`.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/javascript/building-blocks/tasks/functions/functions3.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/functions/functions3-download.html) to work in your own editor or in an online editor.
## Functions 4
In this task, we have an array of names, and we're using {{jsxref("Array.filter()")}} to get an array of only names shorter than 5 characters. The filter is currently being passed a named function `isShort()` which checks the length of the name, returning `true` if the name is less than 5 characters long, and `false` otherwise.
We'd like you to change this into an arrow function. See how compact you can make it.
{{EmbedGHLiveSample("learning-area/javascript/building-blocks/tasks/functions/functions4.html", '100%', 400)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/tasks/functions/functions4-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/javascript | data/mdn-content/files/en-us/learn/javascript/asynchronous/index.md | ---
title: Asynchronous JavaScript
slug: Learn/JavaScript/Asynchronous
page-type: learn-module
---
{{LearnSidebar}}
In this module, we take a look at {{Glossary("asynchronous")}} {{Glossary("JavaScript")}}, why it is important, and how it can be used to effectively handle potential blocking operations, such as fetching resources from a 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
Asynchronous JavaScript is a fairly advanced topic, and you are advised to work through [JavaScript first steps](/en-US/docs/Learn/JavaScript/First_steps) and [JavaScript building blocks](/en-US/docs/Learn/JavaScript/Building_blocks) modules before attempting this.
> **Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you can try out (most of) the code examples in an online coding program such as [JSBin](https://jsbin.com/) or [Glitch](https://glitch.com).
## Guides
- [Introducing asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous/Introducing)
- : In this article, we'll learn about **synchronous** and **asynchronous** programming, why we often need to use asynchronous techniques, and the problems related to the way asynchronous functions have historically been implemented in JavaScript.
- [How to use promises](/en-US/docs/Learn/JavaScript/Asynchronous/Promises)
- : Here we'll introduce promises and show how to use promise-based APIs. We'll also introduce the `async` and `await` keywords.
- [Implementing a promise-based API](/en-US/docs/Learn/JavaScript/Asynchronous/Implementing_a_promise-based_API)
- : This article will outline how to implement your own promise-based API.
- [Introducing workers](/en-US/docs/Learn/JavaScript/Asynchronous/Introducing_workers)
- : Workers enable you to run certain tasks in a separate thread to keep your main code responsive. In this article, we'll rewrite a long-running synchronous function to use a worker.
## Assessments
- [Sequencing animations](/en-US/docs/Learn/JavaScript/Asynchronous/Sequencing_animations)
- : The assessment asks you to use promises to play a set of animations in a particular sequence.
## See also
- [Asynchronous Programming](https://eloquentjavascript.net/11_async.html) from the fantastic [Eloquent JavaScript](https://eloquentjavascript.net/) online book by Marijn Haverbeke.
| 0 |
data/mdn-content/files/en-us/learn/javascript/asynchronous | data/mdn-content/files/en-us/learn/javascript/asynchronous/sequencing_animations/index.md | ---
title: Sequencing animations
slug: Learn/JavaScript/Asynchronous/Sequencing_animations
page-type: learn-module-assessment
---
{{LearnSidebar}}{{PreviousMenu("Learn/JavaScript/Asynchronous/Introducing_workers", "Learn/JavaScript/Asynchronous")}}
In this assessment you'll update a page to play a series of animations in a sequence. To do this you'll use some of the techniques we learned in the [How to use Promises](/en-US/docs/Learn/JavaScript/Asynchronous/Promises) article.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A reasonable understanding of JavaScript
fundamentals, how to use promise-based APIs.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To test understanding of how to use promise-based APIs.</td>
</tr>
</tbody>
</table>
## Starting point
Make a local copy of the files at <https://github.com/mdn/learning-area/tree/main/javascript/asynchronous/sequencing-animations/start>. It contains four files:
- alice.svg
- index.html
- main.js
- style.css
The only file you'll need to edit is "main.js".
If you open "index.html" in a browser you'll see three images arranged diagonally:

The images are taken from our guide to [Using the Web Animations API](/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API).
> **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
We want to update this page so we apply an animation to all three images, one after the other. So when the first has finished we animate the second, and when the second has finished we animate the third.
The animation is already defined in "main.js": it just rotates the image and shrinks it until it disappears.
To give you more of an idea of how we want the page to work, [have a look at the finished example](https://mdn.github.io/learning-area/javascript/asynchronous/sequencing-animations/finished/). Note that the animations only run once: to see them run again, reload the page.
## Steps to complete
### Animating the first image
We're using the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) to animate the images, specifically the {{domxref("Element/animate", "element.animate()")}} method.
Update "main.js" to add a call to `alice1.animate()`, like this:
```js
const aliceTumbling = [
{ transform: "rotate(0) scale(1)" },
{ transform: "rotate(360deg) scale(0)" },
];
const aliceTiming = {
duration: 2000,
iterations: 1,
fill: "forwards",
};
const alice1 = document.querySelector("#alice1");
const alice2 = document.querySelector("#alice2");
const alice3 = document.querySelector("#alice3");
alice1.animate(aliceTumbling, aliceTiming);
```
Reload the page, and you should see the first image rotate and shrink.
### Animating all the images
Next, we want to animate `alice2` when `alice1` has finished, and `alice3` when `alice2` has finished.
The `animate()` method returns an {{domxref("Animation")}} object. This object has a `finished` property, which is a `Promise` that is fulfilled when the animation has finished playing. So we can use this promise to know when to start the next animation.
We'd like you to try a few different ways to implement this, to reinforce different ways of using promises.
1. First, implement something that works, but has the promise version of the "callback hell" problem we saw in our [discussion of using callbacks](/en-US/docs/Learn/JavaScript/Asynchronous/Introducing#callbacks).
2. Next, implement it as a [promise chain](/en-US/docs/Learn/JavaScript/Asynchronous/Promises#chaining_promises). Note that there are a few different ways you can write this, because of the different forms you can use for an [arrow function](/en-US/docs/Learn/JavaScript/Building_blocks/Functions#arrow_functions). Try some different forms. Which is the most concise? Which do you find the most readable?
3. Finally, implement it using [`async` and `await`](/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await).
Remember that `element.animate()` does _not_ return a `Promise`: it returns an `Animation` object with a `finished` property that is a `Promise`.
{{PreviousMenu("Learn/JavaScript/Asynchronous/Introducing_workers", "Learn/JavaScript/Asynchronous")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/asynchronous | data/mdn-content/files/en-us/learn/javascript/asynchronous/promises/index.md | ---
title: How to use promises
slug: Learn/JavaScript/Asynchronous/Promises
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Introducing", "Learn/JavaScript/Asynchronous/Implementing_a_promise-based_API", "Learn/JavaScript/Asynchronous")}}
**Promises** are the foundation of asynchronous programming in modern JavaScript. A promise is an object returned by an asynchronous function, which represents the current state of the operation. At the time the promise is returned to the caller, the operation often isn't finished, but the promise object provides methods to handle the eventual success or failure of the operation.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A reasonable understanding of JavaScript
fundamentals, including event handling.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To understand how to use promises in JavaScript.</td>
</tr>
</tbody>
</table>
In the [previous article](/en-US/docs/Learn/JavaScript/Asynchronous/Introducing), we talked about the use of callbacks to implement asynchronous functions. With that design, you call the asynchronous function, passing in your callback function. The function returns immediately and calls your callback when the operation is finished.
With a promise-based API, the asynchronous function starts the operation and returns a {{jsxref("Promise")}} object. You can then attach handlers to this promise object, and these handlers will be executed when the operation has succeeded or failed.
## Using the fetch() API
> **Note:** In this article, we will explore promises by copying code samples from the page into your browser's JavaScript console. To set this up:
>
> 1. open a browser tab and visit <https://example.org>
> 2. in that tab, open the JavaScript console in your [browser's developer tools](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools)
> 3. when we show an example, copy it into the console. You will have to reload the page each time you enter a new example, or the console will complain that you have redeclared `fetchPromise`.
In this example, we'll download the JSON file from <https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json>, and log some information about it.
To do this, we'll make an **HTTP request** to the server. In an HTTP request, we send a request message to a remote server, and it sends us back a response. In this case, we'll send a request to get a JSON file from the server. Remember in the last article, where we made HTTP requests using the {{domxref("XMLHttpRequest")}} API? Well, in this article, we'll use the {{domxref("fetch", "fetch()")}} API, which is the modern, promise-based replacement for `XMLHttpRequest`.
Copy this into your browser's JavaScript console:
```js
const fetchPromise = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
console.log(fetchPromise);
fetchPromise.then((response) => {
console.log(`Received response: ${response.status}`);
});
console.log("Started requestβ¦");
```
Here we are:
1. calling the `fetch()` API, and assigning the return value to the `fetchPromise` variable
2. immediately after, logging the `fetchPromise` variable. This should output something like: `Promise { <state>: "pending" }`, telling us that we have a `Promise` object, and it has a `state` whose value is `"pending"`. The `"pending"` state means that the fetch operation is still going on.
3. passing a handler function into the Promise's **`then()`** method. When (and if) the fetch operation succeeds, the promise will call our handler, passing in a {{domxref("Response")}} object, which contains the server's response.
4. logging a message that we have started the request.
The complete output should be something like:
```plain
Promise { <state>: "pending" }
Started requestβ¦
Received response: 200
```
Note that `Started requestβ¦` is logged before we receive the response. Unlike a synchronous function, `fetch()` returns while the request is still going on, enabling our program to stay responsive. The response shows the `200` (OK) [status code](/en-US/docs/Web/HTTP/Status), meaning that our request succeeded.
This probably seems a lot like the example in the last article, where we added event handlers to the {{domxref("XMLHttpRequest")}} object. Instead of that, we're passing a handler into the `then()` method of the returned promise.
## Chaining promises
With the `fetch()` API, once you get a `Response` object, you need to call another function to get the response data. In this case, we want to get the response data as JSON, so we would call the {{domxref("Response/json", "json()")}} method of the `Response` object. It turns out that `json()` is also asynchronous. So this is a case where we have to call two successive asynchronous functions.
Try this:
```js
const fetchPromise = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
fetchPromise.then((response) => {
const jsonPromise = response.json();
jsonPromise.then((data) => {
console.log(data[0].name);
});
});
```
In this example, as before, we add a `then()` handler to the promise returned by `fetch()`. But this time, our handler calls `response.json()`, and then passes a new `then()` handler into the promise returned by `response.json()`.
This should log "baked beans" (the name of the first product listed in "products.json").
But wait! Remember the last article, where we said that by calling a callback inside another callback, we got successively more nested levels of code? And we said that this "callback hell" made our code hard to understand? Isn't this just the same, only with `then()` calls?
It is, of course. But the elegant feature of promises is that _`then()` itself returns a promise, which will be completed with the result of the function passed to it_. This means that we can (and certainly should) rewrite the above code like this:
```js
const fetchPromise = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
fetchPromise
.then((response) => response.json())
.then((data) => {
console.log(data[0].name);
});
```
Instead of calling the second `then()` inside the handler for the first `then()`, we can _return_ the promise returned by `json()`, and call the second `then()` on that return value. This is called **promise chaining** and means we can avoid ever-increasing levels of indentation when we need to make consecutive asynchronous function calls.
Before we move on to the next step, there's one more piece to add. We need to check that the server accepted and was able to handle the request, before we try to read it. We'll do this by checking the status code in the response and throwing an error if it wasn't "OK":
```js
const fetchPromise = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
fetchPromise
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log(data[0].name);
});
```
## Catching errors
This brings us to the last piece: how do we handle errors? The `fetch()` API can throw an error for many reasons (for example, because there was no network connectivity or the URL was malformed in some way) and we are throwing an error ourselves if the server returned an error.
In the last article, we saw that error handling can get very difficult with nested callbacks, making us handle errors at every nesting level.
To support error handling, `Promise` objects provide a {{jsxref("Promise/catch", "catch()")}} method. This is a lot like `then()`: you call it and pass in a handler function. However, while the handler passed to `then()` is called when the asynchronous operation _succeeds_, the handler passed to `catch()` is called when the asynchronous operation _fails_.
If you add `catch()` to the end of a promise chain, then it will be called when any of the asynchronous function calls fail. So you can implement an operation as several consecutive asynchronous function calls, and have a single place to handle all errors.
Try this version of our `fetch()` code. We've added an error handler using `catch()`, and also modified the URL so the request will fail.
```js
const fetchPromise = fetch(
"bad-scheme://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
fetchPromise
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log(data[0].name);
})
.catch((error) => {
console.error(`Could not get products: ${error}`);
});
```
Try running this version: you should see the error logged by our `catch()` handler.
## Promise terminology
Promises come with some quite specific terminology that it's worth getting clear about.
First, a promise can be in one of three states:
- **pending**: the promise has been created, and the asynchronous function it's associated with has not succeeded or failed yet. This is the state your promise is in when it's returned from a call to `fetch()`, and the request is still being made.
- **fulfilled**: the asynchronous function has succeeded. When a promise is fulfilled, its `then()` handler is called.
- **rejected**: the asynchronous function has failed. When a promise is rejected, its `catch()` handler is called.
Note that what "succeeded" or "failed" means here is up to the API in question. For example, `fetch()` rejects the returned promise if (among other reasons) a network error prevented the request being sent, but fulfills the promise if the server sent a response, even if the response was an error like [404 Not Found](/en-US/docs/Web/HTTP/Status/404).
Sometimes, we use the term **settled** to cover both **fulfilled** and **rejected**.
A promise is **resolved** if it is settled, or if it has been "locked in" to follow the state of another promise.
The article [Let's talk about how to talk about promises](https://thenewtoys.dev/blog/2021/02/08/lets-talk-about-how-to-talk-about-promises/) gives a great explanation of the details of this terminology.
## Combining multiple promises
The promise chain is what you need when your operation consists of several asynchronous functions, and you need each one to complete before starting the next one. But there are other ways you might need to combine asynchronous function calls, and the `Promise` API provides some helpers for them.
Sometimes, you need all the promises to be fulfilled, but they don't depend on each other. In a case like that, it's much more efficient to start them all off together, then be notified when they have all fulfilled. The {{jsxref("Promise/all", "Promise.all()")}} method is what you need here. It takes an array of promises and returns a single promise.
The promise returned by `Promise.all()` is:
- fulfilled when and if _all_ the promises in the array are fulfilled. In this case, the `then()` handler is called with an array of all the responses, in the same order that the promises were passed into `all()`.
- rejected when and if _any_ of the promises in the array are rejected. In this case, the `catch()` handler is called with the error thrown by the promise that rejected.
For example:
```js
const fetchPromise1 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
const fetchPromise2 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/not-found",
);
const fetchPromise3 = fetch(
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json",
);
Promise.all([fetchPromise1, fetchPromise2, fetchPromise3])
.then((responses) => {
for (const response of responses) {
console.log(`${response.url}: ${response.status}`);
}
})
.catch((error) => {
console.error(`Failed to fetch: ${error}`);
});
```
Here, we're making three `fetch()` requests to three different URLs. If they all succeed, we will log the response status of each one. If any of them fail, then we're logging the failure.
With the URLs we've provided, all the requests should be fulfilled, although for the second, the server will return `404` (Not Found) instead of `200` (OK) because the requested file does not exist. So the output should be:
```plain
https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json: 200
https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/not-found: 404
https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json: 200
```
If we try the same code with a badly formed URL, like this:
```js
const fetchPromise1 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
const fetchPromise2 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/not-found",
);
const fetchPromise3 = fetch(
"bad-scheme://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json",
);
Promise.all([fetchPromise1, fetchPromise2, fetchPromise3])
.then((responses) => {
for (const response of responses) {
console.log(`${response.url}: ${response.status}`);
}
})
.catch((error) => {
console.error(`Failed to fetch: ${error}`);
});
```
Then we can expect the `catch()` handler to run, and we should see something like:
```plain
Failed to fetch: TypeError: Failed to fetch
```
Sometimes, you might need any one of a set of promises to be fulfilled, and don't care which one. In that case, you want {{jsxref("Promise/any", "Promise.any()")}}. This is like `Promise.all()`, except that it is fulfilled as soon as any of the array of promises is fulfilled, or rejected if all of them are rejected:
```js
const fetchPromise1 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
const fetchPromise2 = fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/not-found",
);
const fetchPromise3 = fetch(
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json",
);
Promise.any([fetchPromise1, fetchPromise2, fetchPromise3])
.then((response) => {
console.log(`${response.url}: ${response.status}`);
})
.catch((error) => {
console.error(`Failed to fetch: ${error}`);
});
```
Note that in this case we can't predict which fetch request will complete first.
These are just two of the extra `Promise` functions for combining multiple promises. To learn about the rest, see the {{jsxref("Promise")}} reference documentation.
## async and await
The {{jsxref("Statements/async_function", "async")}} keyword gives you a simpler way to work with asynchronous promise-based code. Adding `async` at the start of a function makes it an async function:
```js
async function myFunction() {
// This is an async function
}
```
Inside an async function, you can use the `await` keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
This enables you to write code that uses asynchronous functions but looks like synchronous code. For example, we could use it to rewrite our fetch example:
```js
async function fetchProducts() {
try {
// after this line, our function will wait for the `fetch()` call to be settled
// the `fetch()` call will either return a Response or throw an error
const response = await fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
// after this line, our function will wait for the `response.json()` call to be settled
// the `response.json()` call will either return the parsed JSON object or throw an error
const data = await response.json();
console.log(data[0].name);
} catch (error) {
console.error(`Could not get products: ${error}`);
}
}
fetchProducts();
```
Here, we are calling `await fetch()`, and instead of getting a `Promise`, our caller gets back a fully complete `Response` object, just as if `fetch()` were a synchronous function!
We can even use a `try...catch` block for error handling, exactly as we would if the code were synchronous.
Note though that async functions always return a promise, so you can't do something like:
```js example-bad
async function fetchProducts() {
try {
const response = await fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error(`Could not get products: ${error}`);
}
}
const promise = fetchProducts();
console.log(promise[0].name); // "promise" is a Promise object, so this will not work
```
Instead, you'd need to do something like:
```js
async function fetchProducts() {
try {
const response = await fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error(`Could not get products: ${error}`);
}
}
const promise = fetchProducts();
promise.then((data) => console.log(data[0].name));
```
Also, note that you can only use `await` inside an `async` function, unless your code is in a [JavaScript module](/en-US/docs/Web/JavaScript/Guide/Modules). That means you can't do this in a normal script:
```js
try {
// using await outside an async function is only allowed in a module
const response = await fetch(
"https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
console.log(data[0].name);
} catch (error) {
console.error(`Could not get products: ${error}`);
}
```
You'll probably use `async` functions a lot where you might otherwise use promise chains, and they make working with promises much more intuitive.
Keep in mind that just like a promise chain, `await` forces asynchronous operations to be completed in series. This is necessary if the result of the next operation depends on the result of the last one, but if that's not the case then something like `Promise.all()` will be more performant.
## Conclusion
Promises are the foundation of asynchronous programming in modern JavaScript. They make it easier to express and reason about sequences of asynchronous operations without deeply nested callbacks, and they support a style of error handling that is similar to the synchronous `try...catch` statement.
The `async` and `await` keywords make it easier to build an operation from a series of consecutive asynchronous function calls, avoiding the need to create explicit promise chains, and allowing you to write code that looks just like synchronous code.
Promises work in the latest versions of all modern browsers; the only place where promise support will be a problem is in Opera Mini and IE11 and earlier versions.
We didn't touch on all features of promises in this article, just the most interesting and useful ones. As you start to learn more about promises, you'll come across more features and techniques.
Many modern Web APIs are promise-based, including [WebRTC](/en-US/docs/Web/API/WebRTC_API), [Web Audio API](/en-US/docs/Web/API/Web_Audio_API), [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API), and many more.
## See also
- [`Promise()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
- [Using promises](/en-US/docs/Web/JavaScript/Guide/Using_promises)
- [We have a problem with promises](https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html) by Nolan Lawson
- [Let's talk about how to talk about promises](https://thenewtoys.dev/blog/2021/02/08/lets-talk-about-how-to-talk-about-promises/)
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Introducing", "Learn/JavaScript/Asynchronous/Implementing_a_promise-based_API", "Learn/JavaScript/Asynchronous")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/asynchronous | data/mdn-content/files/en-us/learn/javascript/asynchronous/introducing_workers/index.md | ---
title: Introducing workers
slug: Learn/JavaScript/Asynchronous/Introducing_workers
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Implementing_a_promise-based_API", "Learn/JavaScript/Asynchronous/Sequencing_animations", "Learn/JavaScript/Asynchronous")}}
In this final article in our "Asynchronous JavaScript" module, we'll introduce _workers_, which enable you to run some tasks in a separate {{Glossary("Thread", "thread")}} of execution.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A reasonable understanding of JavaScript
fundamentals, including event handling.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To understand how to use web workers.</td>
</tr>
</tbody>
</table>
In the first article of this module, we saw what happens when you have a long-running synchronous task in your program β the whole window becomes totally unresponsive. Fundamentally, the reason for this is that the program is _single-threaded_. A _thread_ is a sequence of instructions that a program follows. Because the program consists of a single thread, it can only do one thing at a time: so if it is waiting for our long-running synchronous call to return, it can't do anything else.
Workers give you the ability to run some tasks in a different thread, so you can start the task, then continue with other processing (such as handling user actions).
One concern from all this is that if multiple threads can have access to the same shared data, it's possible for them to change it independently and unexpectedly (with respect to each other).
This can cause bugs that are hard to find.
To avoid these problems on the web, your main code and your worker code never get direct access to each other's variables, and can only truly "share" data in very specific cases.
Workers and the main code run in completely separate worlds, and only interact by sending each other messages. In particular, this means that workers can't access the DOM (the window, document, page elements, and so on).
There are three different sorts of workers:
- dedicated workers
- shared workers
- service workers
In this article, we'll walk through an example of the first sort of worker, then briefly discuss the other two.
## Using web workers
Remember in the first article, where we had a page that calculated prime numbers? We're going to use a worker to run the prime-number calculation, so our page stays responsive to user actions.
### The synchronous prime generator
Let's first take another look at the JavaScript in our previous example:
```js
function generatePrimes(quota) {
function isPrime(n) {
for (let c = 2; c <= Math.sqrt(n); ++c) {
if (n % c === 0) {
return false;
}
}
return true;
}
const primes = [];
const maximum = 1000000;
while (primes.length < quota) {
const candidate = Math.floor(Math.random() * (maximum + 1));
if (isPrime(candidate)) {
primes.push(candidate);
}
}
return primes;
}
document.querySelector("#generate").addEventListener("click", () => {
const quota = document.querySelector("#quota").value;
const primes = generatePrimes(quota);
document.querySelector("#output").textContent =
`Finished generating ${quota} primes!`;
});
document.querySelector("#reload").addEventListener("click", () => {
document.querySelector("#user-input").value =
'Try typing in here immediately after pressing "Generate primes"';
document.location.reload();
});
```
In this program, after we call `generatePrimes()`, the program becomes totally unresponsive.
### Prime generation with a worker
For this example, start by making a local copy of the files at <https://github.com/mdn/learning-area/blob/main/javascript/asynchronous/workers/start>. There are four files in this directory:
- index.html
- style.css
- main.js
- generate.js
The "index.html" file and the "style.css" files are already complete:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Prime numbers</title>
<script src="main.js" defer></script>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<label for="quota">Number of primes:</label>
<input type="text" id="quota" name="quota" value="1000000" />
<button id="generate">Generate primes</button>
<button id="reload">Reload</button>
<textarea id="user-input" rows="5" cols="62">
Try typing in here immediately after pressing "Generate primes"
</textarea>
<div id="output"></div>
</body>
</html>
```
```css
textarea {
display: block;
margin: 1rem 0;
}
```
The "main.js" and "generate.js" files are empty. We're going to add the main code to "main.js", and the worker code to "generate.js".
So first, we can see that the worker code is kept in a separate script from the main code. We can also see, looking at "index.html" above, that only the main code is included in a `<script>` element.
Now copy the following code into "main.js":
```js
// Create a new worker, giving it the code in "generate.js"
const worker = new Worker("./generate.js");
// When the user clicks "Generate primes", send a message to the worker.
// The message command is "generate", and the message also contains "quota",
// which is the number of primes to generate.
document.querySelector("#generate").addEventListener("click", () => {
const quota = document.querySelector("#quota").value;
worker.postMessage({
command: "generate",
quota,
});
});
// When the worker sends a message back to the main thread,
// update the output box with a message for the user, including the number of
// primes that were generated, taken from the message data.
worker.addEventListener("message", (message) => {
document.querySelector("#output").textContent =
`Finished generating ${message.data} primes!`;
});
document.querySelector("#reload").addEventListener("click", () => {
document.querySelector("#user-input").value =
'Try typing in here immediately after pressing "Generate primes"';
document.location.reload();
});
```
- First, we're creating the worker using the {{domxref("Worker/Worker", "Worker()")}} constructor. We pass it a URL pointing to the worker script. As soon as the worker is created, the worker script is executed.
- Next, as in the synchronous version, we add a `click` event handler to the "Generate primes" button. But now, rather than calling a `generatePrimes()` function, we send a message to the worker using {{domxref("Worker/postMessage", "worker.postMessage()")}}. This message can take an argument, and in this case, we're passing a JSON object containing two properties:
- `command`: a string identifying the thing we want the worker to do (in case our worker could do more than one thing)
- `quota`: the number of primes to generate.
- Next, we add a `message` event handler to the worker. This is so the worker can tell us when it has finished, and pass us any resulting data. Our handler takes the data from the `data` property of the message, and writes it to the output element (the data is exactly the same as `quota`, so this is a bit pointless, but it shows the principle).
- Finally, we implement the `click` event handler for the "Reload" button. This is exactly the same as in the synchronous version.
Now for the worker code. Copy the following code into "generate.js":
```js
// Listen for messages from the main thread.
// If the message command is "generate", call `generatePrimes()`
addEventListener("message", (message) => {
if (message.data.command === "generate") {
generatePrimes(message.data.quota);
}
});
// Generate primes (very inefficiently)
function generatePrimes(quota) {
function isPrime(n) {
for (let c = 2; c <= Math.sqrt(n); ++c) {
if (n % c === 0) {
return false;
}
}
return true;
}
const primes = [];
const maximum = 1000000;
while (primes.length < quota) {
const candidate = Math.floor(Math.random() * (maximum + 1));
if (isPrime(candidate)) {
primes.push(candidate);
}
}
// When we have finished, send a message to the main thread,
// including the number of primes we generated.
postMessage(primes.length);
}
```
Remember that this runs as soon as the main script creates the worker.
The first thing the worker does is start listening for messages from the main script. It does this using `addEventListener()`, which is a global function in a worker. Inside the `message` event handler, the `data` property of the event contains a copy of the argument passed from the main script. If the main script passed the `generate` command, we call `generatePrimes()`, passing in the `quota` value from the message event.
The `generatePrimes()` function is just like the synchronous version, except instead of returning a value, we send a message to the main script when we are done. We use the {{domxref("DedicatedWorkerGlobalScope/postMessage", "postMessage()")}} function for this, which like `addEventListener()` is a global function in a worker. As we already saw, the main script is listening for this message and will update the DOM when the message is received.
> **Note:** To run this site, you'll have to run a local web server, because file:// URLs are not allowed to load workers. See our guide to [setting up a local testing server](/en-US/docs/Learn/Common_questions/Tools_and_setup/set_up_a_local_testing_server). With that done, you should be able to click "Generate primes" and have your main page stay responsive.
>
> If you have any problems creating or running the example, you can review the [finished version](https://github.com/mdn/learning-area/blob/main/javascript/asynchronous/workers/finished) and try it [live](https://mdn.github.io/learning-area/javascript/asynchronous/workers/finished).
## Other types of workers
The worker we just created was what's called a _dedicated worker_. This means it's used by a single script instance.
There are other types of workers, though:
- [_Shared workers_](/en-US/docs/Web/API/SharedWorker) can be shared by several different scripts running in different windows.
- [_Service workers_](/en-US/docs/Web/API/Service_Worker_API) act like proxy servers, caching resources so that web applications can work when the user is offline. They're a key component of [Progressive Web Apps](/en-US/docs/Web/Progressive_web_apps).
## Conclusion
In this article we've introduced web workers, which enable a web application to offload tasks to a separate thread. The main thread and the worker don't directly share any variables, but communicate by sending messages, which are received by the other side as `message` events.
Workers can be an effective way to keep the main application responsive, although they can't access all the APIs that the main application can, and in particular can't access the DOM.
## See also
- [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
- [Using service workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
- [Web workers API](/en-US/docs/Web/API/Web_Workers_API)
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Implementing_a_promise-based_API", "Learn/JavaScript/Asynchronous/Sequencing_animations", "Learn/JavaScript/Asynchronous")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/asynchronous | data/mdn-content/files/en-us/learn/javascript/asynchronous/introducing/index.md | ---
title: Introducing asynchronous JavaScript
slug: Learn/JavaScript/Asynchronous/Introducing
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous")}}
In this article, we'll explain what asynchronous programming is, why we need it, and briefly discuss some of the ways asynchronous functions have historically been implemented in JavaScript.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A reasonable understanding of JavaScript
fundamentals, including functions and event handlers.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To gain familiarity with what asynchronous JavaScript is, how it differs from synchronous JavaScript, and why we need it.
</td>
</tr>
</tbody>
</table>
Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result.
Many functions provided by browsers, especially the most interesting ones, can potentially take a long time, and therefore, are asynchronous. For example:
- Making HTTP requests using {{domxref("fetch", "fetch()")}}
- Accessing a user's camera or microphone using {{domxref("MediaDevices/getUserMedia", "getUserMedia()")}}
- Asking a user to select files using {{domxref("window/showOpenFilePicker", "showOpenFilePicker()")}}
So even though you may not have to _implement_ your own asynchronous functions very often, you are very likely to need to _use_ them correctly.
In this article, we'll start by looking at the problem with long-running synchronous functions, which make asynchronous programming a necessity.
## Synchronous programming
Consider the following code:
```js
const name = "Miriam";
const greeting = `Hello, my name is ${name}!`;
console.log(greeting);
// "Hello, my name is Miriam!"
```
This code:
1. Declares a string called `name`.
2. Declares another string called `greeting`, which uses `name`.
3. Outputs the greeting to the JavaScript console.
We should note here that the browser effectively steps through the program one line at a time, in the order we wrote it. At each point, the browser waits for the line to finish its work before going on to the next line. It has to do this because each line depends on the work done in the preceding lines.
That makes this a **synchronous program**. It would still be synchronous even if we called a separate function, like this:
```js
function makeGreeting(name) {
return `Hello, my name is ${name}!`;
}
const name = "Miriam";
const greeting = makeGreeting(name);
console.log(greeting);
// "Hello, my name is Miriam!"
```
Here, `makeGreeting()` is a **synchronous function** because the caller has to wait for the function to finish its work and return a value before the caller can continue.
### A long-running synchronous function
What if the synchronous function takes a long time?
The program below uses a very inefficient algorithm to generate multiple large prime numbers when a user clicks the "Generate primes" button. The higher the number of primes a user specifies, the longer the operation will take.
```html
<label for="quota">Number of primes:</label>
<input type="text" id="quota" name="quota" value="1000000" />
<button id="generate">Generate primes</button>
<button id="reload">Reload</button>
<div id="output"></div>
```
```js
const MAX_PRIME = 1000000;
function isPrime(n) {
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false;
}
}
return n > 1;
}
const random = (max) => Math.floor(Math.random() * max);
function generatePrimes(quota) {
const primes = [];
while (primes.length < quota) {
const candidate = random(MAX_PRIME);
if (isPrime(candidate)) {
primes.push(candidate);
}
}
return primes;
}
const quota = document.querySelector("#quota");
const output = document.querySelector("#output");
document.querySelector("#generate").addEventListener("click", () => {
const primes = generatePrimes(quota.value);
output.textContent = `Finished generating ${quota.value} primes!`;
});
document.querySelector("#reload").addEventListener("click", () => {
document.location.reload();
});
```
{{EmbedLiveSample("A long-running synchronous function", 600, 120)}}
Try clicking "Generate primes". Depending on how fast your computer is, it will probably take a few seconds before the program displays the "Finished!" message.
### The trouble with long-running synchronous functions
The next example is just like the last one, except we added a text box for you to type in. This time, click "Generate primes", and try typing in the text box immediately after.
You'll find that while our `generatePrimes()` function is running, our program is completely unresponsive: you can't type anything, click anything, or do anything else.
```html hidden
<label for="quota">Number of primes:</label>
<input type="text" id="quota" name="quota" value="1000000" />
<button id="generate">Generate primes</button>
<button id="reload">Reload</button>
<textarea id="user-input" rows="5" cols="62">
Try typing in here immediately after pressing "Generate primes"
</textarea>
<div id="output"></div>
```
```css hidden
textarea {
display: block;
margin: 1rem 0;
}
```
```js hidden
const MAX_PRIME = 1000000;
function isPrime(n) {
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false;
}
}
return n > 1;
}
const random = (max) => Math.floor(Math.random() * max);
function generatePrimes(quota) {
const primes = [];
while (primes.length < quota) {
const candidate = random(MAX_PRIME);
if (isPrime(candidate)) {
primes.push(candidate);
}
}
return primes;
}
const quota = document.querySelector("#quota");
const output = document.querySelector("#output");
document.querySelector("#generate").addEventListener("click", () => {
const primes = generatePrimes(quota.value);
output.textContent = `Finished generating ${quota.value} primes!`;
});
document.querySelector("#reload").addEventListener("click", () => {
document.location.reload();
});
```
{{EmbedLiveSample("The trouble with long-running synchronous functions", 600, 200)}}
The reason for this is that this JavaScript program is _single-threaded_. A thread is a sequence of instructions that a program follows. Because the program consists of a single thread, it can only do one thing at a time: so if it is waiting for our long-running synchronous call to return, it can't do anything else.
What we need is a way for our program to:
1. Start a long-running operation by calling a function.
2. Have that function start the operation and return immediately, so that our program can still be responsive to other events.
3. Have the function execute the operation in a way that does not block the main thread, for example by starting a new thread.
4. Notify us with the result of the operation when it eventually completes.
That's precisely what asynchronous functions enable us to do. The rest of this module explains how they are implemented in JavaScript.
## Event handlers
The description we just saw of asynchronous functions might remind you of event handlers, and if it does, you'd be right. Event handlers are really a form of asynchronous programming: you provide a function (the event handler) that will be called, not right away, but whenever the event happens. If "the event" is "the asynchronous operation has completed", then that event could be used to notify the caller about the result of an asynchronous function call.
Some early asynchronous APIs used events in just this way. The {{domxref("XMLHttpRequest")}} API enables you to make HTTP requests to a remote server using JavaScript. Since this can take a long time, it's an asynchronous API, and you get notified about the progress and eventual completion of a request by attaching event listeners to the `XMLHttpRequest` object.
The following example shows this in action. Press "Click to start request" to send a request. We create a new {{domxref("XMLHttpRequest")}} and listen for its {{domxref("XMLHttpRequest/loadend_event", "loadend")}} event. The handler logs a "Finished!" message along with the status code.
After adding the event listener we send the request. Note that after this, we can log "Started XHR request": that is, our program can continue to run while the request is going on, and our event handler will be called when the request is complete.
```html
<button id="xhr">Click to start request</button>
<button id="reload">Reload</button>
<pre readonly class="event-log"></pre>
```
```css hidden
pre {
display: block;
margin: 1rem 0;
}
```
```js
const log = document.querySelector(".event-log");
document.querySelector("#xhr").addEventListener("click", () => {
log.textContent = "";
const xhr = new XMLHttpRequest();
xhr.addEventListener("loadend", () => {
log.textContent = `${log.textContent}Finished with status: ${xhr.status}`;
});
xhr.open(
"GET",
"https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json",
);
xhr.send();
log.textContent = `${log.textContent}Started XHR request\n`;
});
document.querySelector("#reload").addEventListener("click", () => {
log.textContent = "";
document.location.reload();
});
```
{{EmbedLiveSample("Event handlers", 600, 120)}}
This is just like the [event handlers we've encountered in a previous module](/en-US/docs/Learn/JavaScript/Building_blocks/Events), except that instead of the event being a user action, such as the user clicking a button, the event is a change in the state of some object.
## Callbacks
An event handler is a particular type of callback. A callback is just a function that's passed into another function, with the expectation that the callback will be called at the appropriate time. As we just saw, callbacks used to be the main way asynchronous functions were implemented in JavaScript.
However, callback-based code can get hard to understand when the callback itself has to call functions that accept a callback. This is a common situation if you need to perform some operation that breaks down into a series of asynchronous functions. For example, consider the following:
```js
function doStep1(init) {
return init + 1;
}
function doStep2(init) {
return init + 2;
}
function doStep3(init) {
return init + 3;
}
function doOperation() {
let result = 0;
result = doStep1(result);
result = doStep2(result);
result = doStep3(result);
console.log(`result: ${result}`);
}
doOperation();
```
Here we have a single operation that's split into three steps, where each step depends on the last step. In our example, the first step adds 1 to the input, the second adds 2, and the third adds 3. Starting with an input of 0, the end result is 6 (0 + 1 + 2 + 3). As a synchronous program, this is very straightforward. But what if we implemented the steps using callbacks?
```js
function doStep1(init, callback) {
const result = init + 1;
callback(result);
}
function doStep2(init, callback) {
const result = init + 2;
callback(result);
}
function doStep3(init, callback) {
const result = init + 3;
callback(result);
}
function doOperation() {
doStep1(0, (result1) => {
doStep2(result1, (result2) => {
doStep3(result2, (result3) => {
console.log(`result: ${result3}`);
});
});
});
}
doOperation();
```
Because we have to call callbacks inside callbacks, we get a deeply nested `doOperation()` function, which is much harder to read and debug. This is sometimes called "callback hell" or the "pyramid of doom" (because the indentation looks like a pyramid on its side).
When we nest callbacks like this, it can also get very hard to handle errors: often you have to handle errors at each level of the "pyramid", instead of having error handling only once at the top level.
For these reasons, most modern asynchronous APIs don't use callbacks. Instead, the foundation of asynchronous programming in JavaScript is the {{jsxref("Promise")}}, and that's the subject of the next article.
{{NextMenu("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous")}}
| 0 |
data/mdn-content/files/en-us/learn/javascript/asynchronous | data/mdn-content/files/en-us/learn/javascript/asynchronous/implementing_a_promise-based_api/index.md | ---
title: How to implement a promise-based API
slug: Learn/JavaScript/Asynchronous/Implementing_a_promise-based_API
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Introducing_workers", "Learn/JavaScript/Asynchronous")}}
In the last article we discussed how to use APIs that return promises. In this article we'll look at the other side β how to _implement_ APIs that return promises. This is a much less common task than using promise-based APIs, but it's still worth knowing about.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A reasonable understanding of JavaScript
fundamentals, including event handling and the basics of promises.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To understand how to implement promise-based APIs.</td>
</tr>
</tbody>
</table>
Generally, when you implement a promise-based API, you'll be wrapping an asynchronous operation, which might use events, or plain callbacks, or a message-passing model. You'll arrange for a `Promise` object to handle the success or failure of that operation properly.
## Implementing an alarm() API
In this example we'll implement a promise-based alarm API, called `alarm()`. It will take as arguments the name of the person to wake up and a delay in milliseconds to wait before waking the person up. After the delay, the function will send a "Wake up!" message, including the name of the person we need to wake up.
### Wrapping setTimeout()
We'll use the {{domxref("setTimeout()")}} API to implement our `alarm()` function. The `setTimeout()` API takes as arguments a callback function and a delay, given in milliseconds. When `setTimeout()` is called, it starts a timer set to the given delay, and when the time expires, it calls the given function.
In the example below, we call `setTimeout()` with a callback function and a delay of 1000 milliseconds:
```html
<button id="set-alarm">Set alarm</button>
<div id="output"></div>
```
```css hidden
div {
margin: 0.5rem 0;
}
```
```js
const output = document.querySelector("#output");
const button = document.querySelector("#set-alarm");
function setAlarm() {
setTimeout(() => {
output.textContent = "Wake up!";
}, 1000);
}
button.addEventListener("click", setAlarm);
```
{{EmbedLiveSample("Wrapping setTimeout()", 600, 100)}}
### The Promise() constructor
Our `alarm()` function will return a `Promise` that is fulfilled when the timer expires. It will pass a "Wake up!" message into the `then()` handler, and will reject the promise if the caller supplies a negative delay value.
The key component here is the {{jsxref("Promise/Promise", "Promise()")}} constructor. The `Promise()` constructor takes a single function as an argument. We'll call this function the `executor`. When you create a new promise you supply the implementation of the executor.
This executor function itself takes two arguments, which are both also functions, and which are conventionally called `resolve` and `reject`. In your executor implementation, you call the underlying asynchronous function. If the asynchronous function succeeds, you call `resolve`, and if it fails, you call `reject`. If the executor function throws an error, `reject` is called automatically. You can pass a single parameter of any type into `resolve` and `reject`.
So we can implement `alarm()` like this:
```js
function alarm(person, delay) {
return new Promise((resolve, reject) => {
if (delay < 0) {
throw new Error("Alarm delay must not be negative");
}
setTimeout(() => {
resolve(`Wake up, ${person}!`);
}, delay);
});
}
```
This function creates and returns a new `Promise`. Inside the executor for the promise, we:
- check that `delay` is not negative, and throw an error if it is.
- call `setTimeout()`, passing a callback and `delay`. The callback will be called when the timer expires, and in the callback we call `resolve`, passing in our `"Wake up!"` message.
## Using the alarm() API
This part should be quite familiar from the last article. We can call `alarm()`, and on the returned promise call `then()` and `catch()` to set handlers for promise fulfillment and rejection.
```html hidden
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" size="4" value="Matilda" />
</div>
<div>
<label for="delay">Delay:</label>
<input type="text" id="delay" name="delay" size="4" value="1000" />
</div>
<button id="set-alarm">Set alarm</button>
<div id="output"></div>
```
```css hidden
button {
display: block;
}
div,
button {
margin: 0.5rem 0;
}
```
```js
const name = document.querySelector("#name");
const delay = document.querySelector("#delay");
const button = document.querySelector("#set-alarm");
const output = document.querySelector("#output");
function alarm(person, delay) {
return new Promise((resolve, reject) => {
if (delay < 0) {
throw new Error("Alarm delay must not be negative");
}
setTimeout(() => {
resolve(`Wake up, ${person}!`);
}, delay);
});
}
button.addEventListener("click", () => {
alarm(name.value, delay.value)
.then((message) => (output.textContent = message))
.catch((error) => (output.textContent = `Couldn't set alarm: ${error}`));
});
```
{{EmbedLiveSample("Using the alarm() API", 600, 160)}}
Try setting different values for "Name" and "Delay". Try setting a negative value for "Delay".
## Using async and await with the alarm() API
Since `alarm()` returns a `Promise`, we can do everything with it that we could do with any other promise: promise chaining, `Promise.all()`, and `async` / `await`:
```html hidden
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" size="4" value="Matilda" />
</div>
<div>
<label for="delay">Delay:</label>
<input type="text" id="delay" name="delay" size="4" value="1000" />
</div>
<button id="set-alarm">Set alarm</button>
<div id="output"></div>
```
```css hidden
button {
display: block;
}
div,
button {
margin: 0.5rem 0;
}
```
```js
const name = document.querySelector("#name");
const delay = document.querySelector("#delay");
const button = document.querySelector("#set-alarm");
const output = document.querySelector("#output");
function alarm(person, delay) {
return new Promise((resolve, reject) => {
if (delay < 0) {
throw new Error("Alarm delay must not be negative");
}
setTimeout(() => {
resolve(`Wake up, ${person}!`);
}, delay);
});
}
button.addEventListener("click", async () => {
try {
const message = await alarm(name.value, delay.value);
output.textContent = message;
} catch (error) {
output.textContent = `Couldn't set alarm: ${error}`;
}
});
```
{{EmbedLiveSample("Using async and await with the alarm() API", 600, 160)}}
## See also
- [`Promise()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise)
- [Using promises](/en-US/docs/Web/JavaScript/Guide/Using_promises)
{{LearnSidebar}}{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Introducing_workers", "Learn/JavaScript/Asynchronous")}}
| 0 |
data/mdn-content/files/en-us/learn | data/mdn-content/files/en-us/learn/learning_and_getting_help/index.md | ---
title: Learning and getting help
slug: Learn/Learning_and_getting_help
page-type: guide
---
{{learnsidebar}}
It is great that you are putting some time into learning a new set of skills, but there are good practices to employ that will make your learning more effective. There also are times when you'll get stuck and feel frustrated β even professional web developers feel like this regularly β and it pays to know about the most effective ways to try and get help so you can progress in your work. This article provides some hints and tips in both of these areas that will help you get more out of learning web development, as well as further reading so you can find out more information about each sub-topic should you wish.
## Effective learning
Let's move straight on and think about effective learning.
### Different learning methods
It is interesting to consider that there are two main ways in which your brain learns things β **focused** and **diffuse** learning:
- Focused learning is what you might more traditionally associate with academic subjects. You concentrate deeply on a low-level topic and solving the specific problems that it brings. You are focused on a narrow area.
- Diffuse learning is more to do with high-level thinking around a wider area. You let your mind wander more widely, and seemingly make random connections between different things. This is more the kind of thinking you do while you are in the shower, or during a coffee break.
From the studies that neuroscientists have done on brain activity, we have found out that you can't really engage in both ways of learning β or thinking β at once. So which one should you choose? You might think that focused learning is better for studying, but in reality, **both** are very important.
Focused thinking is great for concentrating hard on specific subjects, getting into deep problem-solving, and improving your mastery of the techniques required β strengthening the neural pathways in your brain where that information is stored. It isn't however very good at getting an understanding of "the big picture", and unlocking new neural pathways when you are trying to understand new subjects or solve new problems that you haven't come across before.
For that, you need diffuse thinking. This is the opposite of focus β you let your brain wander around the wider landscape, searching around for connections you didn't have before, touching on new things (or new combinations of things) that you can then focus on later, to strengthen them and start to really understand what they mean.
This is why it is usually good to read some introductory material first to get a high-level understanding of an area before you leap into the specific details.
It is also why you can sometimes get really stuck on a problem, but then figure out the answer when you go for a coffee break (or a walk). You might:
1. Know how to fix problem A with tool A.
2. Know how to fix problem B with tool B.
3. Not know how to fix problem C.
Let's say you focus on problem C for a while and get frustrated because you can't think how to solve it. But then after going on a walk to get some fresh air, you may well find that as your mind wanders, you suddenly make a connection between tool A and tool B, and realize that you can use them together to fix problem C! It isn't always this simple, but it is also surprising how many times this does happen. This also highlights the importance of taking regular breaks when you are studying in front of the computer.
### Different learning materials
It is also worth looking at the different types of learning materials that are available, to see which ones are most effective for you to learn with.
#### Textual articles
You'll find a lot of written articles on the web to teach you about web design. Like most of this course, for example. Some of the articles will be tutorials, to teach you a certain technique or important concept (such as "learn how to create a video player" or "Learn the CSS box model"), and some of the articles will be reference material, to allow you to look up details you may have forgotten (such as "what is the syntax of the CSS `background` property"?)
MDN Web Docs is very good for both types β the area you are currently in is great for learning techniques and concepts, and we also have several giant reference sections allowing you to look up any syntax you can't remember.
There are also several other great resources on the web, some of which we'll mention below.
> **Note:** The above text should have given you an important fact β you aren't expected to remember everything! Professional web developers use tools like MDN Web Docs to look up things they have forgotten all the time. As you'll discover, learning web development is more about problem-solving and learning patterns than it is about learning lots of syntaxes.
#### Videos
There are also a number of sites that have video learning content on them. YouTube is an obvious one, with channels such as [Mozilla Layout Land](https://www.youtube.com/channel/UC7TizprGknbDalbHplROtag), [MozillaDeveloper](https://www.youtube.com/MozillaDeveloper), and [Google ChromeDevelopers](https://www.youtube.com/user/ChromeDevelopers/) providing many useful videos. Many people prefer textual articles for more in-depth learning and reference material, and videos for quick explanations of concepts and new features, but it is really up to you what you prefer to learn from. There is no right and wrong answer here.
#### Interactive code playgrounds
You might be the kind of person that prefers minimal instructions and would prefer to jump straight in and start playing with code. This is also a reasonable approach, and some learning sites tend to favor it. [Codecademy](https://www.codecademy.com/) for example is a learning site where the tutorials mainly consist of interactive code editors where you have to directly write code and see if the desired result was achieved.
Many MDN Web docs reference pages provide interactive examples too, where you can alter the code and see how the live result changes. And there is also nothing wrong with creating your own code examples on your computer, or in an online code editor like [JSBin](https://jsbin.com/?html,css,js,output), [Codepen](https://codepen.io/), or [Glitch](https://glitch.com/). In fact, you'll be called to do so as part of this course when you are learning!
> **Note:** Online code editors are also really useful for sharing code you've written, for example, if you are collaborating on learning with someone else who isn't in the same location, or are sending it to someone to ask for help with it. You can share the web address of the example with them so they can see it.
> **Note:** You might favor one learning method over the others, but realistically a hybrid approach is probably what you will end up with. And you'll probably come up with other methods than the three we covered above.
### Making a plan
It is a good idea to create a plan to help you achieve what you want to achieve through your learning.
#### A goal statement
It sounds silly, but why not start with a single sentence that says what you want to achieve? The following have different scopes, but are all realistic and achievable:
- I want to become a professional web developer in two years' time.
- I want to learn enough to build a website for my local amateur tennis club.
- I want to learn HTML and CSS so I can expand my job role to take over updating the content on our company website.
The following are not quite as reasonable:
- I want to go from a complete beginner to becoming a senior web developer in three months.
- I want to start my own company and build a social network that will out-perform Facebook, in two years.
#### What do you need to get there?
Once you've worked out your goal, it is a good idea to research what you'll need to achieve the goal. For example:
Materials I need:
- A computer
- Internet access
- Pens and paper
Knowledge I need:
- How to use HTML, CSS, JavaScript, and associated tools and best practices to build websites and web applications (we can definitely help you with this one!).
- How to get a domain, hosting, and use them to put a website or application online.
- How to run a small business.
- How to advertise my business and attract clients.
#### How much time and money will it take?
Estimate the time and cost of getting these things. If you'll need to work to earn money to buy the materials required, then the time to do that will have to be factored in. Once you have a time estimate, you can start to build a plan around your life.
#### How many hours per week do I need to dedicate?
Once you know what you need to do and how long you think it'll take, you can start writing out a plan to achieve your goal. It can be as simple as:
"It'll take me 500 hours to learn what I need to know, and I have a year to do it. If I assume 2 weeks of holiday, I'll need to do work on this for 10 hours per week. I am free on evenings and weekends, so I'll plan my time around those."
How much time you can spend on this of course depends on what your circumstances are. If you are at school, then you've got way more free time than if you have a job and children to provide for. It is still possible to achieve your goals, but you have to be realistic about how quickly you can do it.
If you are doing a university or college course to learn web development, then most of this planning is done for you β lucky you!
When you have worked out a weekly schedule then you should keep a record of what you manage to do each week in a simple spreadsheet or even in a notebook!
Also, it might be a good idea to have some sub-goals worked out to allow you to keep track of where you are more easily. For example:
- HTML and CSS basics learned by summer
- JavaScript basics learned by December
- Example website project built by next April
- etc.
Keep thinking about how much progress you are making, and adjust your plan if needs be.
### Staying motivated
It is hard to stay motivated, especially if you are trying to learn a complex skill like programming or web development. What follows are some tips to stay motivated and keep working:
- **Try to make your work environment as productive as possible**. Get a comfortable desk and chair to work in, make sure you have enough light to see what you are doing, and try to include things that help you concentrate (e.g. mellow music, fragrances, whatever else you need). Don't try to work in a room with distractions β for example a television on, with your friends watching football! Also, leave your mobile phone out of the room β most people are distracted by their phone a lot, so you should leave it somewhere else.
- **Take regular breaks**. It is not good for your motivation to keep working away for hours with no break, especially if you are finding it hard or getting stuck on a problem. That just leads to frustration. It is often better to take a break, move around for a bit, then relax with a drink before getting back to work. And as we said earlier, the diffuse learning you do during that time can often help you to figure out a solution to the problem you were facing. It is also physically bad to work for too long without a break; looking at a monitor for too long can hurt your eyes, and sitting still for too long can be bad for your back or legs. We'd recommend taking a 15-minute break every hour to 90 minutes.
- **Eat, exercise, and sleep**. Eat healthily, get regular exercise, and make sure you get enough sleep. This sounds obvious, but it is easy to forget when you get really into coding. Factor these essential ingredients into your schedule, and make sure you are not scheduling more learning time instead of these things.
- **Give yourself rewards**. It's true that _all work and no play makes Jack a dull boy_. You should try to schedule fun things to do after each learning session, which you'll only have when the learning is over and complete. If you are really into gaming, for example, there is something quite motivating about saying "no gaming tonight unless I get through my 5 hours of learning". Now all you need is willpower. Good luck!
- **Co-learning and demoing**. This won't be an option for everyone, but if at all possible try to learn alongside others. Again, this is easier if you are doing a college course on web development, but perhaps you could convince a friend to learn along with you, or find a local meetup or skill-sharing group? It is really useful and motivating to have someone to discuss ideas with and ask for help, and you should also take time to demo your work. Those shouts of appreciation will spur you on.
### Effective problem-solving
There is no one effective way to solve all problems (and learn all things) associated with web design and development, but there are some general bits of advice that will serve you well in most cases.
#### Break things down into chunks
For a start, when you are trying to implement something specific and it seems really hard to get your head around, you should try to break it down into multiple smaller problems or chunks.
For example, if you are looking at a task of "Build a simple two-column website", you could break it down as follows:
- Create the HTML structure
- Work out basic site typography
- Work out a basic color scheme
- Implement a high-level layout β header, horizontal navigation menu, main content area with main and side columns, and footer
- Implement a horizontal navigation menu
- etc.
Then you could break it down further. For example, "Implement horizontal navigation menu" could be written out as:
- Make a list of menu items that sit horizontally in a line.
- Remove unneeded defaults, like list spacing and bullet points.
- Style hover/focus/active states of menu items appropriately.
- Make the menu items equally spaced along the line.
- Give the menu items enough vertical spacing.
- Make sure the text is centered inside each menu item
- etc.
Each of these problems doesn't seem nearly as difficult to solve as the one big problem you had initially. Now you've just got to go through and solve them all!
#### Learn and recognize the patterns
As we said before, web design/programming is mostly about problem-solving and patterns. Once you have written out what you'll need to do to solve a specific problem, you can start to figure out what technology features to use to solve it. For example, professional web developers have created lots of horizontal navigation menus, so they'll immediately start thinking of a solution like this:
A nav menu is usually created from a list of links, something like:
```html
<ul>
<li><a href="">First menu item</a></li>
<li><a href="">Second menu item</a></li>
<li><a href="">Third menu item</a></li>
<li><a href="">etc.</a></li>
</ul>
```
To make all the items sit horizontally on a line, the easiest modern way is to use flexbox:
```css
ul {
display: flex;
}
```
To remove unneeded spacing and bullet points, we can do this:
```css
ul {
list-style-type: none;
padding: 0;
}
```
etc.
If you are a complete beginner to web development, you'll have to do some study and web searches and lookup solutions to such problems. If you are a professional web developer you'll probably remember the last time you solved a similar problem, and only have to look up a few bits of the syntax that you forgot since then.
When you find solutions to such problems, it is worth writing down notes on what you did, and keeping some minimal code examples in a directory somewhere so you can look back on previous work.
In addition, the web has [developer tools](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools) that allow you to look at the code used to build any site on the web. If you don't have a solution to hand, one good research method is to find websites with similar features in the wild, and find out how they did it.
> **Note:** Notice how above we talked about the problem we are trying to solve first, and the technology used to solve it second. This is pretty much always the best way to do it β don't start with a cool new technology that you want to use, and try to shoehorn it into the use case.
> **Note:** The simplest solution is often the best.
### Getting practice
The more you practice solving a problem, the stronger your brain's neural pathways are in that area, and the easier it becomes to recall the details and the logic of that particular problem.
Keep tinkering with code and getting more practice. If you run out of problems to solve, look up some tests online, do some more courses, or ask your friends and family (or local school or church) if there is anything they'd like you to build for them.
## Getting help
Web development requires you to learn a complex set of skills β you are bound to get stuck sometimes and need help. As we said before, even professional developers need regular help working out issues.
There are a variety of ways to get help, and what follows are some tips for doing so more effectively.
### Effective web searches
One important skill to learn is the art of effective web searches β what search terms do you need to use in your favorite search engine to find the articles you need?
It is often fairly obvious what to search for. For example:
- If you want to find out more about responsive web design, you could search for "responsive web design".
- If you want to find out more about a specific technology feature, such as the HTML `<video>` element, or the CSS `background-color` or `opacity` properties, or the JavaScript `Date.setTime()` method, you should just search for the feature's name.
- If you are looking for some more specific information, you can add other keywords as modifiers, for example "\<video> element autoplay attribute", or "Date.setTime parameters".
If you want to search for something that has less obvious buzzwords, you need to think about what is most likely to return what you want.
- Run code after several promises are fulfilled
- Play a video stream from a webcam in the browser
- Create a linear gradient in the background of your element
#### Error messages
If you are having a problem with some code and a specific error message is coming up, it is often a good idea to just copy the error message into your search engine and use it as the search term. If other people have had the same problem, there'll likely be some articles or blog posts about it in places like MDN or Stack Overflow.
> **Note:** [Stack Overflow](https://stackoverflow.com/) is a really useful website β it is basically a huge database of curated questions and answers on various technologies and related techniques. You'll probably find an answer that answers your question. If not, you can ask a question and see if anyone can help you.
#### Browser testing
It is often a good idea to see if your problem is affecting all browsers, or whether it only occurs in one or a small number of browsers. If it is only affecting one browser, for example, you can use that browser to narrow down the search. Example searches might look like:
- \<video> playback doesn't work in the iOS browser.
- Firefox doesn't seem to support the Beetlejuice API.
### Using MDN
The site you are already on has a wealth of information available to you β both reference material for looking up code syntax, and guides/tutorials for learning techniques.
We've provided most of the answers to the questions you'll have about web development fundamentals in this part of MDN. If you are stuck, it is good to re-read the associated articles to see if you missed anything.
If you are not sure which article to read then try searching MDN for some related keywords (as indicated above), or try a general web search. To search on MDN you can either use the site's in-built search functionality or better still, use your favorite search engine and put "mdn" in front of the search term. For example, "mdn responsive web design" or "mdn background-color".
### Other online resources
We already mentioned Stack Overflow, but there are other online resources that can help.
It is good to find a community to be part of, and you'll get a lot of respect if you try to help others answer their questions as well as asking your own. Other good examples include:
- [MDN Discourse](/en-US/docs/MDN/Community/Communication_channels#forums)
- [Sitepoint Forums](https://www.sitepoint.com/community/)
- [webdeveloper.com Forums](https://webdeveloper.com/)
However, it also makes sense to find useful groups on social networking sites such as Twitter or Facebook. Look for groups that discuss web development subjects you are interested in and join up. Follow people on Twitter you know are influential, smart, or just plain seem to share lots of useful tips.
### Physical meetups
Lastly, you should try attending some physical meetups to meet other like-minded people, especially ones that cater to beginners. [meetup.com](https://www.meetup.com/find/?keywords=tech&source=EVENTS) is a good place to find local physical meetups, and you could also try your local press/what's on sites.
You could also try attending full-fledged web conferences. While these can be expensive, you could try volunteering at them, and many conferences offer reduced rate tickets, for example, student or diversity tickets.
## See also
- [Coursera: Learning to learn](https://www.coursera.org/learn/learning-how-to-learn)
- [Freecodecamp](https://www.freecodecamp.org/)
- [Codecademy](https://www.codecademy.com/)
| 0 |
data/mdn-content/files/en-us/learn | data/mdn-content/files/en-us/learn/front-end_web_developer/index.md | ---
title: Front-end web developer
slug: Learn/Front-end_web_developer
page-type: learn-topic
---
{{learnsidebar}}
Welcome to our front-end web developer learning pathway!
Here we provide you with a structured course that will teach you all you need to know to become a front-end web developer. Work through each section, learning new skills (or improving existing ones) as you go along. Each section includes exercises and assessments to test your understanding before you move forward.
## Subjects covered
The subjects covered are:
- Basic setup and learning how to learn
- Web standards and best practices (such as accessibility and cross-browser compatibility)
- HTML, the language that gives web content structure and meaning
- CSS, the language used to style web pages
- JavaScript, the scripting language used to create dynamic functionality on the web
- Tooling that is used to facilitate modern client-side web development.
You can work through sections in order, but each one is also self-contained. For example, if you already know HTML, you can skip ahead to the CSS section.
## Prerequisites
You don't need any previous knowledge to start this course. All you need is a computer that can run modern web browsers, an internet connection, and a willingness to learn.
If you are not sure if front-end web development is for you, and/or you want a gentle introduction before starting a longer and more complete course, work through our [Getting started with the web](/en-US/docs/Learn/Getting_started_with_the_web) module first.
## Getting help
We have tried to make learning front-end web development as comfortable as possible, but you will probably still get stuck because you don't understand something, or some code is just not working.
Don't panic. We all get stuck, whether we are beginner or professional web developers. The [Learning and getting help](/en-US/docs/Learn/Learning_and_getting_help) article provides you with a series of tips for looking up information and helping yourself. If you are still stuck, feel free to post a question on our [Discourse forums](/en-US/docs/MDN/Community/Communication_channels#forums).
Let's get started. Good luck!
## The learning pathway
### Getting started
Time to complete: 1.5β2 hours
#### Prerequisites
Nothing except basic computer literacy.
#### How will I know I'm ready to move on?
There are no assessments in this part of the course. But make sure you don't skip. It is important to get you set up and ready to do work for exercises later on in the course.
#### Guides
- [Installing basic software](/en-US/docs/Learn/Getting_started_with_the_web/Installing_basic_software) β basic tool setup (15 min read)
- [Background on the web and web standards](/en-US/docs/Learn/Getting_started_with_the_web/The_web_and_web_standards) (45 min read)
- [Learning and getting help](/en-US/docs/Learn/Learning_and_getting_help) (45 min read)
### Semantics and structure with HTML
Time to complete: 35β50 hours
#### Prerequisites
A basic web development environment.
#### How will I know I'm ready to move on?
The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module.
#### Modules
- [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) (15β20 hour read/exercises)
- [Multimedia and embedding](/en-US/docs/Learn/HTML/Multimedia_and_embedding) (15β20 hour read/exercises)
- [HTML tables](/en-US/docs/Learn/HTML/Tables) (5β10 hour read/exercises)
### Styling and layout with CSS
Time to complete: 90β120 hours
#### Prerequisites
It is recommended that you have basic HTML knowledge before starting to learn CSS. You should at least study [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) first.
#### How will I know I'm ready to move on?
The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module.
#### Modules
- [CSS first steps](/en-US/docs/Learn/CSS/First_steps) (10β15 hour read/exercises)
- [CSS building blocks](/en-US/docs/Learn/CSS/Building_blocks) (35β45 hour read/exercises)
- [CSS styling text](/en-US/docs/Learn/CSS/Styling_text) (15β20 hour read/exercises)
- [CSS layout](/en-US/docs/Learn/CSS/CSS_layout) (30β40 hour read/exercises)
#### Additional resources
- [CSS layout cookbook](/en-US/docs/Web/CSS/Layout_cookbook)
### Interactivity with JavaScript
Time to complete: 135β185 hours
#### Prerequisites
It is recommended that you have basic HTML knowledge before starting to learn JavaScript. You should at least study [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) first.
#### How will I know I'm ready to move on?
The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module.
#### Modules
- [JavaScript first steps](/en-US/docs/Learn/JavaScript/First_steps) (30β40 hour read/exercises)
- [JavaScript building blocks](/en-US/docs/Learn/JavaScript/Building_blocks) (25β35 hour read/exercises)
- [Introducing JavaScript objects](/en-US/docs/Learn/JavaScript/Objects) (25β35 hour read/exercises)
- [Client-side web APIs](/en-US/docs/Learn/JavaScript/Client-side_web_APIs) (30β40 hour read/exercises)
- [Asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous) (25β35 hour read/exercises)
### Web forms β Working with user data
Time to complete: 40β50 hours
#### Prerequisites
Forms require HTML, CSS, and JavaScript knowledge. Given the complexity of working with forms, it is a dedicated topic.
#### How will I know I'm ready to move on?
The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module.
#### Modules
- [Web forms](/en-US/docs/Learn/Forms) (40β50 hours)
### Making the web work for everyone
Time to complete: 45β55 hours
#### Prerequisites
It is good to know HTML, CSS, and JavaScript before working through this section. Many of the techniques and best practices touch on multiple technologies.
#### How will I know I'm ready to move on?
The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module.
#### Modules
- [Cross-browser testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing) (25β30 hour read/exercises)
- [Accessibility](/en-US/docs/Learn/Accessibility) (20β25 hour read/exercises)
### Modern tooling
Time to complete: 55β90 hours
#### Prerequisites
It is good to know HTML, CSS, and JavaScript before working through this section, as the tools discussed work alongside many of these technologies.
#### How will I know I'm ready to move on?
There are no specific assessment articles in this set of modules. The case study tutorials at the end of the second and third modules prepare you for grasping the essentials of modern tooling.
#### Modules
- [Git and GitHub](/en-US/docs/Learn/Tools_and_testing/GitHub) (5 hour read)
- [Understanding client-side web development tools](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools) (20β25 hour read)
- [Understanding client-side JavaScript frameworks](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks) (30-60 hour read/exercises)
| 0 |
data/mdn-content/files/en-us/learn | data/mdn-content/files/en-us/learn/accessibility/index.md | ---
title: Accessibility
slug: Learn/Accessibility
page-type: learn-module
---
{{LearnSidebar}}
Learning some HTML, CSS, and JavaScript is useful if you want to become a web developer. Beyond mechanical use, it's important to learn how to use these technologies **responsibly** so that all readers might use your creations on the web. To help you achieve this, this module will cover general best practices (which are demonstrated throughout the [HTML](/en-US/docs/Learn/HTML), [CSS](/en-US/docs/Learn/CSS), and [JavaScript](/en-US/docs/Learn/JavaScript) topics), [cross browser testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing), and some tips on enforcing accessibility from the start. We'll cover accessibility in special detail.
## Overview
When someone describes a site as "accessible", they mean that any user can use all its features and content, regardless of how the user accesses the web β even and especially users with physical or mental impairments.
- Sites should be accessible to keyboard, mouse, and touch screen users, and any other way users access the web, including screen readers and voice assistants like Alexa and Google Home.
- Applications should be understandable and usable by people regardless of auditory, visual, physical, or cognitive abilities.
- Sites should also not cause harm: web features like motion can cause migraines or epileptic seizures.
**By default, HTML is accessible, if used correctly.** Web accessibility involves ensuring that content remains accessible, regardless of who and how the web is accessed.
The Firefox Accessibility Inspector is a very useful tool for checking out accessibility issues on web pages. The following video provides a nice introduction to it:
{{EmbedYouTube("7mqqgIxX_NU")}}
> **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 get the most out of this module, it would be a good idea to either work through at least the first two modules of the [HTML](/en-US/docs/Learn/HTML), [CSS](/en-US/docs/Learn/CSS), and [JavaScript](/en-US/docs/Learn/JavaScript) topics, or perhaps even better, work through the relevant parts of the accessibility module as you work through the related technology topics.
> **Note:** If you are working on a computer/tablet/other devices where you don't have the ability to create your own files, you can try out most of the code examples in an online coding program such as [JSBin](https://jsbin.com/) or [Glitch](https://glitch.com/).
## Guides
- [What is accessibility?](/en-US/docs/Learn/Accessibility/What_is_accessibility)
- : This article starts off the module with a good look at what accessibility is β this includes what groups of people we need to consider and why, what tools different people use to interact with the web, and how we can make accessibility part of our web development workflow.
- [HTML: A good basis for accessibility](/en-US/docs/Learn/Accessibility/HTML)
- : A great deal of web content can be made accessible just by making sure the correct HTML elements are always used for the correct purpose. This article looks in detail at how HTML can be used to ensure maximum accessibility.
- [CSS and JavaScript accessibility best practices](/en-US/docs/Learn/Accessibility/CSS_and_JavaScript)
- : CSS and JavaScript, when used properly, also have the potential to allow for accessible web experiences, but if misused they can significantly harm accessibility. This article outlines some CSS and JavaScript best practices that should be considered to ensure that even complex content is as accessible as possible.
- [WAI-ARIA basics](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics)
- : Following on from the previous article, sometimes making complex UI controls that involve unsemantic HTML and dynamic JavaScript-updated content can be difficult. WAI-ARIA is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. Here we'll show how to use it at a basic level to improve accessibility.
- [Accessible multimedia](/en-US/docs/Learn/Accessibility/Multimedia)
- : Another category of content that can create accessibility problems is multimedia β video, audio, and image content need to be given proper textual alternatives, so they can be understood by assistive technologies and their users. This article shows how.
- [Mobile accessibility](/en-US/docs/Learn/Accessibility/Mobile)
- : With web access on mobile devices being so popular, and popular platforms such as iOS and Android having fully-fledged accessibility tools, it is important to consider the accessibility of your web content on these platforms. This article looks at mobile-specific accessibility considerations.
## Assessments
- [Accessibility troubleshooting](/en-US/docs/Learn/Accessibility/Accessibility_troubleshooting)
- : In the assessment for this module, we present to you a simple site with several accessibility issues that you need to diagnose and fix.
## See also
- [Start Building Accessible Web Applications Today](https://egghead.io/courses/start-building-accessible-web-applications-today) β an excellent series of video tutorials by Marcy Sutton.
- [Deque University resources](https://dequeuniversity.com/resources/) β includes code examples, screen reader references, and other useful resources.
- [WebAIM resources](https://webaim.org/resources/) β includes guides, checklists, tools, and more.
- [Web Accessibility Evaluation Tools List](https://www.w3.org/WAI/ER/tools/) β includes a list of web accessibility evaluation tools.
| 0 |
data/mdn-content/files/en-us/learn/accessibility | data/mdn-content/files/en-us/learn/accessibility/what_is_accessibility/index.md | ---
title: What is accessibility?
slug: Learn/Accessibility/What_is_accessibility
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/Accessibility/HTML", "Learn/Accessibility")}}
This article starts the module off with a good look at what accessibility is β this overview includes what groups of people we need to consider and why, what tools different people use to interact with the web, and how we can make accessibility part of our web development workflow.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>A basic understanding of HTML and CSS.</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To gain familiarity with accessibility, including what it is, and how it
affects you as a web developer.
</td>
</tr>
</tbody>
</table>
## So what is accessibility?
Accessibility is the practice of making your websites usable by as many people as possible. We traditionally think of this as being about people with disabilities, but the practice of making sites accessible also benefits other groups such as those using mobile devices, or those with slow network connections.
You might also think of accessibility as treating everyone the same, and giving them equal opportunities, no matter what their ability or circumstances. Just as it is wrong to exclude someone from a physical building because they are in a wheelchair (modern public buildings generally have wheelchair ramps or elevators), it is also not right to exclude someone from a website because they have a visual impairment. We are all different, but we are all human, and therefore have the same human rights.
Accessibility is the right thing to do. Providing accessible sites is part of the law in some countries, which can open up some significant markets that otherwise would not be able to use your services or buy your products.
Building accessible sites benefits everyone:
- Semantic HTML, which improves accessibility, also improves SEO, making your site more findable.
- Caring about accessibility demonstrates good ethics and morals, which improves your public image.
- Other good practices that improve accessibility also make your site more usable by other groups, such as mobile phone users or those on low network speed. In fact, everyone can benefit from many such improvements.
- Did we mention it is also the law in some places?
## What kinds of disability are we looking at?
People with disabilities are just as diverse as people without disabilities, and so are their disabilities. The key lesson here is to think beyond your own computer and how you use the web, and start learning about how others use it β _you are not your users_. The main types of disability to consider are explained below, along with any special tools they use to access web content (known as **assistive technologies**, or **ATs**).
> **Note:** The World Health Organization's [Disability and health](https://www.who.int/en/news-room/fact-sheets/detail/disability-and-health) fact sheet states that "Over a billion people, about 15% of the world's population, have some form of disability", and "Between 110 million and 190 million adults have significant difficulties in functioning."
### People with visual impairments
People with visual impairments include people with blindness, low-level vision, and color blindness. Many people with visual impairments use screen magnifiers that are either physical magnifiers or software zoom capabilities. Most browsers and operating systems these days have zoom capabilities. Some users will rely on screen readers, which is software that reads digital text aloud. Some screen reader examples include:
- Paid commercial products, like [JAWS](https://www.freedomscientific.com/Products/software/JAWS/) (Windows) and [Dolphin Screen Reader](https://yourdolphin.com/en-gb/products/individuals/screen-reader) (Windows).
- Free products, like [NVDA](https://www.nvaccess.org/) (Windows), [ChromeVox](https://support.google.com/chromebook/answer/7031755) (Chrome), and [Orca](https://wiki.gnome.org/Projects/Orca) (Linux).
- Software built into the operating system, like [VoiceOver](https://www.apple.com/accessibility/vision/) (macOS, iPadOS, iOS), [Narrator](https://support.microsoft.com/en-us/windows/complete-guide-to-narrator-e4397a0d-ef4f-b386-d8ae-c172f109bdb1) (Windows), [ChromeVox](https://support.google.com/chromebook/answer/7031755) (on ChromeOS), and [TalkBack](https://play.google.com/store/apps/details?id=com.google.android.marvin.talkback) (Android).
It is a good idea to familiarize yourself with screen readers; you should also set up a screen reader and play around with it, to get an idea of how it works. See our [cross-browser testing screen readers guide](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#screen_readers) for more details on using them. The below video also provides a brief example of what the experience is like.
{{EmbedYouTube("IK97XMibEws")}}
In terms of statistics, the World Health Organization estimates that "285 million people are estimated to be visually impaired worldwide: 39 million are blind and 246 million have low vision." (see [Visual impairment and blindness](https://www.who.int/en/news-room/fact-sheets/detail/blindness-and-visual-impairment)). That's a large and significant population of users to just miss out on because your site isn't coded properly β almost the same size as the population of the United States of America.
### People with hearing impairments
[Deaf and hard-of-hearing (DHH)](https://www.nad.org/resources/american-sign-language/community-and-culture-frequently-asked-questions/) people have various levels of hearing loss ranging from mild to profound. Although some do use AT (see [Assistive Devices for People with Hearing, Voice, Speech, or Language Disorders](https://www.nidcd.nih.gov/health/assistive-devices-people-hearing-voice-speech-or-language-disorders)), they are not widespread.
To provide access, textual alternatives must be provided. Videos should be manually captioned, and transcripts should be provided for audio content. Furthermore, due to high levels of [language deprivation](https://www.therapytravelers.com/language-deprivation/#:~:text=Language%20deprivation%20is%20the%20term,therefore%20not%20exposed%20to%20language.) in DHH populations, [text simplification should be considered](https://circlcenter.org/collaborative-research-automatic-text-simplification-and-reading-assistance-to-support-self-directed-learning-by-deaf-and-hard-of-hearing-computing-workers/).
Deaf and hard-of-hearing people also represent a significant userbase β "466 million people worldwide have disabling hearing loss", says the World Health Organization's [Deafness and hearing loss](https://www.who.int/en/news-room/fact-sheets/detail/deafness-and-hearing-loss) fact sheet.
### People with mobility impairments
These people have disabilities concerning movement, which might involve purely physical issues (such as loss of limb or paralysis), or neurological/genetic disorders that lead to weakness or loss of control in limbs. Some people might have difficulty making the exact hand movements required to use a mouse, while others might be more severely affected, perhaps being significantly paralyzed to the point where they need to use a [head pointer](https://www.performancehealth.com/adjustable-headpointer) to interact with computers.
This kind of disability can also be a result of old age, rather than any specific trauma or condition, and it could also result from hardware limitations β some users might not have a mouse.
The way this usually affects web development work is the requirement that controls be accessible by the keyboard β we'll discuss keyboard accessibility in later articles in the module, but it is a good idea to try out some websites using just the keyboard to see how you get on. Can you use the Tab key to move between the different controls of a web form, for example? You can find more details about keyboard controls in our [Cross browser testing Using native keyboard accessibility](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#using_native_keyboard_accessibility) section.
In terms of statistics, a significant number of people have mobility impairments. The US Centers for Disease Control and Prevention [Disability and Functioning (Non-institutionalized Adults 18 Years and Over)](https://www.cdc.gov/nchs/fastats/disability.htm) reports the USA "Percent of adults with any physical functioning difficulty: 16.1%".
### People with cognitive impairments
Cognitive impairment refers to a broad range of disabilities, from people with intellectual disabilities who have the most-limited capabilities, to all of us as we age and have difficulty thinking and remembering. The range includes people with mental illnesses, such as [depression](https://www.nimh.nih.gov/health/topics/depression) and [schizophrenia](https://www.nimh.nih.gov/health/topics/schizophrenia). It also includes people with learning disabilities, such as [dyslexia](https://www.ninds.nih.gov/health-information/disorders/learning-disabilities) and [attention deficit hyperactivity disorder](https://www.nimh.nih.gov/health/topics/attention-deficit-hyperactivity-disorder-adhd). Importantly, though there is a lot of diversity within clinical definitions of cognitive impairments, people with them experience a common set of functional problems. These include difficulty with understanding content, remembering how to complete tasks, and confusion caused by inconsistent webpage layouts.
A good foundation of accessibility for people with cognitive impairments includes:
- Delivering content in more than one way, such as by text-to-speech or by video.
- Easily understood content, such as text written using plain-language standards.
- Focusing attention on important content.
- Minimizing distractions, such as unnecessary content or advertisements.
- Consistent webpage layout and navigation.
- Familiar elements, such as underlined links blue when not visited and purple when visited.
- Dividing processes into logical, essential steps with progress indicators.
- Website authentication as easy as possible without compromising security.
- Making forms easy to complete, such as with clear error messages and simple error recovery.
### Notes
- Designing with [cognitive accessibility](/en-US/docs/Web/Accessibility/Cognitive_accessibility) will lead to good design practices. They will benefit everyone.
- Many people with cognitive impairments also have physical disabilities. Websites must conform to the W3C's [Web Content Accessibility Guidelines](https://www.w3.org/WAI/standards-guidelines/wcag/), including [cognitive accessibility guidelines](/en-US/docs/Web/Accessibility/Cognitive_accessibility#wcag_guidelines).
- The W3C's [Cognitive and Learning Disabilities Accessibility Task Force](https://www.w3.org/WAI/GL/task-forces/coga/) produces web accessibility guidelines for people with cognitive impairments.
- WebAIM has a [Cognitive page](https://webaim.org/articles/cognitive/) of relevant information and resources.
- The United States Centers for Disease Control estimate that, as of 2018, 1 in 4 US citizens have a disability and, of them, [cognitive impairment is the most common for young people](https://archive.cdc.gov/www_cdc_gov/media/releases/2018/p0816-disability.html).
- In the US, some intellectual disabilities have historically been referred to as "mental retardation." Many now consider this term disparaging, so its use should be avoided.
- In the UK, some intellectual disabilities are referred to as "learning disabilities" or "learning difficulties".
## Implementing accessibility into your project
A common accessibility myth is that accessibility is an expensive "added extra" to implement on a project. This myth actually _can_ be true if either:
- You are trying to "retrofit" accessibility onto an existing website that has significant accessibility issues.
- You have only started to consider accessibility and uncovered related issues in the late stages of a project.
If however, you consider accessibility from the start of a project, the cost of making most content accessible should be fairly minimal.
When planning your project, factor accessibility testing into your testing regime, just like testing for any other important target audience segment (e.g., target desktop or mobile browsers). Test early and often, ideally running automated tests to pick up on programmatically detectable missing features (such as missing image [alternative text](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#text_alternatives) or bad link text β see [Element relationships and context](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#element_relationships_and_context)) and doing some testing with disabled user groups to see how well more complex site features work for them. For example:
- Is my date picker widget usable by people using screen readers?
- If content updates dynamically, do visually impaired people know about it?
- Are my UI buttons accessible to both keyboard and touch interface users?
You can and should keep a note of potential problem areas in your content that will need work to make it accessible, make sure it is tested thoroughly, and think about solutions/alternatives. Text content (as you'll see in the next article) is easy, but what about your multimedia content, and your whizzy 3D graphics? You should look at your project budget and think about what solutions you have available to make such content accessible. Having all your multimedia content transcribed is one option which, while expensive, is possible.
Also, be realistic. "100% accessibility" is an unobtainable ideal β you will always come across some kind of edge case that results in a certain user finding certain content difficult to use β but you should do as much as you can. If you are planning to include a whizzy 3D pie chart graphic made using WebGL, you might want to include a data table as an accessible alternative representation of the data. Or, you might want to just include the table and get rid of the 3D pie chart β the table is accessible by everyone, quicker to code, less CPU-intensive, and easier to maintain.
On the other hand, if you are working on a gallery website showing interesting 3D art, it would be unreasonable to expect every piece of art to be perfectly accessible to visually impaired people, given that it is an entirely visual medium.
To show that you care and have thought about accessibility, publish an accessibility statement on your site that details what your policy is toward accessibility, and what steps you have taken toward making the site accessible. If someone does notify you that your site has an accessibility problem, start a dialog with them, be empathetic, and take reasonable steps to try to fix the problem.
> **Note:** Our [Handling common accessibility problems article](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility) covers accessibility specifics that should be tested in more detail.
To summarize:
- Consider accessibility from the start of a project, and test early and often. Just like any other bug, an accessibility problem becomes more expensive to fix the later it is discovered.
- Bear in mind that a lot of accessibility best practices benefit everyone, not just users with disabilities. For example, lean semantic markup is not only good for screen readers, but it is also fast to load and performant. This benefits everyone, especially those on mobile devices and/or slow connections.
- Publish an accessibility statement on your site and engage with people having problems.
## Accessibility guidelines and the law
There are numerous checklists and sets of guidelines available for basing accessibility tests on, which might seem overwhelming at first glance. Our advice is to familiarize yourself with the basic areas in which you need to take care, as well as understanding the high-level structures of the guidelines that are most relevant to you.
- For a start, the W3C has published a large and very detailed document that includes very precise, technology-agnostic criteria for accessibility conformance. These are called the [Web Content Accessibility Guidelines](https://www.w3.org/WAI/standards-guidelines/wcag/) (WCAG), and they are not a short read by any means. The criteria are split up into four main categories, which specify how implementations can be made perceivable, operable, understandable, and robust. The best place to get a light introduction and start learning is [WCAG at a Glance](https://www.w3.org/WAI/standards-guidelines/wcag/glance/). There is no need to learn all of the WCAG criteria β be aware of the major areas of concern, and use a variety of techniques and tools to highlight any areas that don't conform to the WCAG criteria (see below for more).
- Your country may also have specific legislation governing the need for websites serving their population to be accessible β for example [EN 301 549](https://www.etsi.org/deliver/etsi_en/301500_301599/301549/02.01.02_60/en_301549v020102p.pdf) in the EU, [Section 508 of the Rehabilitation Act](https://www.section508.gov/training/) in the US, [Federal Ordinance on Barrier-Free Information Technology](https://www.einfach-fuer-alle.de/artikel/bitv_english/) in Germany, the [Accessibility Regulations 2018](https://www.legislation.gov.uk/uksi/2018/952/introduction/made) in the UK, [AccessibilitΓ ](https://www.agid.gov.it/it/design-servizi/accessibilita) in Italy, the [Disability Discrimination Act](https://humanrights.gov.au/our-work/disability-rights/world-wide-web-access-disability-discrimination-act-advisory-notes-ver) in Australia, etc. The W3C keeps a list of [Web Accessibility Laws & Policies](https://www.w3.org/WAI/policies/) by country.
So while the WCAG is a set of guidelines, your country will probably have laws governing web accessibility, or at least the accessibility of services available to the public (which could include websites, television, physical spaces, etc.) It is a good idea to find out what your laws are. If you make no effort to check that your content is accessible, you could be legally liable if people complain.
This sounds serious, but really you just need to consider accessibility as the main priority of your web development practices, as outlined above. If in doubt, get advice from a qualified lawyer. We're not going to offer any more advice than this, because we're not lawyers.
## Accessibility APIs
Web browsers make use of special **accessibility APIs** (provided by the underlying operating system) that expose information useful for assistive technologies (ATs) β ATs mostly tend to make use of semantic information, so this information doesn't include things like styling information, or JavaScript. This information is structured in a tree of information called the **accessibility tree**.
Different operating systems have different accessibility APIs available:
- Windows: MSAA/IAccessible, UIAExpress, IAccessible2
- macOS: NSAccessibility
- Linux: AT-SPI
- Android: Accessibility framework
- iOS: UIAccessibility
Where the native semantic information provided by the HTML elements in your web apps falls down, you can supplement it with features from the [WAI-ARIA specification](https://www.w3.org/TR/wai-aria/), which add semantic information to the accessibility tree to improve accessibility. You can learn a lot more about WAI-ARIA in our [WAI-ARIA basics](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics) article.
## Summary
This article should have given you a useful high-level overview of accessibility, shown you why it's important, and looked at how you can fit it into your workflow. You should now also have a thirst to learn about the implementation details that can make sites accessible, and we'll start on that in the next section, looking at why HTML is a good basis for accessibility.
{{NextMenu("Learn/Accessibility/HTML", "Learn/Accessibility")}}
## See also
- [WCAG](/en-US/docs/Web/Accessibility/Understanding_WCAG)
- [Perceivable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable)
- [Operable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable)
- [Understandable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable)
- [Robust](/en-US/docs/Web/Accessibility/Understanding_WCAG/Robust)
- [Google Chrome released an auto-captioning extension](https://blog.google/products/chrome/live-caption-chrome/)
| 0 |
data/mdn-content/files/en-us/learn/accessibility | data/mdn-content/files/en-us/learn/accessibility/html/index.md | ---
title: "HTML: A good basis for accessibility"
slug: Learn/Accessibility/HTML
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Accessibility/What_is_Accessibility","Learn/Accessibility/CSS_and_JavaScript", "Learn/Accessibility")}}
A great deal of web content can be made accessible just by making sure the correct Hypertext Markup Language elements are used for the correct purpose at all times. This article looks in detail at how HTML can be used to ensure maximum accessibility.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML (see
<a href="/en-US/docs/Learn/HTML/Introduction_to_HTML"
>Introduction to HTML</a
>), and an understanding of
<a href="/en-US/docs/Learn/Accessibility/What_is_accessibility"
>what accessibility is</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To gain familiarity with the features of HTML that have accessibility
benefits and how to use them appropriately in your web documents.
</td>
</tr>
</tbody>
</table>
## HTML and accessibility
As you learn more about HTML β read more resources, look at more examples, etc. β you'll keep seeing a common theme: the importance of using semantic HTML (sometimes called POSH, or Plain Old Semantic HTML). This means using the correct HTML elements for their intended purpose as much as possible.
You might wonder why this is so important. After all, you can use a combination of CSS and JavaScript to make just about any HTML element behave in whatever way you want. For example, a control button to play a video on your site could be marked up like this:
```html
<div>Play video</div>
```
But as you'll see in greater detail later on, it makes sense to use the correct element for the job:
```html
<button>Play video</button>
```
Not only do HTML `<button>`s have some suitable styling applied by default (which you will probably want to override), they also have built-in keyboard accessibility β users can navigate between buttons using the <kbd>Tab</kbd> key and activate their selection using <kbd>Space</kbd>, <kbd>Return</kbd> or <kbd>Enter</kbd>.
Semantic HTML doesn't take any longer to write than non-semantic (bad) markup if you do it consistently from the start of your project. Even better, semantic markup has other benefits beyond accessibility:
1. **Easier to develop with** β as mentioned above, you get some functionality for free, plus it is arguably easier to understand.
2. **Better on mobile** β semantic HTML is arguably lighter in file size than non-semantic spaghetti code, and easier to make responsive.
3. **Good for SEO** β search engines give more importance to keywords inside headings, links, etc. than keywords included in non-semantic `<div>`s, etc., so your documents will be more findable by customers.
Let's get on and look at accessible HTML in more detail.
> **Note:** It is a good idea to have a screen reader set up on your local computer so that you can do some testing of the examples shown below. See our [Screen readers guide](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#screen_readers) for more details.
## Good semantics
We've already talked about the importance of proper semantics, and why we should use the right HTML element for the job. This cannot be ignored, as it is one of the main places that accessibility is badly broken if not handled properly.
Out there on the web, the truth is that people do some very strange things with HTML markup. Some abuses of HTML are due to legacy practices that have not been completely forgotten, and some are just plain ignorance. Whatever the case, you should replace such bad code.
Sometimes you are not in the position to get rid of lousy markup β your pages might be generated by some kind of server-side framework over which you don't have full control, or you might have third party content on your page (such as ad banners) over which you have no control.
The goal isn't "all or nothing"; every improvement you can make will help the cause of accessibility.
### Text content
One of the best accessibility aids a screen reader user can have is an excellent content structure with headings, paragraphs, lists, etc. An excellent semantic example might look something like the following:
```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>
<ol>
<li>Here is</li>
<li>a list for</li>
<li>you to read</li>
</ol>
<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, which I think is more interesting
than the last one.
</p>
```
We've prepared a version with longer text for you to try out with a screen reader (see [good-semantics.html](https://mdn.github.io/learning-area/accessibility/html/good-semantics.html)). If you try navigating through this, you'll see that this is pretty easy to navigate:
1. The screen reader reads each header out as you progress through the content, notifying you what a heading is, what is a paragraph, etc.
2. It stops after each element, letting you go at whatever pace is comfortable for you.
3. You can jump to the next/previous heading in many screen readers.
4. You can also bring up a list of all headings in many screen readers, allowing you to use them as a handy table of contents to find specific content.
People sometimes write headings, paragraphs, etc. using line breaks and adding HTML elements purely for styling, something like the following:
```html example-bad
<span style="font-size: 3em">My heading</span> <br /><br />
This is the first section of my document.
<br /><br />
I'll add another paragraph here too.
<br /><br />
1. Here is
<br /><br />
2. a list for
<br /><br />
3. you to read
<br /><br />
<span style="font-size: 2.5em">My subheading</span>
<br /><br />
This is the first subsection of my document. I'd love people to be able to find
this content!
<br /><br />
<span style="font-size: 2.5em">My 2nd subheading</span>
<br /><br />
This is the second subsection of my content. I think is more interesting than
the last one.
```
If you try our longer version out with a screen reader (see [bad-semantics.html](https://mdn.github.io/learning-area/accessibility/html/bad-semantics.html)), you'll not have a very good experience β the screen reader hasn't got anything to use as signposts, so you can't retrieve a useful table of contents, and the whole page is seen as a single giant block, so it is just read out in one go, all at once.
There are other issues too beyond accessibility β it is harder to style the content using CSS, or manipulate it with JavaScript, for example, because there are no elements to use as selectors.
#### Using clear language
The language you use can also affect accessibility. In general, you should use clear language that is not overly complex and doesn't use unnecessary jargon or slang terms. This not only benefits people with cognitive or other disabilities; it benefits readers for whom the text is not written in their first language, younger peopleβ¦, everyone, in fact! Apart from this, you should try to avoid using language and characters that don't get read out clearly by the screen reader. For example:
- Don't use dashes if you can avoid it. Instead of writing 5β7, write 5 to 7.
- Expand abbreviations β instead of writing Jan, write January.
- Expand acronyms, at least once or twice, then use the [`<abbr>`](/en-US/docs/Web/HTML/Element/abbr) tag to describe them.
### Page layouts
In the bad old days, people used to create page layouts using HTML tables β using different table cells to contain the header, footer, sidebar, main content column, etc. This is not a good idea because a screen reader will likely give out confusing readouts, especially if the layout is complex and has many nested tables.
Try our example [table-layout.html](https://mdn.github.io/learning-area/accessibility/html/table-layout.html) example, which looks something like this:
```html
<table width="1200">
<!-- main heading row -->
<tr id="heading">
<td colspan="6">
<h1 align="center">Header</h1>
</td>
</tr>
<!-- nav menu row -->
<tr id="nav" bgcolor="#ffffff">
<td width="200">
<a href="#" align="center">Home</a>
</td>
<td width="200">
<a href="#" align="center">Our team</a>
</td>
<td width="200">
<a href="#" align="center">Projects</a>
</td>
<td width="200">
<a href="#" align="center">Contact</a>
</td>
<td width="300">
<form width="300">
<label
>Search
<input
type="search"
name="q"
placeholder="Search query"
width="300" />
</label>
</form>
</td>
<td width="100">
<button width="100">Go!</button>
</td>
</tr>
<!-- spacer row -->
<tr id="spacer" height="10">
<td></td>
</tr>
<!-- main content and aside row -->
<tr id="main">
<td id="content" colspan="4">
<!-- main content goes here -->
</td>
<td id="aside" colspan="2" valign="top">
<h2>Related</h2>
<!-- aside content goes here -->
</td>
</tr>
<!-- spacer row -->
<tr id="spacer" height="10">
<td></td>
</tr>
<!-- footer row -->
<tr id="footer">
<td colspan="6">
<p>Β©Copyright 1996 by nobody. All rights reversed.</p>
</td>
</tr>
</table>
```
If you try to navigate this using a screen reader, it will probably tell you that there's a table to be looked at (although some screen readers can guess the difference between table layouts and data tables). You'll then likely (depending on which screen reader you're using) have to go down into the table as an object and look at its features separately, then get out of the table again to carry on navigating the content.
Table layouts are a relic of the past β they made sense back when CSS support was not widespread in browsers, but now they just create confusion for screen reader users. Additionally, their source code requires more markup, which makes them less flexible and more difficult to maintain. You can verify these claims by comparing your previous experience with a [more modern website structure example](https://mdn.github.io/learning-area/html/introduction-to-html/document_and_website_structure/), which could look something like this:
```html
<header>
<h1>Header</h1>
</header>
<nav>
<!-- main navigation in here -->
</nav>
<!-- Here is our page's main content -->
<main>
<!-- It contains an article -->
<article>
<h2>Article heading</h2>
<!-- article content in here -->
</article>
<aside>
<h2>Related</h2>
<!-- aside content in here -->
</aside>
</main>
<!-- And here is our main footer that is used across all the pages of our website -->
<footer>
<!-- footer content in here -->
</footer>
```
If you try our more modern structure example with a screen reader, you'll see that the layout markup no longer gets in the way and confuses the content readout. It is also much leaner and smaller in terms of code size, which means easier to maintain code, and less bandwidth for the user to download (particularly prevalent for those on slow connections).
Another consideration when creating layouts is using HTML semantic elements as seen in the above example (see [content sectioning](/en-US/docs/Web/HTML/Element#content_sectioning)) β you can create a layout using only nested {{htmlelement("div")}} elements, but it is better to use appropriate sectioning elements to wrap your main navigation ({{htmlelement("nav")}}), footer ({{htmlelement("footer")}}), repeating content units ({{htmlelement("article")}}), etc. These provide extra semantics for screen readers (and other tools) to give users extra clues about the content they are navigating (see [Screen Reader Support for new HTML5 Section Elements](https://www.accessibilityoz.com/2020/02/html5-sectioning-elements-and-screen-readers/) for an idea of what screen reader support is like).
> **Note:** In addition to having good semantics and an attractive layout, 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, so what screen reader users get read out to them will make sense.
### UI controls
By UI controls, we mean the main parts of web documents that users interact with β most commonly buttons, links, and form controls. In this section, we'll look at the basic accessibility concerns to be aware of when creating such controls. Later articles on WAI-ARIA and multimedia will look at other aspects of UI accessibility.
One key aspect of the accessibility of UI controls is that by default, browsers allow them to be manipulated by the keyboard. 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:** You can enable an overlay that shows the page tabbing order in your developer tools. 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:** Different browsers may have different keyboard control options available. See [Using native keyboard accessibility](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#using_native_keyboard_accessibility) for more details.
You essentially get this behavior for free, just by using the appropriate elements, e.g.
```html example-good
<h1>Links</h1>
<p>This is a link to <a href="https://www.mozilla.org">Mozilla</a>.</p>
<p>
Another link, to the
<a href="https://developer.mozilla.org">Mozilla Developer Network</a>.
</p>
<h2>Buttons</h2>
<p>
<button data-message="This is from the first button">Click me!</button>
<button data-message="This is from the second button">Click me too!</button>
<button data-message="This is from the third button">And me!</button>
</p>
<h2>Form</h2>
<form>
<div>
<label for="name">Fill in your name:</label>
<input type="text" id="name" name="name" />
</div>
<div>
<label for="age">Enter your age:</label>
<input type="text" id="age" name="age" />
</div>
<div>
<label for="mood">Choose your mood:</label>
<select id="mood" name="mood">
<option>Happy</option>
<option>Sad</option>
<option>Angry</option>
<option>Worried</option>
</select>
</div>
</form>
```
This means using links, buttons, form elements, and labels appropriately (including the {{htmlelement("label")}} element for form controls).
However, it is again the case that people sometimes do strange things with HTML. For example, you sometimes see buttons marked up using {{htmlelement("div")}}s, for example:
```html example-bad
<div data-message="This is from the first button">Click me!</div>
<div data-message="This is from the second button">Click me too!</div>
<div data-message="This is from the third button">And me!</div>
```
But using such code is not advised β you immediately lose the native keyboard accessibility you would have had if you'd just used {{htmlelement("button")}} elements, plus you don't get any of the default CSS styling that buttons get. In the rare to non-existent case when you need to use a non-button element for a button, use the [`button` role](/en-US/docs/Web/Accessibility/ARIA/Roles/button_role) and implement all the default button behaviors, including keyboard and mouse button support.
#### Building keyboard accessibility back in
Adding such advantages back in takes a bit of work (you can see an example in our [fake-div-buttons.html](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/fake-div-buttons.html) example β also see the [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"`. We also include `role="button"` so screen reader users know they can focus on and interact with the element:
```html
<div data-message="This is from the first button" tabindex="0" role="button">
Click me!
</div>
<div data-message="This is from the second button" tabindex="0" role="button">
Click me too!
</div>
<div data-message="This is from the third button" tabindex="0" role="button">
And me!
</div>
```
Basically, the [`tabindex`](/en-US/docs/Web/HTML/Global_attributes#tabindex) attribute is primarily intended to allow tabbable elements to have a custom tab order (specified in positive numerical order), instead of just being tabbed through in their default source order. This is nearly always a bad idea, as it can cause major confusion. Use it only if you really need to, for example, if the layout shows things in a very different visual order to the source code, and you want to make things work more logically. There are two other options for `tabindex`:
- `tabindex="0"` β as indicated above, this value allows elements that are not normally tabbable to become tabbable. This is the most useful value of `tabindex`.
- `tabindex="-1"` β this allows not normally tabbable elements to receive focus programmatically, e.g., via JavaScript, or as the target of links.
While the above addition allows us to tab to the buttons, it does not allow us to activate them via the <kbd>Enter</kbd>/<kbd>Return</kbd> key. To do that, we had to add the following bit of JavaScript trickery:
```js
document.onkeydown = (e) => {
// The Enter/Return key
if (e.key === "Enter") {
document.activeElement.click();
}
};
```
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 [`key`](/en-US/docs/Web/API/KeyboardEvent/key) property; if the key pressed is <kbd>Enter</kbd>/<kbd>Return</kbd>, we run the function stored in the button's `onclick` handler using `document.activeElement.click()`. [`activeElement`](/en-US/docs/Web/API/Document/activeElement) which gives us the element that is currently focused on the page.
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.**
#### Meaningful text labels
UI control text labels are very useful to all users, but getting them right is particularly important to users with disabilities.
You should make sure that your button and link text labels are understandable and distinctive. Don't just use "Click here" for your labels, as screen reader users sometimes get up a list of buttons and form controls. The following screenshot shows our controls being listed by VoiceOver on Mac.

Make sure your labels make sense out of context, read on their own, as well as in the context of the paragraph they are in. For example, the following shows an example of good link text:
```html example-good
<p>
Whales are really awesome creatures.
<a href="whales.html">Find out more about whales</a>.
</p>
```
but this is bad link text:
```html example-bad
<p>
Whales are really awesome creatures. To find out more about whales,
<a href="whales.html">click here</a>.
</p>
```
> **Note:** You can find a lot more about link implementation and best practices in our [Creating hyperlinks](/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks) article. You can also see some good and bad examples at [good-links.html](https://mdn.github.io/learning-area/accessibility/html/good-links.html) and [bad-links.html](https://mdn.github.io/learning-area/accessibility/html/bad-links.html).
Form labels are also important for giving you a clue about what you need to enter into each form input. The following seems like a reasonable enough example:
```html example-bad
Fill in your name: <input type="text" id="name" name="name" />
```
However, this is not so useful for disabled users. There is nothing in the above example to associate the label unambiguously with the form input and make it clear how to fill it in if you cannot see it. If you access this with some screen readers, you may only be given a description along the lines of "edit text."
The following is a much better example:
```html example-good
<div>
<label for="name">Fill in your name:</label>
<input type="text" id="name" name="name" />
</div>
```
With code like this, the label will be clearly associated with the input; the description will be more like "Fill in your name: edit text."

As an added bonus, in most browsers associating a label with a form input means that you can click the label to select or activate the form element. This gives the input a bigger hit area, making it easier to select.
> **Note:** You can see some good and bad form examples in [good-form.html](https://mdn.github.io/learning-area/accessibility/html/good-form.html) and [bad-form.html](https://mdn.github.io/learning-area/accessibility/html/bad-form.html).
You can find a nice explanation of the importance of proper text labels, and how to investigate text label issues using the [Firefox Accessibility Inspector](https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/index.html), in the following video:
{{EmbedYouTube("YhlAVlfH0rQ")}}
## Accessible data tables
A basic data table can be written with very simple markup, for example:
```html
<table>
<tr>
<td>Name</td>
<td>Age</td>
<td>Pronouns</td>
</tr>
<tr>
<td>Gabriel</td>
<td>13</td>
<td>he/him</td>
</tr>
<tr>
<td>Elva</td>
<td>8</td>
<td>she/her</td>
</tr>
<tr>
<td>Freida</td>
<td>5</td>
<td>she/her</td>
</tr>
</table>
```
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 the above table (see [bad-table.html](https://mdn.github.io/learning-area/accessibility/html/bad-table.html) and try the example out yourself).
Now have a look at our [punk bands table example](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:
- Table headers are defined using {{htmlelement("th")}} elements β you can also specify if they are headers for rows or columns using the `scope` attribute. This gives you complete groups of data that can be consumed by screen readers as single units.
- The {{htmlelement("caption")}} element and the `<table>` element's `summary` attribute both do similar jobs β they act as alt text for a table, giving a screen reader user a useful quick summary of the table's contents. The `<caption>` element is generally preferred as it makes it's content accessible to sighted users too, who might also find it useful. You don't really need both.
> **Note:** See our [HTML table advanced features and accessibility](/en-US/docs/Learn/HTML/Tables/Advanced) article for more details about accessible data tables.
## Text alternatives
Whereas textual content is inherently accessible, the same cannot necessarily be said for multimedia content β image and video content cannot be seen by visually-impaired people, and audio content cannot be heard by hearing-impaired people. We cover video and audio content in detail in the [Accessible multimedia](/en-US/docs/Learn/Accessibility/Multimedia), but for this article we'll look at accessibility for the humble {{htmlelement("img")}} element.
We have a simple example written up, [accessible-image.html](https://mdn.github.io/learning-area/accessibility/html/accessible-image.html), which features four copies of the same image:
```html
<img src="dinosaur.png" />
<img
src="dinosaur.png"
alt="A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth." />
<img
src="dinosaur.png"
alt="A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth."
title="The Mozilla red dinosaur" />
<img src="dinosaur.png" aria-labelledby="dino-label" />
<p id="dino-label">
The Mozilla red Tyrannosaurus Rex: A two legged dinosaur standing upright like
a human, with small arms, and a large head with lots of sharp teeth.
</p>
```
The first image, when viewed by a screen reader, doesn't really offer the user much help β VoiceOver for example reads out "/dinosaur.png, image". It reads out the filename to try to provide some help. In this example the user will at least know it is a dinosaur of some kind, but often files may be uploaded with machine-generated file names (e.g. from a digital camera) and these file names would likely provide no context to the image's content.
> **Note:** This is why you should never include text content inside an image β screen readers can't access it. There are other disadvantages too β you can't select it and copy/paste it. Just don't do it!
When a screen reader encounters the second image, it reads out the full alt attribute β "A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth.".
This highlights the importance of not only using meaningful file names in case so-called **alt text** is not available, but also making sure that alt text is provided in `alt` attributes wherever possible.
Note that the contents of the `alt` attribute should always provide a direct representation of the image and what it conveys visually. The alt should be brief and concise and include all the information conveyed in the image that is not duplicated in the surrounding text.
The content of the `alt` attribute for a single image differs based on the context. For example, if the photo of Fluffy is an avatar next to a review for Yuckymeat dog food, `alt="Fluffy"` is appropriate. If the photo is part of Fluffy's adoption page for the animal rescue society, information conveyed in the image that is relevant for a prospective dog parent that is not duplicated in the surrounding text should be included. A longer description, such as `alt="Fluffy, a tri-color terrier with very short hair, with a tennis ball in her mouth."` is appropriate. As the surrounding text likely has Fluffy's size and breed, that is not included in the `alt`. However, as the dog's biography likely doesn't include hair length, colors, or toy preferences, which the potential parent needs to know, it is included. Is the image outdoors, or does Fluffy have a red collar with a blue leash? Not important in terms of adopting the pet and therefore not included. All information image conveys that a sited user can access and is relevant to the context is what needs to be conveyed; nothing more. Keep it short, precise, and useful.
Any personal knowledge or extra description shouldn't be included here, as it is not useful for people who have not seen the image before. If the ball is Fluffy's favorite toy or if the sited user can't know that from the image, then don't include it.
One thing to consider is whether your images have meaning inside your content, or whether they are purely for visual decoration, and thus have no meaning. If they are decorative, it is better to write an empty text as a value for `alt` attribute (see [Empty alt attributes](#empty_alt_attributes)) or to just include them in the page as CSS background images.
> **Note:** Read [Images in HTML](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML) and [Responsive images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images) for a lot more information about image implementation and best practices.
If you do want to provide extra contextual information, you should put it in the text surrounding the image, or inside a `title` attribute, as shown above. In this case, most screen readers will read out the alt text, the title attribute, and the filename. In addition, browsers display title text as tooltips when moused over.

Let's have another quick look at the fourth method:
```html
<img src="dinosaur.png" aria-labelledby="dino-label" />
<p id="dino-label">The Mozilla red Tyrannosaurusβ¦</p>
```
In this case, we are not using the `alt` attribute at all β instead, we have presented our description of the image as a regular text paragraph, given it an `id`, and then used the `aria-labelledby` attribute to refer to that `id`, which causes screen readers to use that paragraph as the alt text/label for that image. This is especially useful if you want to use the same text as a label for multiple images β something that isn't possible with `alt`.
> **Note:** [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) is part of the [WAI-ARIA](https://www.w3.org/TR/wai-aria-1.1/) spec, which allows developers to add in extra semantics to their markup to improve screen reader accessibility where needed. To learn more about how it works, read our [WAI-ARIA Basics](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics) article.
### Figures and figure captions
HTML includes two elements β {{htmlelement("figure")}} and {{htmlelement("figcaption")}} β which associate a figure of some kind (it could be anything, not necessarily an image) with a figure caption:
```html
<figure>
<img
src="dinosaur.png"
alt="The Mozilla Tyrannosaurus"
aria-describedby="dinodescr" />
<figcaption id="dinodescr">
A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a
human, with small arms, and a large head with lots of sharp teeth.
</figcaption>
</figure>
```
While there is mixed screen reader support of associating figure captions with their figures, including [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) creates the association if none is present. That said, the element structure is useful for CSS styling, plus it provides a way to place a description of the image next to it in the source.
### Empty alt attributes
```html
<h3>
<img src="article-icon.png" alt="" />
Tyrannosaurus Rex: the king of the dinosaurs
</h3>
```
There may be times where an image is included in a page's design, but its primary purpose is for visual decoration. You'll notice in the code example above that the image's `alt` attribute is empty β this is to make screen readers recognize the image, but not attempt to describe the image (instead they'd just say "image", or similar).
The reason to use an empty `alt` instead of not including it is because many screen readers announce the whole image URL if no `alt` is provided. In the above example, the image is acting as a visual decoration to the heading it's associated with. In cases like this, and in cases where an image is only decoration and has no content value, you should include an empty `alt` in your `img` elements. Another alternative is to use the aria [`role`](/en-US/docs/Web/Accessibility/ARIA/Roles) attribute [`role="presentation"`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) as this also stops screen readers from reading out alternative text.
> **Note:** If possible you should use CSS to display images that are only decorative.
## More on links
Links (the [`<a>`](/en-US/docs/Web/HTML/Element/a) element with an `href` attribute), depending on how they are used, can help or harm accessibility. By default, links are accessible in appearance. They can improve accessibility by helping a user quickly navigate to different sections of a document. They can also harm accessibility if their accessible styling is removed or if JavaScript causes them to behave in unexpected ways.
### Link styling
By default, links are visually different from other text in both color and [text-decoration](/en-US/docs/Web/CSS/text-decoration), with links being blue and underlined by default, purple and underlined if visited, and with a [focus-ring](/en-US/docs/Web/CSS/:focus) when they receive keyboard focus.
Color should not be used as the sole method of distinguishing links from non-linking content. Link text color, like all text, has to be significantly different from the background color ([a 4.5:1 contrast](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast)). In addition, links should visually be significantly different from non-linking text, with a minimum contrast requirement of 3:1 between link text and surrounding text and between default, visited, and focus/active states and a 4.5:1 contrast between all those state colors and the background color.
### `onclick` events
Anchor tags are often abused with the `onclick` event to create pseudo-buttons by setting **href** to `"#"` or `"javascript:void(0)"` to prevent the page from refreshing.
These values cause unexpected behavior when copying or dragging links, opening links in a new tab or window, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a {{HTMLElement("button")}} instead. In general you should only use an anchor for navigation using a proper URL.
### External links and linking to non-HTML resources
Links that open in a new tab or window via the `target="_blank"` declaration and links to whose `href` value points to a file resource should include an indicator about the behavior that will occur when the link is activated.
People experiencing low vision conditions, who are navigating with the aid of screen reading technology, or who have cognitive concerns may become confused when the new tab, window, or application is opened unexpectedly. Older versions of screen reading software may not even announce the behavior.
#### Link that opens a new tab or window
```html
<a target="_blank" href="https://www.wikipedia.org/"
>Wikipedia (opens in a new window)</a
>
```
#### Link to a non-HTML resource
```html
<a target="_blank" href="2017-annual-report.ppt"
>2017 Annual Report (PowerPoint)</a
>
```
If an icon is used in place of text to signify this kind of links behavior, make sure it includes an [alternate description](/en-US/docs/Web/HTML/Element/img#alt).
- [WebAIM: Links and Hypertext - Hypertext Links](https://webaim.org/techniques/hypertext/hypertext_links)
- [MDN Understanding WCAG, Guideline 3.2 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable#guideline_3.2_β_predictable_make_web_pages_appear_and_operate_in_predictable_ways)
- [G200: Opening new windows and tabs from a link only when necessary | W3C Techniques for WCAG 2.0](https://www.w3.org/TR/WCAG20-TECHS/G200.html)
- [G201: Giving users advanced warning when opening a new window | W3C Techniques for WCAG 2.0](https://www.w3.org/TR/WCAG20-TECHS/G201.html)
### Skip links
A skip link, also known as skipnav, is an `a` element placed as close as possible to the opening {{HTMLElement("body")}} element that links to the beginning of the page's main content. This link allows people to bypass content repeated throughout multiple pages on a website, such as a website's header and primary navigation.
Skip links are especially useful for people who navigate with the aid of assistive technology such as switch control, voice command, or mouth sticks/head wands, where the act of moving through repetitive links can be a laborious task.
- [WebAIM: "Skip Navigation" Links](https://webaim.org/techniques/skipnav/)
- [Howβto: Use Skip Navigation links - The A11Y Project](https://www.a11yproject.com/posts/skip-nav-links/)
- [MDN Understanding WCAG, Guideline 2.4 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.4_%e2%80%94_navigable_provide_ways_to_help_users_navigate_find_content_and_determine_where_they_are)
- [Understanding Success Criterion 2.4.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-skip.html)
### Proximity
Large amounts of interactive contentβincluding anchorsβplaced in close visual proximity to each other should have space inserted to separate them. This spacing is beneficial for people who suffer from fine motor control issues and may accidentally activate the wrong interactive content while navigating.
Spacing may be created using CSS properties such as {{CSSxRef("margin")}}.
- [Hand tremors and the giant-button-problem - Axess Lab](https://axesslab.com/hand-tremors/)
## Test your skills!
You've reached the end of this article, but can you remember the most important information? See [Test your skills: HTML Accessibility](/en-US/docs/Learn/Accessibility/Test_your_skills:_HTML_accessibility) to verify that you've retained this information before you move on.
## Summary
You should now be well-versed in writing accessible HTML for most occasions. Our WAI-ARIA basics article will help to fill gaps in this knowledge, but this article has taken care of the basics. Next up we'll explore CSS and JavaScript, and how accessibility is affected by their good or bad use.
{{PreviousMenuNext("Learn/Accessibility/What_is_Accessibility","Learn/Accessibility/CSS_and_JavaScript", "Learn/Accessibility")}}
| 0 |
data/mdn-content/files/en-us/learn/accessibility | data/mdn-content/files/en-us/learn/accessibility/mobile/index.md | ---
title: Mobile accessibility
slug: Learn/Accessibility/Mobile
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Accessibility/Multimedia","Learn/Accessibility/Accessibility_troubleshooting", "Learn/Accessibility")}}
With web access on mobile devices being so popular and renowned platforms such as iOS and Android having full-fledged accessibility tools, it is important to consider the accessibility of your web content on these platforms. This article looks at mobile-specific accessibility considerations.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML, CSS, and
JavaScript. An understanding of the
<a href="/en-US/docs/Learn/Accessibility"
>previous articles in the course</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand what problems exist with accessibility on mobile devices,
and how to overcome them.
</td>
</tr>
</tbody>
</table>
## Accessibility on mobile devices
The state of accessibility β and support for web standards in general β is good in modern mobile devices. Long gone are the days when mobile devices ran completely different web technologies to desktop browsers, forcing developers to use browser sniffing and serve them completely separate sites (although quite a few companies still detect usage of mobile devices and serve them a separate mobile domain).
These days, mobile devices can usually handle fully-featured websites, and the main platforms even have screen readers built in to enable visually impaired users to use them successfully. Modern mobile browsers tend to have good support for [WAI-ARIA](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics), too.
To make a website accessible and usable on mobile, you just need to follow general good web design and accessibility best practices.
There are some exceptions that need special consideration for mobile; the main ones are:
- Control mechanisms β Make sure interface controls such as buttons are accessible on mobiles (i.e., mainly touchscreen), as well as desktops/laptops (mainly mouse/keyboard).
- User input β Make user input requirements as painless as possible on mobile (e.g., in forms, keep typing to a minimum).
- Responsive design β Make sure layouts work on mobile, conserve image download sizes, and think about the provision of images for high-resolution screens.
## Summary of screen reader testing on Android and iOS
The most common mobile platforms have fully functional screen readers. These function in much the same way as desktop screen readers, except they are largely operated using touch gestures rather than key combinations.
Let's look at the main two: TalkBack on Android and VoiceOver on iOS.
### Android TalkBack
The TalkBack screen reader is built into the Android operating system.
To turn it on, look up what phone model and Android version you have, and then look up where the TalkBack menu is. It tends to differ widely between Android versions and even between different phone models. Some phone manufacturers (e.g. Samsung) don't even have TalkBack in newer phones, and instead opted for their own screen reader.
When you've found the TalkBack menu, press the slider switch to turn TalkBack on. Follow any additional on-screen prompts that you are presented with.
When TalkBack is turned on, your Android device's basic controls will be a bit different. For example:
1. Single-tapping an app will select it, and the device will read out what the app is.
2. Swiping left and right will move between apps, or buttons/controls if you are in a control bar. The device will read out each option.
3. Double-tapping anywhere will open the app/select the option.
4. You can also "explore by touch" β hold your finger down on the screen and drag it around, and your device will read out the different apps/items you move across.
If you want to turn TalkBack off:
1. Navigate back to the TalkBack menu screen (using the different gestures that are currently enabled.)
2. Navigate to the slider switch and activate it to turn it off.
> **Note:** You can get to your home screen at any time by swiping up and left in a smooth motion. If you have more than one home screen, you can move between them by swiping two fingers left and right.
For a more complete list of TalkBack gestures, see [Use TalkBack gestures](https://support.google.com/accessibility/android/answer/6151827).
#### Unlocking the phone
When TalkBack is turned on, unlocking the phone is a bit different.
You can do a two-finger swipe up from the bottom of the lock screen. If you've set a passcode or pattern for unlocking your device, you will then be taken to the relevant entry screen to enter it.
You can also explore by touch to find the _Unlock_ button at the bottom middle of the screen, and then double-tap.
#### Global and local menus
TalkBack allows you to access global and local context menus, wherever you have navigated on the device. The former provides global options relating to the device as a whole, and the latter provides options relating just to the current app/screen you are in.
To get to these menus:
1. Access the global menu by quickly swiping down, and then right.
2. Access the local menu by quickly swiping up, and then right.
3. Swipe left and right to cycle between the different options.
4. Once you've selected the option you want, double-tap to choose that option.
For details on all the options available under the global and local context menus, see [Use global and local context menus](https://support.google.com/accessibility/android/answer/6007066).
#### Browsing web pages
You can use the local context menu while in a web browser to find options to navigate web pages using just the headings, form controls, or links, or navigate line by line, etc.
For example, with TalkBack turned on:
1. Open your web browser.
2. Activate the URL bar.
3. Enter a web page that has a bunch of headings on it, such as the front page of bbc.co.uk. To enter the text of the URL:
- Select the URL bar by swiping left/right till you get to it, and then double-tapping.
- Hold your finger down on the virtual keyboard until you get the character you want, and then release your finger to type it. Repeat for each character.
- Once you've finished, find the Enter key and press it.
4. Swipe left and right to move between different items on the page.
5. Swipe up and right with a smooth motion to enter the local content menu.
6. Swipe right until you find the "Headings and Landmarks" option.
7. Double-tap to select it. Now you'll be able to swipe left and right to move between headings and ARIA landmarks.
8. To go back to the default mode, enter the local context menu again by swiping up and right, select "Default", and then double-tap to activate.
> **Note:** See [Get started on Android with TalkBack](https://support.google.com/accessibility/android/answer/6283677?hl=en&ref_topic=3529932) for more complete documentation.
### iOS VoiceOver
A mobile version of VoiceOver is built into the iOS operating system.
To turn it on, go to Your _Settings_ app and select _Accessibility > VoiceOver_. Press the _VoiceOver_ slider to enable it (you'll also see several other options related to VoiceOver on this page).
> **Note:** Some older iOS devices have the VoiceOver menu at _Settings app_ > _General_ > _Accessibility_ > _VoiceOver_.
Once VoiceOver is enabled, iOS's basic control gestures will be a bit different:
1. A single tap will cause the item you tap on to be selected; your device will speak the item you've tapped on.
2. You can also navigate the items on the screen by swiping left and right to move between them, or by sliding your finger around on the screen to move between different items (when you find the item you want, you can remove your finger to select it).
3. To activate the selected item (e.g., open a selected app), double-tap anywhere on the screen.
4. Swipe with three fingers to scroll through a page.
5. Tap with two fingers to perform a context-relevant action β for example, taking a photo while in the camera app.
To turn it off again, navigate back to _Settings > General > Accessibility > VoiceOver_ using the above gestures, and toggle the _VoiceOver_ slider back to off.
#### Unlock phone
To unlock the phone, you need to press the home button (or swipe) as normal. If you have a passcode set, you can select each number by swiping/sliding (as explained above) and then double-tapping to enter each number when you've found the right one.
#### Using the Rotor
When VoiceOver is turned on, you have a navigation feature called the Rotor available to you, which allows you to quickly choose from a number of common useful options. To use it:
1. Twist two fingers around on the screen like you are turning a dial. Each option will be read aloud as you twist further around. You can go back and forth to cycle through the options.
2. Once you've found the option you want:
- Release your fingers to select it.
- If it is an option you can iterate the value of (such as Volume or Speaking Rate), you can do a swipe up or down to increase or decrease the value of the selected item.
The options available under the Rotor are context-sensitive β they will differ depending on what app or view you are in (see below for an example).
#### Browsing web pages
Let's have a go at web browsing with VoiceOver:
1. Open your web browser.
2. Activate the URL bar.
3. Enter a web page that has a bunch of headings on it, such as the front page of bbc.co.uk. To enter the text of the URL:
- Select the URL bar by swiping left/right until you get to it, and then double-tapping.
- For each character, hold your finger down on the virtual keyboard until you get the character you want, and then release your finger to select it. Double-tap to type it.
- Once you've finished, find the Enter key and press it.
4. Swipe left and right to move between items on the page. You can double-tap an item to select it (e.g., follow a link).
5. By default, the selected Rotor option will be Speaking Rate; you can currently swipe up and down to increase or decrease the speaking rate.
6. Now turn two fingers around the screen like a dial to show the rotor and move between its options. Here are a few examples of the options available:
- _Speaking Rate_: Change the speaking rate.
- _Containers_: Move between different semantic containers on the page.
- _Headings_: Move between headings on the page.
- _Links_: Move between links on the page.
- _Form Controls_: Move between form controls on the page.
- _Language_: Move between different translations, if they are available.
7. Select _Headings_. Now you'll be able to swipe up and down to move between headings on the page.
> **Note:** For a more complete reference covering the VoiceOver gestures available and other hints on accessibility testing on iOS, see [Test Accessibility on Your Device with VoiceOver](https://developer.apple.com/library/archive/technotes/TestingAccessibilityOfiOSApps/TestAccessibilityonYourDevicewithVoiceOver/TestAccessibilityonYourDevicewithVoiceOver.html).
## Control mechanisms
In our CSS and JavaScript accessibility article, we looked at the idea of events that are specific to a certain type of control mechanism (see [Mouse-specific events](/en-US/docs/Learn/Accessibility/CSS_and_JavaScript#mouse-specific_events)). To recap, these cause accessibility issues because other control mechanisms can't activate the associated functionality.
As an example, the [click](/en-US/docs/Web/API/Element/click_event) event is good in terms of accessibility β an associated event handler can be invoked by clicking the element the handler is set on, tabbing to it and pressing Enter/Return, or tapping it on a touchscreen device. Try our [simple-button-example.html](https://github.com/mdn/learning-area/blob/main/accessibility/mobile/simple-button-example.html) example ([see it running live](https://mdn.github.io/learning-area/accessibility/mobile/simple-button-example.html)) to see what we mean.
Alternatively, mouse-specific events such as [mousedown](/en-US/docs/Web/API/Element/mousedown_event) and [mouseup](/en-US/docs/Web/API/Element/mouseup_event) create problems β their event handlers cannot be invoked using non-mouse controls.
If you try to control our [simple-box-drag.html](https://github.com/mdn/learning-area/blob/main/accessibility/mobile/simple-box-drag.html) ([see example live](https://mdn.github.io/learning-area/accessibility/mobile/simple-box-drag.html)) example with a keyboard or touch, you'll see the problem. This occurs because we are using code such as the following:
```js
div.onmousedown = () => {
initialBoxX = div.offsetLeft;
initialBoxY = div.offsetTop;
movePanel();
};
document.onmouseup = stopMove;
```
To enable other forms of control, you need to use different, yet equivalent events β for example, touch events work on touchscreen devices:
```js
div.ontouchstart = (e) => {
initialBoxX = div.offsetLeft;
initialBoxY = div.offsetTop;
positionHandler(e);
movePanel();
};
panel.ontouchend = stopMove;
```
We've provided a simple example that shows how to use the mouse and touch events together β see [multi-control-box-drag.html](https://github.com/mdn/learning-area/blob/main/accessibility/mobile/multi-control-box-drag.html) ([see the example live](https://mdn.github.io/learning-area/accessibility/mobile/multi-control-box-drag.html) also).
> **Note:** You can also see fully functional examples showing how to implement different control mechanisms at [Implementing game control mechanisms](/en-US/docs/Games/Techniques/Control_mechanisms).
## Responsive design
[Responsive design](/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design) is the practice of making your layouts and other features of your apps dynamically change depending on factors such as screen size and resolution, so they are usable and accessible to users of different device types.
In particular, the most common problems that need to be addressed for mobile are:
- Suitability of layouts for mobile devices. A multi-column layout won't work as well on a narrow screen, for example, and the text size may need to be increased so it is legible. Such issues can be solved by creating a responsive layout using technologies such as [media queries](/en-US/docs/Web/CSS/CSS_media_queries), [viewport](/en-US/docs/Web/HTML/Viewport_meta_tag), and [flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox).
- Conserving image sizes downloaded. In general, small-screen devices won't need images that are as large as their desktop counterparts, and they are more likely to be on slow network connections. Therefore, it is wise to serve smaller images to narrow screen devices as appropriate. You can handle this using [responsive image techniques](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images).
- Thinking about high resolutions. Many mobile devices have high-resolution screens, and therefore need higher-resolution images so that the display can continue to look crisp and sharp. Again, you can serve images as appropriate using responsive image techniques. In addition, many image requirements can be fulfilled using the SVG vector images format, which is well-supported across browsers today. SVG has a small file size and will stay sharp regardless of whatever size is being displayed (see [Adding vector graphics to the web](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web) for more details).
> **Note:** We won't provide a full discussion of responsive design techniques here, as they are covered in other places around MDN (see the above links).
### Specific mobile considerations
There are other important issues to consider when making sites more accessible on mobile. We have listed a couple here, but we will add more when we think of them.
#### Not disabling zoom
Using [viewport](/en-US/docs/Web/HTML/Viewport_meta_tag), it is possible to disable zoom. Always ensure resizing is enabled, and set the width to the device's width in the {{htmlelement("head")}}:
```html
<meta name="viewport" content="width=device-width; user-scalable=yes" />
```
You should never set `user-scalable=no` if at all possible β many people rely on zoom to be able to see the content of your website, so taking this functionality away is a really bad idea. There are certain situations where zooming might break the UI; in such cases, if you feel that you need to disable zoom, you should provide some other kind of equivalent, such as a control for increasing the text size in a way that doesn't break your UI.
#### Keeping menus accessible
Because the screen is so much narrower on mobile devices, it is very common to use media queries and other technologies to make the navigation menu shrink down to a tiny icon at the top of the display β which can be pressed to reveal the menu only if it's needed β when the site is viewed on mobile. This is commonly represented by a "three horizontal lines" icon, and the design pattern is consequently known as a "hamburger menu".
When implementing such a menu, you need to make sure that the control to reveal it is accessible by appropriate control mechanisms (normally touch for mobile), as discussed in [Control mechanisms](#control_mechanisms) above, and that the rest of the page is moved out of the way or hidden in some way while the menu is being accessed, to avoid confusion with navigating it.
Click here for a [good hamburger menu example](https://fritz-weisshart.de/meg_men/).
## User input
On mobile devices, inputting data tends to be more annoying for users than the equivalent experience on desktop computers. It is more convenient to type text into form inputs using a desktop or laptop keyboard than a touchscreen virtual keyboard or a tiny mobile physical keyboard.
For this reason, it is worth trying to minimize the amount of typing needed. As an example, instead of getting users to fill out their job title each time using a regular text input, you could instead offer a {{htmlelement("select")}} menu containing the most common options (which also helps with consistency in data entry) and offer an "Other" option that displays a text field to type any outliers into. You can see a simple example of this idea in action in [common-job-types.html](https://github.com/mdn/learning-area/blob/main/accessibility/mobile/common-job-types.html) (see the [common jobs example live](https://mdn.github.io/learning-area/accessibility/mobile/common-job-types.html)).
It is also worth considering the use of HTML form input types such as the date on mobile platforms as they handle them well β both Android and iOS, for example, display usable widgets that fit well with the device experience. See [html5-form-examples.html](https://github.com/mdn/learning-area/blob/main/accessibility/mobile/html5-form-examples.html) for some examples (see the [HTML5 form examples live](https://mdn.github.io/learning-area/accessibility/mobile/html5-form-examples.html)) β try loading these and manipulating them on mobile devices. For example:
- Types `number`, `tel`, and `email` display suitable virtual keyboards for entering numbers/telephone numbers.
- Types `time` and `date` display suitable pickers for selecting times and dates.
If you want to provide a different solution for desktops, you could always serve different markup to your mobile devices using feature detection. See [input types](https://diveinto.html5doctor.com/detect.html#input-types) for raw information on detecting different input types, and also check out our [feature detection article](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Feature_detection) for much more information.
## Summary
In this article, we have provided you with some details about common mobile accessibility-specific issues and how to overcome them. We also took you through the usage of the most common screen readers to aid you in accessibility testing.
## See also
- [Guidelines For Mobile Web Development](https://www.smashingmagazine.com/2012/07/guidelines-for-mobile-web-development/) β A list of articles in _Smashing Magazine_ covering different techniques for mobile web design.
- [Make your site work on touch devices](https://www.creativebloq.com/javascript/make-your-site-work-touch-devices-51411644) β Useful article about using touch events to get interactions working on mobile devices.
{{PreviousMenuNext("Learn/Accessibility/Multimedia","Learn/Accessibility/Accessibility_troubleshooting", "Learn/Accessibility")}}
| 0 |
data/mdn-content/files/en-us/learn/accessibility | data/mdn-content/files/en-us/learn/accessibility/multimedia/index.md | ---
title: Accessible multimedia
slug: Learn/Accessibility/Multimedia
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Accessibility/WAI-ARIA_basics","Learn/Accessibility/Mobile", "Learn/Accessibility")}}
Another category of content that can create accessibility problems is multimedia. Video, audio, and image content need to be given proper textual alternatives so that they can be understood by assistive technologies and their users. This article shows how.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML, CSS, JavaScript, and an understanding of
<a href="/en-US/docs/Learn/Accessibility/What_is_accessibility"
>what accessibility is</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the accessibility issues behind multimedia, and how to
overcome them.
</td>
</tr>
</tbody>
</table>
## Multimedia and accessibility
So far in this module, we have looked at a variety of content and what needs to be done to ensure its accessibility, ranging from simple text content to data tables, images, native controls such as form elements and buttons, and even more complex markup structures (with [WAI-ARIA](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics) attributes).
This article on the other hand looks at another general class of content that arguably isn't as easy to ensure accessibility for β multimedia. Images, audio tracks, videos, {{htmlelement("canvas")}} elements, etc., aren't as easily understood by screen readers or navigated by the keyboard, and we need to give them a helping hand.
But don't despair β here we will help you navigate through the techniques available for making multimedia more accessible.
## Simple images
We already covered simple text alternatives for HTML images in our [HTML: A good basis for accessibility](/en-US/docs/Learn/Accessibility/HTML) article β you can refer back to there for the full details. In short, you should ensure that where possible visual content has an alternative text available for screen readers to pick up and read to their users.
For example:
```html
<img
src="dinosaur.png"
alt="A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth." />
```
## Accessible audio and video controls
Implementing controls for web-based audio/video shouldn't be a problem, right? Let's investigate.
### The problem with native HTML controls
HTML video and audio instances even come with a set of inbuilt controls that allow you to control the media straight out of the box. For example (see `native-controls.html` [source code](https://github.com/mdn/learning-area/blob/main/accessibility/multimedia/native-controls.html) and [live](https://mdn.github.io/learning-area/accessibility/multimedia/native-controls.html)):
```html
<audio controls>
<source src="viper.mp3" type="audio/mp3" />
<source src="viper.ogg" type="audio/ogg" />
<p>
Your browser doesn't support HTML audio. Here is a
<a href="viper.mp3">link to the audio</a> instead.
</p>
</audio>
<br />
<video controls>
<source src="rabbit320.mp4" type="video/mp4" />
<source src="rabbit320.webm" type="video/webm" />
<p>
Your browser doesn't support HTML video. Here is a
<a href="rabbit320.mp4">link to the video</a> instead.
</p>
</video>
```
The controls attribute provides play/pause buttons, seek bar, etc. β the basic controls you'd expect from a media player. It looks like so in Firefox and Chrome:


However, there are problems with these controls:
- They are not keyboard-accessible in most browsers, i.e. you can't tab between the controls inside the native player. Opera and Chrome provide this to some degree, but it still isn't ideal.
- Different browsers give the native controls differing styling and functionality, and they aren't stylable, meaning that they can't be easily made to follow a site style guide.
To remedy this, we can create our own custom controls. Let's look at how.
### Creating custom audio and video controls
HTML video and audio share an API β HTML Media Element β which allows you to map custom functionality to buttons and other controls β both of which you define yourself.
Let's take the video example from above and add custom controls to them.
#### Basic setup
First, grab a copy of our [custom-controls-start.html](https://github.com/mdn/learning-area/blob/main/accessibility/multimedia/custom-controls-start.html), [custom-controls.css](https://github.com/mdn/learning-area/blob/main/accessibility/multimedia/custom-controls.css), [rabbit320.mp4](https://raw.githubusercontent.com/mdn/learning-area/master/accessibility/multimedia/rabbit320.mp4), and [rabbit320.webm](https://raw.githubusercontent.com/mdn/learning-area/master/accessibility/multimedia/rabbit320.webm) files and save them in a new directory on your hard drive.
Create a new file called main.js and save it in the same directory.
First of all, let's look at the HTML for the video player, in the HTML:
```html
<section class="player">
<video controls>
<source src="rabbit320.mp4" type="video/mp4" />
<source src="rabbit320.webm" type="video/webm" />
<p>
Your browser doesn't support HTML video. Here is a
<a href="rabbit320.mp4">link to the video</a> instead.
</p>
</video>
<div class="controls">
<button class="playpause">Play</button>
<button class="stop">Stop</button>
<button class="rwd">Rwd</button>
<button class="fwd">Fwd</button>
<div class="time">00:00</div>
</div>
</section>
```
#### JavaScript basic setup
We've inserted some simple control buttons below our video. These controls of course won't do anything by default; to add functionality, we will use JavaScript.
We will first need to store references to each of the controls β add the following to the top of your JavaScript file:
```js
const playPauseBtn = document.querySelector(".playpause");
const stopBtn = document.querySelector(".stop");
const rwdBtn = document.querySelector(".rwd");
const fwdBtn = document.querySelector(".fwd");
const timeLabel = document.querySelector(".time");
```
Next, we need to grab a reference to the video/audio player itself β add this line below the previous lines:
```js
const player = document.querySelector("video");
```
This holds a reference to a {{domxref("HTMLMediaElement")}} object, which has several useful properties and methods available on it that can be used to wire up functionality to our buttons.
Before moving on to creating our button functionality, let's remove the native controls so they don't get in the way of our custom controls. Add the following, again at the bottom of your JavaScript:
```js
player.removeAttribute("controls");
```
Doing it this way round rather than just not including the controls attribute in the first place has the advantage that if our JavaScript fails for any reason, the user still has some controls available.
#### Wiring up our buttons
First, let's set up the play/pause button. We can get this to toggle between play and pause with a simple conditional function, like the following. Add it to your code, at the bottom:
```js
playPauseBtn.onclick = () => {
if (player.paused) {
player.play();
playPauseBtn.textContent = "Pause";
} else {
player.pause();
playPauseBtn.textContent = "Play";
}
};
```
Next, add this code to the bottom, which controls the stop button:
```js
stopBtn.onclick = () => {
player.pause();
player.currentTime = 0;
playPauseBtn.textContent = "Play";
};
```
There is no `stop()` function available on {{domxref("HTMLMediaElement")}}s, so instead we `pause()` it, and at the same time set the `currentTime` to 0.
Next, our rewind and fast-forward buttons β add the following blocks to the bottom of your code:
```js
rwdBtn.onclick = () => {
player.currentTime -= 3;
};
fwdBtn.onclick = () => {
player.currentTime += 3;
if (player.currentTime >= player.duration || player.paused) {
player.pause();
player.currentTime = 0;
playPauseBtn.textContent = "Play";
}
};
```
These are very simple, just adding or subtracting 3 seconds to the `currentTime` each time they are clicked. In a real video player, you'd probably want a more elaborate seeking bar, or similar.
Note that we also check to see if the `currentTime` is more than the total media `duration` or if the media is not playing when the `fwdBtn` is pressed. If either condition is true, we stop the video to avoid the user interface going wrong if they attempt to fast forward when the video is not playing or fast forward past the end of the video.
Last of all, add the following to the end of the code, to control the time elapsed display:
```js
player.ontimeupdate = () => {
const minutes = Math.floor(player.currentTime / 60);
const seconds = Math.floor(player.currentTime - minutes * 60);
const minuteValue = minutes < 10 ? `0${minutes}` : minutes;
const secondValue = seconds < 10 ? `0${seconds}` : seconds;
const mediaTime = `${minuteValue}:${secondValue}`;
timeLabel.textContent = mediaTime;
};
```
Each time the time updates (once per second), we fire this function. It works out the number of minutes and seconds from the given currentTime value (which is in seconds), adds a leading 0 if either the minute or second value is less than 10, and then creates the display readout and adds it to the time label.
#### Further reading
This gives you a basic idea of how to add custom player functionality to video/audio player instances. For more information on how to add more complex features to video/audio players, see:
- [Audio and video delivery](/en-US/docs/Web/Media/Audio_and_video_delivery)
- [Video player styling basics](/en-US/docs/Web/Media/Audio_and_video_delivery/Video_player_styling_basics)
- [Creating a cross-browser video player](/en-US/docs/Web/Media/Audio_and_video_delivery/cross_browser_video_player)
We've also created an advanced example to show how you could create an object-oriented system that finds every video and audio player on the page (no matter how many there are) and adds our custom controls to it. See [custom-controls-oojs](https://mdn.github.io/learning-area/accessibility/multimedia/custom-controls-OOJS/) (also [see the source code](https://github.com/mdn/learning-area/tree/main/accessibility/multimedia/custom-controls-OOJS)).
## Audio transcripts
To provide deaf people with access to audio content, you need to create text transcripts. These can either be included on the same page as the audio in some way or included on a separate page and linked to.
In terms of actually creating the transcript, your options are:
- Commercial services β You could pay a professional to do the transcription, see for example companies like [Scribie](https://scribie.com/), [Casting Words](https://castingwords.com/), or [Rev](https://www.rev.com/). Look around and ask for advice to make sure you find a reputable company that you'll be able to work with effectively.
- Community/grassroots/self transcription β If you are part of an active community or team in your workplace, then you could ask them for help with doing the translations. You could even have a go at doing them yourself.
- Automated services β There are AI services available, like [Trint](https://trint.com) or [Transcribear](https://transcribear.com/index.html). Upload a video/audio file to the site, and it automatically transcribes it for you. On YouTube, you can choose to generate automated captions/transcripts. Depending on how clear the spoken audio is, the resulting transcript quality will vary greatly.
As with most things in life, you tend to get what you pay for; different services will vary in accuracy and time taken to produce the transcript. If you pay a reputable company or AI service to do the transcription, you will probably get it done rapidly and to a high quality. If you don't want to pay for it, you are likely to get it done at a lower quality, and/or slowly.
It is not OK to publish an audio resource but promise to publish the transcript later on β such promises often aren't kept, which will erode trust between you and your users. If the audio you are presenting is something like a face to face meeting or live spoken performance, it would be acceptable to take notes during the performance, publish them in full along with the audio, then seek help in cleaning up the notes afterward.
### Transcript examples
If you use an automated service, then you'll probably have to use the user interface that the tool provides. For example, take a look at our [Wait, ARIA Roles Have Categories?](https://www.youtube.com/watch?v=mwF-PpJOjMs) video and choose the three-dot menu (. . .) _> Show Transcript_. You'll see the transcript come up in a separate panel.
If you are creating your own user interface to present your audio and associated transcript, you can do it however you like, but it might make sense to include it in a showable/hideable panel; see our [audio-transcript-ui](https://mdn.github.io/learning-area/accessibility/multimedia/audio-transcript-ui/) example (also see the [source code](https://github.com/mdn/learning-area/tree/main/accessibility/multimedia/audio-transcript-ui)).
### Audio descriptions
On occasions where visuals are accompanying your audio, you'll need to provide audio descriptions of some kind to describe that extra content.
In many cases, this will take the form of video, in which case you can implement captions using the techniques described in the next section of the article.
However, there are some edge cases. You might for example have an audio recording of a meeting that refers to an accompanying resource such as a spreadsheet or chart. In such cases, you should make sure that the resources are provided along with the audio + transcript, and specifically link to them in the places where they are referred to in the transcript. This of course will help all users, not just people who are deaf.
> **Note:** An audio transcript will in general help multiple user groups. As well as giving deaf users access to the information contained in the audio, think about a user with a low bandwidth connection, who would find downloading the audio inconvenient. Think also about a user in a noisy environment like a pub or bar, who is trying to access the information but can't hear it over the noise.
## Video text tracks
To make video accessible for the deaf, visually impaired, or other groups of users (such as those on low bandwidth, or who don't understand the language the video is recorded in), you need to include text tracks along with your video content.
> **Note:** Text tracks are also useful for potentially any user, not just those with disabilities. For example, some users may not be able to hear the audio because they are in noisy environments (like a crowded bar when a sports game is being shown) or might not want to disturb others if they are in a quiet place (like a library).
This is not a new concept β television services have had closed captioning available for quite a long time:

Many countries offer English films with subtitles written in their own native languages, and different language subtitles are often available on DVDs, as shown below:

There are different types of text tracks for different purposes. The main ones you'll come across are:
- Captions β There for the benefit of deaf users who can't hear the audio track, including the words being spoken, and contextual information such as who spoke the words, if the people were angry or sad, and what mood the music is currently creating.
- Subtitles β Include translations of the audio dialog, for users that don't understand the language being spoken.
- Descriptions β These include descriptions for visually impaired people who can't see the video, for example, what the scene looks like.
- Chapter titles β Chapter markers intended to help the user navigate the media resource
### Implementing HTML video text tracks
Text tracks for displaying with HTML video need to be written in WebVTT, a text format containing multiple strings of text along with metadata such as what time in the video you want each text string to be displayed, and even limited styling/positioning information. These text strings are called cues.
A typical WebVTT file will look something like this:
```plain
WEBVTT
1
00:00:22.230 --> 00:00:24.606
This is the first subtitle.
2
00:00:30.739 --> 00:00:34.074
This is the second.
β¦
```
To get this displayed along with the HTML media playback, you need to:
- Save it as a .vtt file in a sensible place.
- Link to the .vtt file with the {{htmlelement("track")}} element. `<track>` should be placed within `<audio>` or `<video>`, but after all `<source>` elements. Use the [`kind`](/en-US/docs/Web/HTML/Element/track#kind) attribute to specify whether the cues are subtitles, captions, or descriptions. Furthermore, use [`srclang`](/en-US/docs/Web/HTML/Element/track#srclang) to tell the browser what language you have written the subtitles in.
Here's an example:
```html
<video controls>
<source src="example.mp4" type="video/mp4" />
<source src="example.webm" type="video/webm" />
<track kind="subtitles" src="subtitles_en.vtt" srclang="en" />
</video>
```
This will result in a video that has subtitles displayed, kind of like this:

For more details, see [Adding captions and subtitles to HTML video](/en-US/docs/Web/Media/Audio_and_video_delivery/Adding_captions_and_subtitles_to_HTML5_video). You can find [the example](https://iandevlin.github.io/mdn/video-player-with-captions/) that goes along with this article on GitHub, written by Ian Devlin (see the [source code](https://github.com/iandevlin/iandevlin.github.io/tree/master/mdn/video-player-with-captions) too.) This example uses JavaScript to allow users to choose between different subtitles. Note that to turn the subtitles on, you need to press the "CC" button and select an option β English, Deutsch, or EspaΓ±ol.
> **Note:** Text tracks and transcriptions also help you with {{glossary("SEO")}}, since search engines especially thrive on text. Text tracks even allow search engines to link directly to a spot partway through the video.
## Test your skills!
You've reached the end of this article, but can you remember the most important information?
We've not written a new set of assessments for this article, because there are already assessments available in our [HTML Multimedia and embedding](/en-US/docs/Learn/HTML/Multimedia_and_embedding) module that test your knowledge of the information presented here. If you haven't already, go and try out the assessments at [Test your skills: HTML images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML/Test_your_skills:_HTML_images) and [Test your skills: Multimedia and embedding](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content/Test_your_skills:_Multimedia_and_embedding).
## Summary
This chapter has provided a summary of accessibility concerns for multimedia content, along with some practical solutions.
It is not always easy to make multimedia accessible. If for example, you are dealing with an immersive 3D game or virtual reality app, it is quite difficult to provide text alternatives for such an experience, and you might argue that visually impaired users are not really in the target audience bracket for such apps.
You can however make sure that such an app has good enough color contrast and clear presentation so it is perceivable to those with low vision/color blindness, and also make it keyboard accessible. Remember that accessibility is about doing as much as you can, rather than striving for 100% accessibility all the time, which is often impossible.
{{PreviousMenuNext("Learn/Accessibility/WAI-ARIA_basics","Learn/Accessibility/Mobile", "Learn/Accessibility")}}
| 0 |
data/mdn-content/files/en-us/learn/accessibility | data/mdn-content/files/en-us/learn/accessibility/accessibility_troubleshooting/index.md | ---
title: "Assessment: Accessibility troubleshooting"
slug: Learn/Accessibility/Accessibility_troubleshooting
page-type: learn-module-assessment
---
{{LearnSidebar}}{{PreviousMenu("Learn/Accessibility/Mobile", "Learn/Accessibility")}}
In the assessment for this module, we present to you a simple site with a number of accessibility issues that you need to diagnose and fix.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML, CSS, and
JavaScript, an understanding of the
<a href="/en-US/docs/Learn/Accessibility"
>previous articles in the course</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To test basic knowledge of accessibility fundamentals.</td>
</tr>
</tbody>
</table>
## Starting point
To get this assessment started, you should go and grab the [ZIP containing the files that comprise the example](https://raw.githubusercontent.com/mdn/learning-area/main/accessibility/assessment-start/assessment-files.zip). Decompress the contents into a new directory somewhere on your local computer.
Alternatively, you could use an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
The finished assessment site should look like so:

You will see some differences/issues with the display of the starting state of the assessment β this is mainly due to the differences in the markup, which in turn cause some styling issues as the CSS is not applied properly. Don't worry β you'll be fixing these problems in the upcoming sections!
> **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
For this project, you are presented with a fictional nature site displaying a "factual" article about bears. As it stands, it has a number of accessibility issues β your task is to explore the existing site and fix them to the best of your abilities, answering the questions given below.
### Color
The text is difficult to read because of the current color scheme. Can you do a test of the current color contrast (text/background), report the results of the test, and then fix it by changing the assigned colors?
### Semantic HTML
1. The content is still not very accessible β report on what happens when you try to navigate it using a screen reader.
2. Can you update the article text to make it easier for screen reader users to navigate?
3. The navigation menu part of the site (wrapped in `<div class="nav"></div>`) could be made more accessible by putting it in a proper HTML semantic element. Which one should it be updated to? Make the update.
> **Note:** You'll need to update the CSS rule selectors that style the tags to their proper equivalents for the semantic headings. Once you add paragraph elements, you'll notice the styling looking better.
### The images
The images are currently inaccessible to screen reader users. Can you fix this?
### The audio player
1. The `<audio>` player isn't accessible to hearing impaired (deaf) people β can you add some kind of accessible alternative for these users?
2. The `<audio>` player isn't accessible to those using older browsers that don't support HTML audio. How can you allow them to still access the audio?
### The forms
1. The `<input>` element in the search form at the top could do with a label, but we don't want to add a visible text label that would potentially spoil the design and isn't really needed by sighted users. How can you add a label that is only accessible to screen readers?
2. The two `<input>` elements in the comment form have visible text labels, but they are not unambiguously associated with their labels β how do you achieve this? Note that you'll need to update some of the CSS rule as well.
### The show/hide comment control
The show/hide comment control button is not currently keyboard-accessible. Can you make it keyboard accessible, both in terms of focusing it using the tab key, and activating it using the return key?
### The table
The data table is not currently very accessible β it is hard for screen reader users to associate data rows and columns together, and the table also has no kind of summary to make it clear what it shows. Can you add some features to your HTML to fix this problem?
### Other considerations?
Can you list two more ideas for improvements that would make the website more accessible?
{{PreviousMenu("Learn/Accessibility/Mobile", "Learn/Accessibility")}}
| 0 |
data/mdn-content/files/en-us/learn/accessibility | data/mdn-content/files/en-us/learn/accessibility/css_and_javascript/index.md | ---
title: CSS and JavaScript accessibility best practices
slug: Learn/Accessibility/CSS_and_JavaScript
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Accessibility/HTML","Learn/Accessibility/WAI-ARIA_basics", "Learn/Accessibility")}}
CSS and JavaScript, when used properly, also have the potential to allow for accessible web experiences, or they can significantly harm accessibility if misused. This article outlines some CSS and JavaScript best practices that should be considered to ensure even complex content is as accessible as possible.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML, CSS, and
JavaScript, and understanding of
<a href="/en-US/docs/Learn/Accessibility/What_is_accessibility"
>what accessibility is</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To gain familiarity with using CSS and JavaScript appropriately in your
web documents to maximize accessibility and not detract from it.
</td>
</tr>
</tbody>
</table>
## CSS and JavaScript are accessible?
CSS and JavaScript don't have the same immediate importance for accessibility as HTML, but they are still able to help or damage accessibility, depending on how they are used. To put it another way, it is important that you consider some best practice advice to make sure that your use of CSS and JavaScript doesn't ruin the accessibility of your documents.
## CSS
Let's start off by looking at CSS.
### Correct semantics and user expectation
It is possible to use CSS to make any HTML element look like _anything_, but this doesn't mean that you should. As we frequently mentioned in our [HTML: A good basis for accessibility](/en-US/docs/Learn/Accessibility/HTML) article, you should use the appropriate semantic element for the job, whenever possible. If you don't, it can cause confusion and usability issues for everyone, but particularly users with disabilities. Using correct semantics has a lot to do with user expectations β elements look and behave in certain ways, according to their functionality, and these common conventions are expected by users.
As an example, a screen reader user can't navigate a page via heading elements if the developer hasn't appropriately used heading elements to markup the content. By the same token, a heading loses its visual purpose if you style it so it doesn't look like a heading.
Bottom line, you can update the styling of a page feature to fit in your design, but don't change it so much that it no longer looks or behaves as expected. The following sections summarize the main HTML features to consider.
#### "Standard" text content structure
Headings, paragraphs, lists β the core text content of your page:
```html
<h1>Heading</h1>
<p>Paragraph</p>
<ul>
<li>My list</li>
<li>has two items.</li>
</ul>
```
Some typical CSS might look like this:
```css
h1 {
font-size: 5rem;
}
p,
li {
line-height: 1.5;
font-size: 1.6rem;
}
```
You should:
- Select sensible font sizes, line heights, letter spacing, etc. to make your text logical, legible, and comfortable to read.
- Make sure your headings stand out from your body text, typically big and bold like the default styling. Your lists should look like lists.
- Your text color should contrast well with your background color.
See [HTML text fundamentals](/en-US/docs/Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals) and [Styling text](/en-US/docs/Learn/CSS/Styling_text) for more information.
#### Emphasized text
Inline markup that confers specific emphasis to the text that it wraps:
```html
<p>The water is <em>very hot</em>.</p>
<p>
Water droplets collecting on surfaces is called <strong>condensation</strong>.
</p>
```
You might want to add some simple coloring to your emphasized text:
```css
strong,
em {
color: #a60000;
}
```
You will however rarely need to style emphasis elements in any significant way. The standard conventions of bold and italic text are very recognizable, and changing the style can cause confusion. For more on emphasis, see [Emphasis and importance](/en-US/docs/Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals#emphasis_and_importance).
#### Abbreviations
An element that allows an abbreviation, acronym, or initialization to be associated with its expansion:
```html
<p>
Web content is marked up using Hypertext Markup Language, or
<abbr>HTML</abbr>.
</p>
```
Again, you might want to style it in some simple way:
```css
abbr {
color: #a60000;
}
```
The recognized styling convention for abbreviations is a dotted underline, and it is unwise to significantly deviate from this. For more on abbreviations, see [Abbreviations](/en-US/docs/Learn/HTML/Introduction_to_HTML/Advanced_text_formatting#abbreviations).
#### Links
Hyperlinks β the way you get to new places on the web:
```html
<p>Visit the <a href="https://www.mozilla.org">Mozilla homepage</a>.</p>
```
Some very simple link styling is shown below:
```css
a {
color: #ff0000;
}
a:hover,
a:visited,
a:focus {
color: #a60000;
text-decoration: none;
}
a:active {
color: #000000;
background-color: #a60000;
}
```
The standard link conventions are underlined and a different color (default: blue) in their standard state, another color variation when the link has previously been visited (default: purple), and yet another color when the link is activated (default: red). In addition, the mouse pointer changes to a pointer icon when links are moused over, and the link receives a highlight when focused (e.g. via tabbing) or activated. The following image shows the highlight in both Firefox (a dotted outline) and Chrome (a blue outline):


You can be creative with link styles, as long as you keep giving users feedback when they interact with the links. Something should definitely happen when states change, and you shouldn't get rid of the pointer cursor or the outline β both are very important accessibility aids for those using keyboard controls.
#### Form elements
Elements to allow users to input data into websites:
```html
<div>
<label for="name">Enter your name</label>
<input type="text" id="name" name="name" />
</div>
```
You can see some good example CSS in our [form-css.html](https://github.com/mdn/learning-area/blob/main/accessibility/css/form-css.html) example ([see it live](https://mdn.github.io/learning-area/accessibility/css/form-css.html) also).
Most of the CSS you'll write for forms will be for sizing the elements, lining up labels and inputs, and getting them looking neat and tidy.
You shouldn't however deviate too much from the expected visual feedback form elements receive when they are focused, which is basically the same as links (see above). You could style form focus/hover states to make this behavior more consistent across browsers or fit in better with your page design, but don't get rid of it altogether β again, people rely on these clues to help them know what is going on.
#### Tables
Tables for presenting tabular data.
You can see a good, simple example of table HTML and CSS in our [table-css.html](https://github.com/mdn/learning-area/blob/main/accessibility/css/table-css.html) example ([see it live also](https://mdn.github.io/learning-area/accessibility/css/table-css.html)).
Table CSS generally serves to make the table fit better into your design and look less ugly. It is a good idea to make sure the table headers stand out (normally using bold), and use zebra striping to make different rows easier to parse.
### Color and color contrast
When choosing a color scheme for your website, 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.
There is an easy way to check whether your contrast is large enough to not cause problems. There are a number of contrast checking tools online that you can enter your foreground and background colors into, to check them. For example WebAIM's [Color Contrast Checker](https://webaim.org/resources/contrastchecker/) is simple to use, and provides an explanation of what you need to conform to the WCAG criteria around color contrast.
> **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.
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.
### Hiding things
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.
### Accept that users can override styles
It is possible for users to override your styles with their own custom styles, for example:
- See Sarah Maddox's [How to use a custom style sheet (CSS) with Firefox](https://www.itsupportguides.com/knowledge-base/computer-accessibility/how-to-use-a-custom-style-sheet-css-with-firefox/) for a useful guide covering how to do this manually in Firefox.
- It is probably easier to do it using an extension. For example, the Stylus extension is available for [Firefox](https://addons.mozilla.org/en-US/firefox/addon/styl-us/), with Stylish being a [Chrome](https://chrome.google.com/webstore/detail/stylish-custom-themes-for/fjnbnpbmkenffdnngjfgmeleoegfcffe) equivalent.
Users might do this for a variety of reasons. A visually impaired user might want to make the text bigger on all websites they visit, or a user with severe color deficiency might want to put all websites in high contrast colors that are easy for them to see. Whatever the need, you should be comfortable with this, and make your designs flexible enough so that such changes will work in your design. As an example, you might want to make sure your main content area can handle bigger text (maybe it will start to scroll to allow it all to be seen), and won't just hide it, or break completely.
## JavaScript
JavaScript can also break accessibility, depending on how it is used.
Modern JavaScript is a powerful language, and we can do so much with it these days, from simple content and UI updates to fully-fledged 2D and 3D games. There is no rule that says all content has to be 100% accessible to all people β you just need to do what you can, and make your apps as accessible as possible.
Simple content and functionality is arguably easy to make accessible β for example text, images, tables, forms and push button that activate functions. As we looked at in our [HTML: A good basis for accessibility](/en-US/docs/Learn/Accessibility/HTML) article, the key considerations are:
- Good semantics: Using the right element for the right job. For example, making sure you use headings and paragraphs, and {{htmlelement("button")}} and {{htmlelement("a")}} elements
- Making sure content is available as text, either directly as text content, good text labels for form elements, or [text alternatives](/en-US/docs/Learn/Accessibility/HTML#text_alternatives), e.g. alt text for images.
We also looked at an example of how to use JavaScript to build in functionality where it is missing β see [Building keyboard accessibility back in](/en-US/docs/Learn/Accessibility/HTML#building_keyboard_accessibility_back_in). This is not ideal β really you should just use the right element for the right job β but it shows that it is possible in situations where for some reason you can't control the markup that is used. Another way to improve accessibility for non-semantic JavaScript-powered widgets is to use WAI-ARIA to provide extra semantics for screen reader users. The next article will also cover this in detail.
Complex functionality like 3D games are not so easy to make accessible β a complex 3D game created using [WebGL](/en-US/docs/Web/API/WebGL_API) will be rendered on a {{htmlelement("canvas")}} element, which has no facility at this time to provide text alternatives or other information for severely visually impaired users to make use of. It is arguable that such a game doesn't really have this group of people as a part of its main target audience, and it would be unreasonable to expect you to make it 100% accessible to blind people. However, 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.
### The problem with too much JavaScript
The problem often comes when people rely on JavaScript too much. Sometimes you'll see a website where everything has been done with JavaScript β the HTML has been generated by JavaScript, the CSS has been generated by JavaScript, etc. This has all kinds of accessibility and other issues associated with it, so it is not advised.
As well as using the right element for the right job, you should also make sure you are using the right technology for the right job! Think carefully about whether you need that shiny JavaScript-powered 3D information box, or whether plain old text would do. Think carefully about whether you need a complex non-standard form widget, or whether a text input would do. And don't generate all your HTML content using JavaScript if at all possible.
### Keeping it unobtrusive
You should keep **unobtrusive JavaScript** in mind when creating your content. The idea of unobtrusive JavaScript is that it should be used wherever possible to enhance functionality, not build it in entirely β basic functions should ideally work without JavaScript, although it is appreciated that this is not always an option. But again, a large part of it is using built-in browser functionality where possible.
Good example uses of unobtrusive 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, along with a direct link to the video that can be used to access it if JavaScript is not available (the default `<video>` browser controls aren't keyboard accessible in most browsers).
As an example, we've written a quick and dirty client-side form validation example β see [form-validation.html](https://github.com/mdn/learning-area/blob/main/accessibility/css/form-validation.html) (also [see the demo live](https://mdn.github.io/learning-area/accessibility/css/form-validation.html)). Here you'll see a simple form; when you try to submit the form with one or both fields left empty, the submit fails, and an error message box appears to tell you what is wrong.
This kind of form validation is unobtrusive β you can still use the form absolutely fine without the JavaScript being available, and any sensible form implementation will have server-side validation active as well, because it is too easy for malicious users to bypass client-side validation (for example, by turning JavaScript off in the browser). The client-side validation is still really useful for reporting errors β users can know about mistakes they make instantly, rather than having to wait for a round trip to the server and a page reload. This is a definite usability advantage.
> **Note:** Server-side validation has not been implemented in this simple demo.
We've made this form validation pretty accessible too. We've used {{htmlelement("label")}} elements to make sure the form labels are unambiguously linked to their inputs, so screen readers can read them out alongside:
```html
<label for="name">Enter your name:</label>
<input type="text" name="name" id="name" />
```
We only do the validation when the form is submitted β this is so that we don't update the UI too often and potentially confuse screen reader (and possibly other) users:
```js
form.onsubmit = validate;
function validate(e) {
errorList.innerHTML = "";
for (let i = 0; i < formItems.length; i++) {
const testItem = formItems[i];
if (testItem.input.value === "") {
errorField.style.left = "360px";
createLink(testItem);
}
}
if (errorList.innerHTML !== "") {
e.preventDefault();
}
}
```
> **Note:** In this example, we are hiding and showing the error message box using absolute positioning rather than another method such as visibility or display, because it doesn't interfere with the screen reader being able to read content from it.
Real form validation would be much more complex than this β you'd want to check that the entered name actually looks like a name, the entered age is actually a number and is realistic (e.g. nonnegative and less than 4 digits). Here we've just implemented a simple check that a value has been filled in to each input field (`if (testItem.input.value === '')`).
When the validation has been performed, if the tests pass then the form is submitted. If there are errors (`if (errorList.innerHTML !== '')`) then we stop the form submitting (using [`preventDefault()`](/en-US/docs/Web/API/Event/preventDefault)), and display any error messages that have been created (see below). This mechanism means that the errors will only be shown if there are errors, which is better for usability.
For each input that doesn't have a value filled in when the form is submitted, we create a list item with a link and insert it in the `errorList`.
```js
function createLink(testItem) {
const listItem = document.createElement("li");
const anchor = document.createElement("a");
const name = testItem.input.name;
anchor.textContent = `${name} field is empty: fill in your ${name}.`;
anchor.href = `#${name}`;
listItem.appendChild(anchor);
errorList.appendChild(listItem);
}
```
Each link serves a dual purpose β it tells you what the error is, plus you can click on it/activate it to jump straight to the input element in question and correct your entry.
In addition, the `errorField` is placed at the top of the source order (although it is positioned differently in the UI using CSS), meaning that users can find out exactly what's wrong with their form submissions and get to the input elements in question by going back up to the start of the page.
As a final note, we have used some WAI-ARIA attributes in our demo to help solve accessibility problems caused by areas of content constantly updating without a page reload (screen readers won't pick this up or alert users to it by default):
```html
<div class="errors" role="alert" aria-relevant="all">
<ul></ul>
</div>
```
We will explain these attributes in our next article, which covers [WAI-ARIA](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics) in much more detail.
> **Note:** Some of you will probably be thinking about the fact that HTML forms have built-in validation mechanisms like the `required`, `min`/`minlength`, and `max`/`maxlength` attributes (see the {{htmlelement("input")}} element reference for more information). We didn't end up using these in the demo because cross-browser support for them is patchy (for example IE10 and above only).
> **Note:** WebAIM's [Usable and Accessible Form Validation and Error Recovery](https://webaim.org/techniques/formvalidation/) provides some further useful information about accessible form validation.
### Other JavaScript accessibility concerns
There are other things to be aware of when implementing JavaScript and thinking about accessibility. We will add more as we find them.
#### mouse-specific events
As you will be aware, most user interactions are implemented in client-side JavaScript using event handlers, which allow us to run functions in response to certain events happening. Some events can have accessibility issues. The main example you'll come across is mouse-specific events like [mouseover](/en-US/docs/Web/API/Element/mouseover_event), [mouseout](/en-US/docs/Web/API/Element/mouseout_event), [dblclick](/en-US/docs/Web/API/Element/dblclick_event), etc. Functionality that runs in response to these events will not be accessible using other mechanisms, like keyboard controls.
To mitigate such problems, you should double up these events with similar events that can be activated by other means (so-called device-independent event handlers) β [focus](/en-US/docs/Web/API/Element/focus_event) and [blur](/en-US/docs/Web/API/Element/blur_event) would provide accessibility for keyboard users.
Let's look at an example that highlights when this could be useful. Maybe we want to provide a thumbnail image that shows a larger version of the image when it is moused over or focused (like you'd see on an e-commerce product catalog.)
We've made a very simple example, which you can find at [mouse-and-keyboard-events.html](https://mdn.github.io/learning-area/accessibility/css/mouse-and-keyboard-events.html) (see also the [source code](https://github.com/mdn/learning-area/blob/main/accessibility/css/mouse-and-keyboard-events.html)). The code features two functions that show and hide the zoomed-in image; these are run by the following lines that set them as event handlers:
```js
imgThumb.onmouseover = showImg;
imgThumb.onmouseout = hideImg;
imgThumb.onfocus = showImg;
imgThumb.onblur = hideImg;
```
The first two lines run the functions when the mouse pointer hovers over and stops hovering over the thumbnail, respectively. This won't allow us to access the zoomed view by keyboard though β to allow that, we've included the last two lines, which run the functions when the image is focused and blurred (when focus stops). This can be done by tabbing over the image, because we've included `tabindex="0"` on it.
The [click](/en-US/docs/Web/API/Element/click_event) event is interesting β it sounds mouse-dependent, but most browsers will activate [onclick](/en-US/docs/Web/API/Element/click_event) event handlers after Enter/Return is pressed on a link or form element that has focus, or when such an element is tapped on a touchscreen device. This doesn't work by default however when you allow a non-default-focusable event to have focus using tabindex β in such cases you need to detect specifically when that exact key is pressed (see [Building keyboard accessibility back in](/en-US/docs/Learn/Accessibility/HTML#building_keyboard_accessibility_back_in)).
## 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: CSS and JavaScript accessibility](/en-US/docs/Learn/Accessibility/CSS_and_JavaScript/Test_your_skills:_CSS_and_JavaScript_accessibility).
## Summary
We hope this article has given you a good amount of detail and understanding about the accessibility issues surrounding CSS and JavaScript use on web pages.
Next up, WAI-ARIA!
{{PreviousMenuNext("Learn/Accessibility/HTML","Learn/Accessibility/WAI-ARIA_basics", "Learn/Accessibility")}}
| 0 |
data/mdn-content/files/en-us/learn/accessibility/css_and_javascript | data/mdn-content/files/en-us/learn/accessibility/css_and_javascript/test_your_skills_colon__css_and_javascript_accessibility/index.md | ---
title: "Test your skills: CSS and JavaScript accessibility"
slug: Learn/Accessibility/CSS_and_JavaScript/Test_your_skills:_CSS_and_JavaScript_accessibility
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [CSS and JavaScript accessibility best practices](/en-US/docs/Learn/Accessibility/CSS_and_JavaScript) 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).
## CSS accessibility 1
In the first task you are presented with a list of links. However, their accessibility is pretty bad β there is no way to really tell that they are links, or to tell which one the user is focussed on.
We'd like you to assume that the existing ruleset with the `a` selector is supplied by some CMS, and that you can't change it β instead, you need to create new rules to make the links look and behave like links, and for the user to be able to tell where they are in the list.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/accessibility/tasks/html-css/css/css-a11y1.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/accessibility/tasks/html-css/css/css-a11y1-download.html) to work in your own editor or in an online editor.
## CSS accessibility 2
In this next task you are presented with a simple bit of content β just headings and paragraphs. There are accessibility issues with the colors and sizing of the text; we'd like you to:
1. Explain what the problems are, and what the guidelines are that state the acceptable values for color and sizing.
2. Select new values for the color and font-size that fix the problem.
3. Update the CSS with these new values to fix the problem.
4. Test the code to make sure the problem is now fixed. Explain what tools or methods you used to select the new values and test the code.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/accessibility/tasks/html-css/css/css-a11y2.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/accessibility/tasks/html-css/css/css-a11y2-download.html) to work in your own editor or in an online editor.
## JavaScript accessibility 1
In our final task here, you have some JavaScripting to do. We have a simple app that presents a list of animal names. Clicking one of the animal names causes a further description of that animal to appear in a box below the list.
But it is not very accessible β in its current state you can only operate it with the mouse. We'd like you to add to the HTML and JavaScript to make it keyboard accessible too.
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/accessibility/tasks/js/js/js1-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/accessibility | data/mdn-content/files/en-us/learn/accessibility/wai-aria_basics/index.md | ---
title: WAI-ARIA basics
slug: Learn/Accessibility/WAI-ARIA_basics
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Accessibility/CSS_and_JavaScript","Learn/Accessibility/Multimedia", "Learn/Accessibility")}}
Following on from the previous article, sometimes making complex UI controls that involve unsemantic HTML and dynamic JavaScript-updated content can be difficult. WAI-ARIA is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. Here we'll show how to use it at a basic level to improve accessibility.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
A basic understanding of HTML, CSS, and
JavaScript. An understanding of the
<a href="/en-US/docs/Learn/Accessibility"
>previous articles in the course</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To gain familiarity with WAI-ARIA, and how it can be used to provide
useful additional semantics to enhance accessibility where required.
</td>
</tr>
</tbody>
</table>
## What is WAI-ARIA?
Let's start by looking at what WAI-ARIA is, and what it can do for us.
### A whole new set of problems
As web apps started to get more complex and dynamic, a new set of accessibility features and problems started to appear.
For example, HTML introduced a number of semantic elements to define common page features ({{htmlelement("nav")}}, {{htmlelement("footer")}}, etc.). Before these were available, developers would use {{htmlelement("div")}}s with IDs or classes, e.g. `<div class="nav">`, but these were problematic, as there was no easy way to easily find a specific page feature such as the main navigation programmatically.
The initial solution was to add one or more hidden links at the top of the page to link to the navigation (or whatever else), for example:
```html
<a href="#hidden" class="hidden">Skip to navigation</a>
```
But this is still not very precise, and can only be used when the screen reader is reading from the top of the page.
As another example, apps started to feature complex controls like date pickers for choosing dates, sliders for choosing values, etc. HTML provides special input types to render such controls:
```html
<input type="date" /> <input type="range" />
```
These were originally not well-supported and it was, and still is to a lesser extent, difficult to style them, leading designers and developers to opt for custom solutions. Instead of using these native features, some developers rely on JavaScript libraries that generate such controls as a series of nested {{htmlelement("div")}}s which are then styled using CSS and controlled using JavaScript.
The problem here is that visually they work, but screen readers can't make any sense of what they are at all, and their users just get told that they can see a jumble of elements with no semantics to describe what they mean.
### Enter WAI-ARIA
[WAI-ARIA](https://www.w3.org/TR/wai-aria/) (Web Accessibility Initiative - Accessible Rich Internet Applications) is a specification written by the W3C, defining a set of additional HTML attributes that can be applied to elements to provide additional semantics and improve accessibility wherever it is lacking. There are three main features defined in the spec:
- [Roles](/en-US/docs/Web/Accessibility/ARIA/Roles)
- : These define what an element is or does. Many of these are so-called landmark roles, which largely duplicate the semantic value of structural elements, such as `role="navigation"` ({{htmlelement("nav")}}) or `role="complementary"` ({{htmlelement("aside")}}). Some other roles describe different page structures, such as `role="banner"`, `role="search"`, `role="tablist"`, and `role="tabpanel"`, which are commonly found in UIs.
- Properties
- : These define properties of elements, which can be used to give them extra meaning or semantics. As an example, `aria-required="true"` specifies that a form input needs to be filled in order to be valid, whereas `aria-labelledby="label"` allows you to put an ID on an element, then reference it as being the label for anything else on the page, including multiple elements, which is not possible using `<label for="input">`. As an example, you could use `aria-labelledby` to specify that a key description contained in a {{htmlelement("div")}} is the label for multiple table cells, or you could use it as an alternative to image alt text β specify existing information on the page as an image's alt text, rather than having to repeat it inside the `alt` attribute. You can see an example of this at [Text alternatives](/en-US/docs/Learn/Accessibility/HTML#text_alternatives).
- States
- : Special properties that define the current conditions of elements, such as `aria-disabled="true"`, which specifies to a screen reader that a form input is currently disabled. States differ from properties in that properties don't change throughout the lifecycle of an app, whereas states can change, generally programmatically via JavaScript.
An important point about WAI-ARIA attributes is that they don't affect anything about the web page, except for the information exposed by the browser's accessibility APIs (where screen readers get their information from). WAI-ARIA doesn't affect webpage structure, the DOM, etc., although the attributes can be useful for selecting elements by CSS.
> **Note:** You can find a useful list of all the ARIA roles and their uses, with links to further information, in the WAI-ARIA spec β see [Definition of Roles](https://www.w3.org/TR/wai-aria-1.1/#role_definitions) β on this site β see [ARIA roles](/en-US/docs/Web/Accessibility/ARIA/Roles).
>
> The spec also contains a list of all the properties and states, with links to further information β see [Definitions of States and Properties (all `aria-*` attributes)](https://www.w3.org/TR/wai-aria-1.1/#state_prop_def).
### Where is WAI-ARIA supported?
This is not an easy question to answer. It is difficult to find a conclusive resource that states what features of WAI-ARIA are supported, and where, because:
1. There are a lot of features in the WAI-ARIA spec.
2. There are many combinations of operating systems, browsers, and screen readers to consider.
This last point is key β To use a screen reader in the first place, your operating system needs to run browsers that have the necessary accessibility APIs in place to expose the information screen readers need to do their job. Most popular OSes have one or two browsers in place that screen readers can work with. The Paciello Group has a fairly up-to-date post that provides data for this β see [Rough Guide: browsers, operating systems and screen reader support updated](https://www.tpgi.com/rough-guide-browsers-operating-systems-and-screen-reader-support-updated/).
Next, you need to worry about whether the browsers in question support ARIA features and expose them via their APIs, but also whether screen readers recognize that information and present it to their users in a useful way.
1. Browser support is almost universal.
2. Screen reader support for ARIA features isn't quite at this level, but the most popular screen readers are getting there. You can get an idea of support levels by looking at Powermapper's [WAI-ARIA Screen reader compatibility](https://www.powermapper.com/tests/screen-readers/aria/) article.
In this article, we won't attempt to cover every WAI-ARIA feature, and its exact support details. Instead, we will cover the most critical WAI-ARIA features for you to know about; if we don't mention any support details, you can assume that the feature is well-supported. We will clearly mention any exceptions to this.
> **Note:** Some JavaScript libraries support WAI-ARIA, meaning that when they generate UI features like complex form controls, they add ARIA attributes to improve the accessibility of those features. If you are looking for a 3rd party JavaScript solution for rapid UI development, you should definitely consider the accessibility of its UI widgets as an important factor when making your choice. Good examples are jQuery UI (see [About jQuery UI: Deep accessibility support](https://jqueryui.com/about/#deep-accessibility-support)), [ExtJS](https://www.sencha.com/products/extjs/), and [Dojo/Dijit](https://dojotoolkit.org/reference-guide/1.10/dijit/a11y/statement.html).
### When should you use WAI-ARIA?
We talked about some of the problems that prompted WAI-ARIA to be created earlier on, but essentially, there are four main areas that WAI-ARIA is useful in:
- Signposts/Landmarks
- : ARIA's [`role`](/en-US/docs/Web/Accessibility/ARIA/Roles) attribute values can act as landmarks that either replicate the semantics of HTML elements (e.g., {{htmlelement("nav")}}), or go beyond HTML semantics to provide signposts to different functional areas, for example, `search`, `tablist`, `tab`, `listbox`, etc.
- Dynamic content updates
- : Screen readers tend to have difficulty with reporting constantly changing content; with ARIA we can use `aria-live` to inform screen reader users when an area of content is updated dynamically: for example, by JavaScript in the page [fetching new content from the server and updating the DOM](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data).
- Enhancing keyboard accessibility
- : There are built-in HTML elements that have native keyboard accessibility; when other elements are used along with JavaScript to simulate similar interactions, keyboard accessibility and screen reader reporting suffers as a result. Where this is unavoidable, WAI-ARIA provides a means to allow other elements to receive focus (using `tabindex`).
- Accessibility of non-semantic controls
- : When a series of nested `<div>`s along with CSS/JavaScript is used to create a complex UI-feature, or a native control is greatly enhanced/changed via JavaScript, accessibility can suffer β screen reader users will find it difficult to work out what the feature does if there are no semantics or other clues. In these situations, ARIA can help to provide what's missing with a combination of roles like `button`, `listbox`, or `tablist`, and properties like `aria-required` or `aria-posinset` to provide further clues as to functionality.
One thing to remember though β **you should only use WAI-ARIA when you need to!** Ideally, you should _always_ use [native HTML features](/en-US/docs/Learn/Accessibility/HTML) to provide the semantics required by screen readers to tell their users what is going on. Sometimes this isn't possible, either because you have limited control over the code, or because you are creating something complex that doesn't have an easy HTML element to implement it. In such cases, WAI-ARIA can be a valuable accessibility enhancing tool.
But again, only use it when necessary!
> **Note:** Also, try to make sure you test your site with a variety of _real_ users β non-disabled people, people using screen readers, people using keyboard navigation, etc. They will have better insights than you about how well it works.
## Practical WAI-ARIA implementations
In the next section, we'll look at the four areas in more detail, along with practical examples. Before you continue, you should get a screen reader testing setup put in place, so you can test some of the examples as you go through.
See our section on [testing screen readers](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#screen_readers) for more information.
### Signposts/Landmarks
WAI-ARIA adds the [`role` attribute](https://www.w3.org/TR/wai-aria-1.1/#role_definitions) to browsers, which allows you to add extra semantic value to elements on your site wherever they are needed. The first major area in which this is useful is providing information for screen readers so that their users can find common page elements. Let's look at an example β our [website-no-roles](https://github.com/mdn/learning-area/tree/main/accessibility/aria/website-no-roles) example ([see it live](https://mdn.github.io/learning-area/accessibility/aria/website-no-roles/)) has the following structure:
```html
<header>
<h1>β¦</h1>
<nav>
<ul>
β¦
</ul>
<form>
<!-- search form -->
</form>
</nav>
</header>
<main>
<article>β¦</article>
<aside>β¦</aside>
</main>
<footer>β¦</footer>
```
If you try testing the example with a screen reader in a modern browser, you'll already get some useful information. For example, VoiceOver gives you the following:
- On the `<header>` element β "banner, 2 items" (it contains a heading and the `<nav>`).
- On the `<nav>` element β "navigation 2 items" (it contains a list and a form).
- On the `<main>` element β "main 2 items" (it contains an article and an aside).
- On the `<aside>` element β "complementary 2 items" (it contains a heading and a list).
- On the search form input β "Search query, insertion at beginning of text".
- On the `<footer>` element β "footer 1 item".
If you go to VoiceOver's landmarks menu (accessed using VoiceOver key + U and then using the cursor keys to cycle through the menu choices), you'll see that most of the elements are nicely listed so they can be accessed quickly.

However, we could do better here. The search form is a really important landmark that people will want to find, but it is not listed in the landmarks menu or treated like a notable landmark beyond the actual input being called out as a search input (`<input type="search">`).
Let's improve it by the use of some ARIA features. First, we'll add some [`role`](/en-US/docs/Web/Accessibility/ARIA/Roles) attributes to our HTML structure. You can try taking a copy of our original files (see [`index.html`](https://github.com/mdn/learning-area/blob/main/accessibility/aria/website-no-roles/index.html) and [`style.css`](https://github.com/mdn/learning-area/blob/main/accessibility/aria/website-no-roles/style.css)), or navigating to our [website-aria-roles](https://github.com/mdn/learning-area/tree/main/accessibility/aria/website-aria-roles) example ([see it live](https://mdn.github.io/learning-area/accessibility/aria/website-aria-roles/)), which has a structure like this:
```html
<header>
<h1>β¦</h1>
<nav role="navigation">
<ul>
β¦
</ul>
<form role="search">
<!-- search form -->
</form>
</nav>
</header>
<main>
<article role="article">β¦</article>
<aside role="complementary">β¦</aside>
</main>
<footer>β¦</footer>
```
We've also given you a bonus feature in this example β the {{htmlelement("input")}} element has been given the attribute [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label), which gives it a descriptive label to be read out by a screen reader, even though we haven't included a {{htmlelement("label")}} element. In cases like these, this is very useful β a search form like this one is a very common, easily recognized feature, and adding a visual label would spoil the page design.
```html
<input
type="search"
name="q"
placeholder="Search query"
aria-label="Search through site content" />
```
Now if we use VoiceOver to look at this example, we get some improvements:
- The search form is called out as a separate item, both when browsing through the page, and in the Landmarks menu.
- The label text contained in the `aria-label` attribute is read out when the form input is highlighted.
Beyond this, the site is more likely to be accessible to users of older browsers such as IE8; it is worth including ARIA roles for that purpose. And if for some reason your site is built using just `<div>`s, you should definitely include the ARIA roles to provide these much needed semantics!
The improved semantics of the search form have shown what is made possible when ARIA goes beyond the semantics available in HTML. You'll see a lot more about these semantics and the power of ARIA properties/attributes below, especially in the [Accessibility of non-semantic controls](#accessibility_of_non-semantic_controls) section. For now though, let's look at how ARIA can help with dynamic content updates.
### Dynamic content updates
Content loaded into the DOM can be easily accessed using a screen reader, from textual content to alternative text attached to images. Traditional static websites with largely text content are therefore easy to make accessible for people with visual impairments.
The problem is that modern web apps are often not just static text β they often update parts of the page by fetching new content from the server and updating the DOM. These are sometimes referred to as **live regions**.
Let's look at a quick example β see [`aria-no-live.html`](https://github.com/mdn/learning-area/blob/main/accessibility/aria/aria-no-live.html) (also [see it running live](https://mdn.github.io/learning-area/accessibility/aria/aria-no-live.html)). In this example, we have a simple random quote box:
```html
<section>
<h1>Random quote</h1>
<blockquote>
<p></p>
</blockquote>
</section>
```
Our JavaScript uses the {{domxref("fetch()")}} API to load a JSON file via containing a series of random quotes and their authors. Once that is done, we start up a [`setInterval()`](/en-US/docs/Web/API/setInterval) loop that loads a new random quote into the quote box every 10 seconds:
```js
const intervalID = setInterval(showQuote, 10000);
```
This works OK, but it is not good for accessibility β the content update is not detected by screen readers, so their users would not know what is going on. This is a fairly trivial example, but just imagine if you were creating a complex UI with lots of constantly updating content, like a chat room, or a strategy game UI, or a live updating shopping cart display β it would be impossible to use the app in any effective way without some kind of way of alerting the user to the updates.
WAI-ARIA, fortunately, provides a useful mechanism to provide these alerts β the [`aria-live`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-live) property. Applying this to an element causes screen readers to read out the content that is updated. How urgently the content is read out depends on the attribute value:
- `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.
We'd like you to take a copy of [`aria-no-live.html`](https://github.com/mdn/learning-area/blob/main/accessibility/aria/aria-no-live.html) and [`quotes.json`](https://github.com/mdn/learning-area/blob/main/accessibility/aria/quotes.json), and update your `<section>` opening tag as follows:
```html
<section aria-live="assertive">β¦</section>
```
This will cause a screen reader to read out the content as it is updated.
> **Note:** Most browsers will throw a security exception if you try to make an HTTP request from a `file://` URL, e.g. if you just load the file by loading it directly into the browser (via double clicking, etc.). See [how to set up a local testing server](/en-US/docs/Learn/Common_questions/Tools_and_setup/set_up_a_local_testing_server).
There is an additional consideration here β only the bit of text that updates is read out. It might be nice if we always read out the heading too, so the user can remember what is being read out. To do this, we can add the [`aria-atomic`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-atomic) property to the section. Update your `<section>` opening tag again, like so:
```html
<section aria-live="assertive" aria-atomic="true">β¦</section>
```
The `aria-atomic="true"` attribute tells screen readers to read out the entire element contents as one atomic unit, not just the bits that were updated.
> **Note:** You can see the finished example at [`aria-live.html`](https://github.com/mdn/learning-area/blob/main/accessibility/aria/aria-live.html) ([see it running live](https://mdn.github.io/learning-area/accessibility/aria/aria-live.html)).
> **Note:** The [`aria-relevant`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant) property is also quite useful for controlling what gets read out when a live region is updated. You can for example only get content additions or removals read out.
### Enhancing keyboard accessibility
As discussed in a few other places in the module, one of the key strengths of HTML with respect to accessibility is the built-in keyboard accessibility of features such as buttons, form controls, and links. Generally, you can use the tab key to move between controls, the Enter/Return key to select or activate controls, and occasionally other controls as needed (for example the up and down cursor to move between options in a `<select>` box).
However, sometimes you will end up having to write code that either uses non-semantic elements as buttons (or other types of control), or uses focusable controls for not quite the right purpose. You might be trying to fix some bad code you've inherited, or you might be building some kind of complex widget that requires it.
In terms of making non-focusable code focusable, WAI-ARIA extends the `tabindex` attribute with some new values:
- `tabindex="0"` β as indicated above, this value allows elements that are not normally tabbable to become tabbable. This is the most useful value of `tabindex`.
- `tabindex="-1"` β this allows not normally tabbable elements to receive focus programmatically, e.g. via JavaScript, or as the target of links.
We discussed this in more detail and showed a typical implementation back in our HTML accessibility article β see [Building keyboard accessibility back in](/en-US/docs/Learn/Accessibility/HTML#building_keyboard_accessibility_back_in).
### Accessibility of non-semantic controls
This follows on from the previous section β when a series of nested `<div>`s along with CSS/JavaScript is used to create a complex UI-feature, or a native control is greatly enhanced/changed via JavaScript, not only can keyboard accessibility suffer, but screen reader users will find it difficult to work out what the feature does if there are no semantics or other clues. In such situations, ARIA can help to provide those missing semantics.
#### Form validation and error alerts
First of all, let's revisit the form example we first looked at in our CSS and JavaScript accessibility article (read [Keeping it unobtrusive](/en-US/docs/Learn/Accessibility/CSS_and_JavaScript#keeping_it_unobtrusive) for a full recap). At the end of this section, we showed that we have included some ARIA attributes on the error message box that displays any validation errors when you try to submit the form:
```html
<div class="errors" role="alert" aria-relevant="all">
<ul></ul>
</div>
```
- [`role="alert"`](/en-US/docs/Web/Accessibility/ARIA/Roles/alert_role) automatically turns the element it is applied to into a live region, so changes to it are read out; it also semantically identifies it as an alert message (important time/context-sensitive information), and represents a better, more accessible way of delivering an alert to a user (modal dialogs like [`alert()`](/en-US/docs/Web/API/Window/alert) calls have a number of accessibility problems; see [Popup Windows](https://webaim.org/techniques/javascript/other#popups) by WebAIM).
- An [`aria-relevant`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant) value of `all` instructs the screen reader to read out the contents of the error list when any changes are made to it β i.e., when errors are added or removed. This is useful because the user will want to know what errors are left, not just what has been added or removed from the list.
We could go further with our ARIA usage, and provide some more validation help. How about indicating whether fields are required in the first place, and what range the age should be?
1. At this point, take a copy of our [`form-validation.html`](https://github.com/mdn/learning-area/blob/main/accessibility/css/form-validation.html) and [`validation.js`](https://github.com/mdn/learning-area/blob/main/accessibility/css/validation.js) files, and save them in a local directory.
2. Open them both in a text editor and have a look at how the code works.
3. First of all, add a paragraph just above the opening `<form>` tag, like the one below, and mark both the form `<label>`s with an asterisk. This is normally how we mark required fields for sighted users.
```html
<p>Fields marked with an asterisk (*) are required.</p>
```
4. This makes visual sense, but it isn't as easy to understand for screen reader users. Fortunately, WAI-ARIA provides the [`aria-required`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-required) attribute to give screen readers hints that they should tell users that form inputs need to be filled in. Update the `<input>` elements like so:
```html
<input type="text" name="name" id="name" aria-required="true" />
<input type="number" name="age" id="age" aria-required="true" />
```
5. If you save the example now and test it with a screen reader, you should hear something like "Enter your name star, required, edit text".
6. It might also be useful if we give screen reader users and sighted users an idea of what the age value should be. This is often presented as a tooltip or placeholder inside the form field. WAI-ARIA does include [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) and [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) properties to specify min and max values, and screen readers support the native `min` and `max` attributes. Another well-supported feature is the HTML `placeholder` attribute, which can contain a message that is shown in the input when no value is entered and is read out by a few screen readers. Update your number input like this:
```html
<label for="age">Your age:</label>
<input
type="number"
name="age"
id="age"
placeholder="Enter 1 to 150"
required
aria-required="true" />
```
Always include a {{HTMLelement('label')}} for every input. While some screen readers announce the placeholder text, most do not. Acceptable substitutions for providing form controls with an accessible name include [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) and [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby). But the `<label>` element with a `for` attribute is the preferred method as it provides usability for all users, including mouse users.
> **Note:** You can see the finished example live at [`form-validation-updated.html`](https://mdn.github.io/learning-area/accessibility/aria/form-validation-updated.html).
WAI-ARIA also enables some advanced form labelling techniques, beyond the classic {{htmlelement("label")}} element. We already talked about using the [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) property to provide a label where we don't want the label to be visible to sighted users (see the [Signposts/Landmarks](#signpostslandmarks) section, above). Some other labeling techniques use other properties such as [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) if you want to designate a non-`<label>` element as a label or label multiple form inputs with the same label, and [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby), if you want to associate other information with a form input and have it read out as well. See [WebAIM's Advanced Form Labeling article](https://webaim.org/techniques/forms/advanced) for more details.
There are many other useful properties and states too, for indicating the status of form elements. For example, `aria-disabled="true"` can be used to indicate that a form field is disabled. Many browsers will skip past disabled form fields which leads to them not being read out by screen readers. In some cases, a disabled element will be perceived, so it is a good idea to include this attribute to let the screen reader know that a disabled form control is in fact disabled.
If the disabled state of an input is likely to change, then it is also a good idea to indicate when it happens, and what the result is. For example, in our [`form-validation-checkbox-disabled.html`](https://mdn.github.io/learning-area/accessibility/aria/form-validation-checkbox-disabled.html) demo, there is a checkbox that when checked, enables another form input to allow further information to be entered. We've set up a hidden live region:
```html
<p class="hidden-alert" aria-live="assertive"></p>
```
which is hidden from view using absolute positioning. When this is checked/unchecked, we update the text inside the hidden live region to tell screen reader users what the result of checking this checkbox is, as well as updating the `aria-disabled` state, and some visual indicators too:
```js
function toggleMusician(bool) {
const instruItem = formItems[formItems.length - 1];
if (bool) {
instruItem.input.disabled = false;
instruItem.label.style.color = "#000";
instruItem.input.setAttribute("aria-disabled", "false");
hiddenAlert.textContent =
"Instruments played field now enabled; use it to tell us what you play.";
} else {
instruItem.input.disabled = true;
instruItem.label.style.color = "#999";
instruItem.input.setAttribute("aria-disabled", "true");
instruItem.input.removeAttribute("aria-label");
hiddenAlert.textContent = "Instruments played field now disabled.";
}
}
```
#### Describing non-semantic buttons as buttons
A few times in this course already, we've mentioned the native accessibility of (and the accessibility issues behind using other elements to fake) buttons, links, or form elements (see [UI controls](/en-US/docs/Learn/Accessibility/HTML#ui_controls) in the HTML accessibility article, and [Enhancing keyboard accessibility](#enhancing_keyboard_accessibility), above). Basically, you can add keyboard accessibility back in without too much trouble in many cases, using `tabindex` and a bit of JavaScript.
But what about screen readers? They still won't see the elements as buttons. If we test our [`fake-div-buttons.html`](https://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/fake-div-buttons.html) example in a screen reader, our fake buttons will be reported using phrases like "Click me!, group", which is obviously confusing.
We can fix this using a WAI-ARIA role. Make a local copy of [`fake-div-buttons.html`](https://github.com/mdn/learning-area/blob/main/tools-testing/cross-browser-testing/accessibility/fake-div-buttons.html), and add [`role="button"`](/en-US/docs/Web/Accessibility/ARIA/Roles/button_role) to each button `<div>`, for example:
```html
<div data-message="This is from the first button" tabindex="0" role="button">
Click me!
</div>
```
Now when you try this using a screen reader, you'll have buttons be reported using phrases like "Click me!, button". While this is much better, you still have to add in all the native button features users expect, like handling <kbd>enter</kbd> and click events, as explained in the [`button` role documentation](/en-US/docs/Web/Accessibility/ARIA/Roles/button_role).
> **Note:** Don't forget however that using the correct semantic element where possible is always better. If you want to create a button, and can use a {{htmlelement("button")}} element, you should use a {{htmlelement("button")}} element!
#### Guiding users through complex widgets
There are a whole host of other [roles](/en-US/docs/Web/Accessibility/ARIA/Roles) that can identify non-semantic element structures as common UI features that go beyond what's available in standard HTML, for example [`combobox`](/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role), [`slider`](/en-US/docs/Web/Accessibility/ARIA/Roles/slider_role), [`tabpanel`](/en-US/docs/Web/Accessibility/ARIA/Roles/tabpanel_role), [`tree`](/en-US/docs/Web/Accessibility/ARIA/Roles/tree_role). You can see several useful examples in the [Deque university code library](https://dequeuniversity.com/library/) to give you an idea of how such controls can be made accessible.
Let's go through an example of our own. We'll return to our simple absolutely-positioned tabbed interface (see [Hiding things](/en-US/docs/Learn/Accessibility/CSS_and_JavaScript#hiding_things) in our CSS and JavaScript accessibility article), which you can find at [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)).
This example as-is works fine in terms of keyboard accessibility β you can happily tab between the different tabs and select them to show the tab contents. It is also fairly accessible too β you can scroll through the content and use the headings to navigate, even if you can't see what is happening on screen. It is however not that obvious what the content is β a screen reader currently reports the content as a list of links, and some content with three headings. It doesn't give you any idea of what the relationship is between the content. Giving the user more clues as to the structure of the content is always good.
To improve things, we've created a new version of the example called [`aria-tabbed-info-box.html`](https://github.com/mdn/learning-area/blob/main/accessibility/aria/aria-tabbed-info-box.html) ([see it running live](https://mdn.github.io/learning-area/accessibility/aria/aria-tabbed-info-box.html)). We've updated the structure of the tabbed interface like so:
```html
<ul role="tablist">
<li
class="active"
role="tab"
aria-selected="true"
aria-setsize="3"
aria-posinset="1"
tabindex="0">
Tab 1
</li>
<li
role="tab"
aria-selected="false"
aria-setsize="3"
aria-posinset="2"
tabindex="0">
Tab 2
</li>
<li
role="tab"
aria-selected="false"
aria-setsize="3"
aria-posinset="3"
tabindex="0">
Tab 3
</li>
</ul>
<div class="panels">
<article class="active-panel" role="tabpanel" aria-hidden="false">β¦</article>
<article role="tabpanel" aria-hidden="true">β¦</article>
<article role="tabpanel" aria-hidden="true">β¦</article>
</div>
```
> **Note:** The most striking change here is that we've removed the links that were originally present in the example, and just used the list items as the tabs β this was done because it makes things less confusing for screen reader users (the links don't really take you anywhere; they just change the view), and it allows the setsize/position in set features to work better β when these were put on the links, the browser kept reporting "1 of 1" all the time, not "1 of 3", "2 of 3", etc.
ARIA features used include:
- New roles β [`tablist`](/en-US/docs/Web/Accessibility/ARIA/Roles/tablist_role), [`tab`](/en-US/docs/Web/Accessibility/ARIA/Roles/tab_role), [`tabpanel`](/en-US/docs/Web/Accessibility/ARIA/Roles/tabpanel_role)
- : These identify the important areas of the tabbed interface β the container for the tabs, the tabs themselves, and the corresponding tabpanels.
- [`aria-selected`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected)
- : Defines which tab is currently selected. As different tabs are selected by the user, the value of this attribute on the different tabs is updated via JavaScript.
- [`aria-hidden`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden)
- : Hides an element from being read out by a screen reader. As different tabs are selected by the user, the value of this attribute on the different tabs is updated via JavaScript.
- `tabindex="0"`
- : As we've removed the links, we need to give the list items this attribute to provide it with keyboard focus.
- [`aria-setsize`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize)
- : This property allows you to specify to screen readers that an element is part of a series, and how many items the series has.
- [`aria-posinset`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset)
- : This property allows you to specify what position in a series an element is in. Along with `aria-setsize`, it provides a screen reader with enough information to tell you that you are currently on item "1 of 3", etc. In many cases, browsers should be able to infer this information from the element hierarchy, but it certainly helps to provide more clues.
In our tests, this new structure did serve to improve things overall. The tabs are now recognized as tabs (e.g. "tab" is spoken by the screen reader), the selected tab is indicated by "selected" being read out with the tab name, and the screen reader also tells you which tab number you are currently on. In addition, because of the `aria-hidden` settings (only the non-hidden tab ever has `aria-hidden="false"` set), the non-hidden content is the only one you can navigate down to, meaning the selected content is easier to find.
> **Note:** If there is anything you explicitly don't want screen readers to read out, you can give them the `aria-hidden="true"` attribute.
## 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: WAI-ARIA](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics/Test_your_skills:_WAI-ARIA).
## Summary
This article has by no means covered all that's available in WAI-ARIA, but it should have given you enough information to understand how to use it, and know some of the most common patterns you will encounter that require it.
## See also
- [Aria states and properties](/en-US/docs/Web/Accessibility/ARIA/Attributes): All `aria-*` attributes
- [WAI-ARIA roles](/en-US/docs/Web/Accessibility/ARIA/Roles): Categories of ARIA roles and the roles covered on MDN
- [ARIA in HTML](https://www.w3.org/TR/html-aria/) on W3C: A specification that defines, for each HTML feature, the accessibility (ARIA) semantics implicitly applied on it by the browser and the WAI-ARIA features you may set on it if extra semantics are required
- [Deque university code library](https://dequeuniversity.com/library/): A library of really useful and practical examples showing complex UI controls made accessible using WAI-ARIA features
- [WAI-ARIA authoring practices](https://www.w3.org/WAI/ARIA/apg/) on W3C: A very detailed design pattern from the W3C, explaining how to implement different types of complex UI control whilst making them accessible using WAI-ARIA features
{{PreviousMenuNext("Learn/Accessibility/CSS_and_JavaScript","Learn/Accessibility/Multimedia", "Learn/Accessibility")}}
| 0 |
data/mdn-content/files/en-us/learn/accessibility/wai-aria_basics | data/mdn-content/files/en-us/learn/accessibility/wai-aria_basics/test_your_skills_colon__wai-aria/index.md | ---
title: "Test your skills: WAI-ARIA"
slug: Learn/Accessibility/WAI-ARIA_basics/Test_your_skills:_WAI-ARIA
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [WAI-ARIA basics](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics) 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).
## WAI-ARIA 1
In our first ARIA task, we present you with a section of non-semantic markup, which is obviously meant to be a list. Assuming you are not able to change the elements used, how can you allow screen reader users to recognize this as a list?
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/accessibility/tasks/html-css/aria/aria1.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/accessibility/tasks/html-css/aria/aria1-download.html) to work in your own editor or in an online editor.
## WAI-ARIA 2
In our second WAI-ARIA task, we present a simple search form, and we want you to add in a couple of WAI-ARIA features to improve its accessibility:
1. How can you allow the search form to be called out as a separate landmark on the page by screen readers, to make it easily findable?
2. How can you give the search input a suitable label, without explicitly adding a visible text label to the DOM?
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/accessibility/tasks/html-css/aria/aria2.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/accessibility/tasks/html-css/aria/aria2-download.html) to work in your own editor or in an online editor.
## WAI-ARIA 3
For this final WAI-ARIA task, we return to an example we previously saw in the [CSS and JavaScript skill test](/en-US/docs/Learn/Accessibility/CSS_and_JavaScript/Test_your_skills:_CSS_and_JavaScript_accessibility). As before, we have a simple app that presents a list of animal names. Clicking one of the animal names causes a further description of that animal to appear in a box below the list. Here, we are starting with a mouse- and keyboard-accessible version.
The problem we have now is that when the DOM changes to show a new description, screen readers cannot see what has changed. Can you update it so that description changes are announced by the screen reader?
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/accessibility/tasks/js/aria/aria-js1-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/accessibility | data/mdn-content/files/en-us/learn/accessibility/test_your_skills_colon__html_accessibility/index.md | ---
title: "Test your skills: HTML accessibility"
slug: Learn/Accessibility/Test_your_skills:_HTML_accessibility
page-type: learn-module-assessment
---
{{learnsidebar}}
The aim of this skill test is to assess whether you've understood our [HTML: A good basis for accessibility](/en-US/docs/Learn/Accessibility/HTML) 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 accessibility 1
In this task we will test your understanding of text semantics, and why they are good for accessibility. The given text is a simple information panel with action buttons, but the HTML is really bad.
We want you to update it use appropriate semantic HTML. You don't need to worry too much about recreating the _exact_ same look and text sizing, as long as the semantics are good.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/accessibility/tasks/html-css/html/html-a11y1.html", '100%', 1100)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/accessibility/tasks/html-css/html/html-a11y1-download.html) to work in your own editor or in an online editor.
## HTML accessibility 2
In the second task, you have a form containing three input fields. You need to:
- Semantically associate the input with their labels.
- Assume that these inputs will be part of a larger form, and wrap them in an element that associates them all together as a single related group.
- Give the group a description/title that summarizes all of the information as personal data.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/accessibility/tasks/html-css/html/html-a11y2.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/accessibility/tasks/html-css/html/html-a11y2-download.html) to work in your own editor or in an online editor.
## HTML accessibility 3
In this task you are required to turn all the information links in the paragraph into good, accessible links.
- The first two links just go to regular web pages.
- The third link goes to a PDF, and it's large β 8MB.
- The fourth link goes to a Word document, so the user will need some kind of application installed that can handle that.
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/accessibility/tasks/html-css/html/html-a11y3.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/accessibility/tasks/html-css/html/html-a11y3-download.html) to work in your own editor or in an online editor.
## HTML accessibility 4
In our final HTML accessibility task, you are given a simple image gallery, which has some accessibility problems. Can you fix them?
- The header image has an accessibility issue, and so do the gallery images.
- You could take the header image further and implement it using CSS for arguably better accessibility. Why is this better, and what would a solution look like?
Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("learning-area/accessibility/tasks/html-css/html/html-a11y4.html", '100%', 1100)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/learning-area/blob/main/accessibility/tasks/html-css/html/html-a11y4-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn | data/mdn-content/files/en-us/learn/css/index.md | ---
title: Learn to style HTML using CSS
slug: Learn/CSS
page-type: learn-topic
---
{{LearnSidebar}}
Cascading Style Sheets β or {{glossary("CSS")}} β is the first technology you should start learning after {{glossary("HTML")}}. While HTML is used to define the structure and semantics of your content, CSS is used to style it and lay it out. For example, you can use CSS to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.
> **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 learn the basics of HTML before attempting any CSS. We recommend that you work through our [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) module first.
Once you understand the fundamentals of HTML, we recommend that you learn further HTML and CSS at the same time, moving back and forth between the two topics. This is because HTML is far more interesting and much more fun to learn when you apply CSS, and you can't learn CSS without knowing HTML.
Before starting this topic, you should also be familiar with using computers and using the web passively (i.e., just looking at it, consuming the content). You should have 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 understand how to create and manage files, as detailed in [Dealing with files](/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files) β both of which are parts of our [Getting started with the web](/en-US/docs/Learn/Getting_started_with_the_web) complete beginner's module.
It is also recommended that you work through [Getting started with the web](/en-US/docs/Learn/Getting_started_with_the_web) before proceeding with this topic, especially if you are completely new to web development. However, much of what is covered in its [CSS basics](/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics) article is also covered in our [CSS first steps](/en-US/docs/Learn/CSS/First_steps) module, albeit in a lot more detail.
## Modules
This topic contains the following modules, in a suggested order for working through them. You should start with the first one.
- [CSS first steps](/en-US/docs/Learn/CSS/First_steps)
- : CSS (Cascading Style Sheets) is used to style and layout web pages β for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features. This module provides a gentle beginning to your path towards CSS mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to HTML.
- [CSS building blocks](/en-US/docs/Learn/CSS/Building_blocks)
- : This module carries on where [CSS first steps](/en-US/docs/Learn/CSS/First_steps) left off β now you've gained familiarity with the language and its syntax, and got some basic experience with 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).
- [CSS styling text](/en-US/docs/Learn/CSS/Styling_text)
- : With the basics of the CSS language covered, the next CSS topic for you to concentrate on is styling text β one of the most common things you'll do with CSS. Here we look at text styling fundamentals, including setting font, boldness, italics, line and letter spacing, drop shadows, and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links.
- [CSS layout](/en-US/docs/Learn/CSS/CSS_layout)
- : At this point, we've already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place with respect to the viewport, and one another. We have covered the necessary prerequisites so we can now dive deep into CSS layout, looking at different display settings, modern layout tools like flexbox, CSS grid, and positioning, and some of the legacy techniques you might still want to know about.
## Solving common CSS problems
[Use CSS to solve common problems](/en-US/docs/Learn/CSS/Howto) provides links to sections of content explaining how to use CSS to solve very common problems when creating a web page.
From the beginning, you'll primarily apply colors to HTML elements and their backgrounds; change the size, shape, and position of elements; and add and define borders on elements. But there's not much you can't do once you have a solid understanding of even the basics of CSS. One of the best things about learning CSS is that once you know the fundamentals, usually you have a pretty good feel for what can and can't be done, even if you don't know how to do it yet!
## "CSS is weird"
CSS works a bit differently from most programming languages and design tools you'll come across. Why does it work the way it does? In the following video, Miriam Suzanne provides a useful explanation of why CSS works as it does, and why it has evolved as it has:
{{EmbedYouTube("aHUtMbJw8iA")}}
## See also
- [CSS on MDN](/en-US/docs/Web/CSS)
- : The main entry point for CSS documentation on MDN, where you'll find detailed reference documentation for all features of the CSS 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/css | data/mdn-content/files/en-us/learn/css/styling_text/index.md | ---
title: CSS styling text
slug: Learn/CSS/Styling_text
page-type: learn-module
---
{{LearnSidebar}}
With the basics of the CSS language covered, the next CSS topic for you to concentrate on is styling text β one of the most common things you'll do with CSS. Here we look at text styling fundamentals including setting font, boldness, italics, line and letter spacing, drop shadows, and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links.
> **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 already have basic familiarity with HTML, as discussed in the [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) module, and be comfortable with CSS fundamentals, as discussed in [Introduction to CSS](/en-US/docs/Learn/CSS/First_steps).
> **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 will teach you all of the essentials behind styling HTML text content.
- [Fundamental text and font styling](/en-US/docs/Learn/CSS/Styling_text/Fundamentals)
- : In this article we go through all the basics of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.
- [Styling lists](/en-US/docs/Learn/CSS/Styling_text/Styling_lists)
- : Lists behave like any other text for the most part, but there are some CSS properties specific to lists that you need to know about, and some best practices to consider. This article explains all.
- [Styling links](/en-US/docs/Learn/CSS/Styling_text/Styling_links)
- : When styling links, it is important to understand how to make use of pseudo-classes to style link states effectively, and how to style links for use in common varied interface features such as navigation menus and tabs. We'll look at all these topics in this article.
- [Web fonts](/en-US/docs/Learn/CSS/Styling_text/Web_fonts)
- : Here we will explore web fonts in detail β these allow you to download custom fonts along with your web page, to allow for more varied, custom text styling.
## Assessments
The following assessment will test your understanding of the text styling techniques covered in the guides above.
- [Typesetting a community school homepage](/en-US/docs/Learn/CSS/Styling_text/Typesetting_a_homepage)
- : In this assessment we'll test your understanding of styling text by getting you to style the text for a community school's homepage.
| 0 |
data/mdn-content/files/en-us/learn/css/styling_text | data/mdn-content/files/en-us/learn/css/styling_text/typesetting_a_homepage/index.md | ---
title: Typesetting a community school homepage
slug: Learn/CSS/Styling_text/Typesetting_a_homepage
page-type: learn-module-assessment
---
{{LearnSidebar}}{{PreviousMenu("Learn/CSS/Styling_text/Web_fonts", "Learn/CSS/Styling_text")}}
In this assessment, we'll test your understanding of all the text styling techniques we've covered throughout this module by getting you to style the text for a community school's homepage. You might just have some fun along the way.
<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 text styling techniques.</td>
</tr>
</tbody>
</table>
## Starting point
To get this assessment started, you should:
- Go and grab the [HTML](https://github.com/mdn/learning-area/blob/main/css/styling-text/typesetting-a-homepage-start/index.html) and [CSS](https://github.com/mdn/learning-area/blob/main/css/styling-text/typesetting-a-homepage-start/style.css) files for the exercise, and the provided [external link icon](https://github.com/mdn/learning-area/blob/main/css/styling-text/typesetting-a-homepage-start/external-link-52.png).
- Make a copy of them on your local computer.
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 external link icon](https://mdn.github.io/learning-area/css/styling-text/typesetting-a-homepage-start/external-link-52.png) as a background image.
> **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've been provided with some raw HTML for the homepage of an imaginary community college, plus some CSS that styles the page into a three column layout and provides some other rudimentary styling. You're to write your CSS additions below the comment at the bottom of the CSS file to make sure it's easy to mark the bits you've done. Don't worry if some of the selectors are repetitious; we'll let you off in this instance.
Fonts:
- First of all, download a couple of free-to-use fonts. Because this is a college, the fonts should be chosen to give the page a fairly serious, formal, trustworthy feel: a serif site-wide font for the general body text, coupled with a sans-serif or slab serif for the headings might be nice.
- Use a suitable service to generate bulletproof `@font-face` code for these two fonts.
- Apply your body font to the whole page, and your heading font to your headings.
General text styling:
- Give the page a site-wide `font-size` of `10px`.
- Give your headings and other element types appropriate font-sizes defined using a suitable relative unit.
- Give your body text a suitable `line-height`.
- Center your top level heading on the page.
- Give your headings a little bit of `letter-spacing` to make them not too squashed, and allow the letters to breathe a bit.
- Give your body text some `letter-spacing` and `word-spacing`, as appropriate.
- Give the first paragraph after each heading in the `<section>` a little bit of text-indentation, say 20px.
Links:
- Give the link, visited, focus, and hover states some colors that go with the color of the horizontal bars at the top and bottom of the page.
- Make it so that links are underlined by default, but when you hover or focus them the underline disappears.
- Remove the default focus outline from ALL the links on the page.
- Give the active state a noticeably different styling so it stands out nicely, but make it still fit in with the overall page design.
- Make it so that _external_ links have the external link icon inserted next to them.
Lists:
- Make sure the spacing of your lists and list items works well with the styling of the overall page. Each list item should have the same `line-height` as a paragraph line, and each list should have the same spacing at its top and bottom as you have between paragraphs.
- Give your list items a nice bullet appropriate for the design of the page. It is up to you whether you choose a custom bullet image or something else.
Navigation menu:
- Style your navigation menu so that it harmonizes with the page.
## Hints and tips
- You don't need to edit the HTML in any way for this exercise.
- You don't necessarily have to make the nav menu look like buttons, but it needs to be a bit taller so that it doesn't look silly on the side of the page; also remember that you need to make this one a vertical nav menu.
## Example
The following screenshot shows an example of what the finished design could look like:

{{PreviousMenu("Learn/CSS/Styling_text/Web_fonts", "Learn/CSS/Styling_text")}}
| 0 |
data/mdn-content/files/en-us/learn/css/styling_text | data/mdn-content/files/en-us/learn/css/styling_text/fundamentals/index.md | ---
title: Fundamental text and font styling
slug: Learn/CSS/Styling_text/Fundamentals
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/CSS/Styling_text/Styling_lists", "Learn/CSS/Styling_text")}}
In this article we'll start you on your journey towards mastering text styling with {{glossary("CSS")}}. Here we'll go through all the basic fundamentals of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.
<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
>), CSS basics (study
<a href="/en-US/docs/Learn/CSS/First_steps">Introduction to CSS</a>).
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn the fundamental properties and techniques needed to style text
on web pages.
</td>
</tr>
</tbody>
</table>
## What is involved in styling text in CSS?
Text inside an element is laid out inside the element's [content box](/en-US/docs/Learn/CSS/Building_blocks/The_box_model#parts_of_a_box). It starts at the top left of the content area (or the top right, in the case of RTL language content), and flows towards the end of the line. Once it reaches the end, it goes down to the next line and flows to the end again. This pattern repeats until all the content has been placed in the box. Text content effectively behaves like a series of inline elements, being laid out on lines adjacent to one another, and not creating line breaks until the end of the line is reached, or unless you force a line break manually using the {{htmlelement("br")}} element.
> **Note:** If the above paragraph leaves you feeling confused, then no matter β go back and review our [Box model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model) article to brush up on the box model theory before carrying on.
The CSS properties used to style text generally fall into two categories, which we'll look at separately in this article:
- **Font styles**: Properties that affect a text's font, e.g., which font gets applied, its size, and whether it's bold, italic, etc.
- **Text layout styles**: Properties that affect the spacing and other layout features of the text, allowing manipulation of, for example, the space between lines and letters, and how the text is aligned within the content box.
> **Note:** Bear in mind that the text inside an element is all affected as one single entity. You can't select and style subsections of text unless you wrap them in an appropriate element (such as a {{htmlelement("span")}} or {{htmlelement("strong")}}), or use a text-specific pseudo-element like [::first-letter](/en-US/docs/Web/CSS/::first-letter) (selects the first letter of an element's text), [::first-line](/en-US/docs/Web/CSS/::first-line) (selects the first line of an element's text), or [::selection](/en-US/docs/Web/CSS/::selection) (selects the text currently highlighted by the cursor).
## Fonts
Let's move straight on to look at properties for styling fonts. In this example, we'll apply some CSS properties to the following HTML sample:
```html
<h1>Tommy the cat</h1>
<p>Well I remember it as though it were a meal agoβ¦</p>
<p>
Said Tommy the Cat as he reeled back to clear whatever foreign matter may have
nestled its way into his mighty throat. Many a fat alley rat had met its
demise while staring point blank down the cavernous barrel of this awesome
prowling machine. Truly a wonder of nature this urban predator β Tommy the cat
had many a story to tell. But it was a rare occasion such as this that he did.
</p>
```
You can find the [finished example on GitHub](https://mdn.github.io/learning-area/css/styling-text/fundamentals/) (see also [the source code](https://github.com/mdn/learning-area/blob/main/css/styling-text/fundamentals/index.html)).
### Color
The {{cssxref("color")}} property sets the color of the foreground content of the selected elements, which is usually the text, but can also include a couple of other things, such as an underline or overline placed on text using the {{cssxref("text-decoration")}} property.
`color` can accept any [CSS color unit](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#colors), for example:
```css
p {
color: red;
}
```
This will cause the paragraphs to become red, rather than the standard browser default of black, like so:
```html hidden
<h1>Tommy the cat</h1>
<p>Well I remember it as though it were a meal agoβ¦</p>
<p>
Said Tommy the Cat as he reeled back to clear whatever foreign matter may have
nestled its way into his mighty throat. Many a fat alley rat had met its
demise while staring point blank down the cavernous barrel of this awesome
prowling machine. Truly a wonder of nature this urban predator β Tommy the cat
had many a story to tell. But it was a rare occasion such as this that he did.
</p>
```
{{ EmbedLiveSample('Color', '100%', 230) }}
### Font families
To set a different font for your text, you use the {{cssxref("font-family")}} property β this allows you to specify a font (or list of fonts) for the browser to apply to the selected elements. The browser will only apply a font if it is available on the machine the website is being accessed on; if not, it will just use a browser [default font](#default_fonts). A simple example looks like so:
```css
p {
font-family: Arial;
}
```
This would make all paragraphs on a page adopt the arial font, which is found on any computer.
#### Web safe fonts
Speaking of font availability, there are only a certain number of fonts that are generally available across all systems and can therefore be used without much worry. These are the so-called **web safe fonts**.
Most of the time, as web developers we want to have more specific control over the fonts used to display our text content. The problem is to find a way to know which font is available on the computer used to see our web pages. There is no way to know this in every case, but the web safe fonts are known to be available on nearly all instances of the most used operating systems (Windows, macOS, the most common Linux distributions, Android, and iOS).
The list of actual web safe fonts will change as operating systems evolve, but it's reasonable to consider the following fonts web safe, at least for now (many of them have been popularized thanks to the Microsoft _[Core fonts for the Web](https://en.wikipedia.org/wiki/Core_fonts_for_the_Web)_ initiative in the late 90s and early 2000s):
<table class="standard-table no-markdown">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Generic type</th>
<th scope="col">Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Arial</td>
<td>sans-serif</td>
<td>
It's often considered best practice to also add <em>Helvetica</em> as a
preferred alternative to <em>Arial</em> as, although their font faces
are almost identical, <em>Helvetica</em> is considered to have a nicer
shape, even if <em>Arial</em> is more broadly available.
</td>
</tr>
<tr>
<td>Courier New</td>
<td>monospace</td>
<td>
Some OSes have an alternative (possibly older) version of the
<em>Courier New</em> font called <em>Courier</em>. It's considered best
practice to use both with <em>Courier New</em> as the preferred
alternative.
</td>
</tr>
<tr>
<td>Georgia</td>
<td>serif</td>
<td></td>
</tr>
<tr>
<td>Times New Roman</td>
<td>serif</td>
<td>
Some OSes have an alternative (possibly older) version of the
<em>Times New Roman</em> font called <em>Times</em>. It's considered
best practice to use both with <em>Times New Roman</em> as the preferred
alternative.
</td>
</tr>
<tr>
<td>Trebuchet MS</td>
<td>sans-serif</td>
<td>
You should be careful with using this font β it isn't widely available
on mobile OSes.
</td>
</tr>
<tr>
<td>Verdana</td>
<td>sans-serif</td>
<td></td>
</tr>
</tbody>
</table>
> **Note:** Among various resources, the [cssfontstack.com](https://www.cssfontstack.com/) website maintains a list of web safe fonts available on Windows and macOS operating systems, which can help you make your decision about what you consider safe for your usage.
> **Note:** There is a way to download a custom font along with a webpage, to allow you to customize your font usage in any way you want: **web fonts**. This is a little bit more complex, and we will discuss it in a [separate article](/en-US/docs/Learn/CSS/Styling_text/Web_fonts) later on in the module.
#### Default fonts
CSS defines five generic names for fonts: `serif`, `sans-serif`, `monospace`, `cursive`, and `fantasy`. These are very generic and the exact font face used from these generic names can vary between each browser and each operating system that they are displayed on. It represents a _worst case scenario_ where the browser will try its best to provide a font that looks appropriate. `serif`, `sans-serif`, and `monospace` are quite predictable and should provide something reasonable. On the other hand, `cursive` and `fantasy` are less predictable and we recommend using them very carefully, testing as you go.
The five names are defined as follows:
<table class="standard-table no-markdown">
<thead>
<tr>
<th scope="col">Term</th>
<th scope="col">Definition</th>
<th scope="col">Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>serif</code></td>
<td>
Fonts that have serifs (the flourishes and other small details you see
at the ends of the strokes in some typefaces).
</td>
<td id="serif-example">
<pre class="brush: html hidden">My big red elephant</pre>
<pre class="brush: css hidden">
body {
font-family: serif;
}</pre
>
{{EmbedLiveSample("serif-example", 100, 60)}}
</td>
</tr>
<tr>
<td><code>sans-serif</code></td>
<td>Fonts that don't have serifs.</td>
<td id="sans-serif-example">
<pre class="brush: html hidden">My big red elephant</pre>
<pre class="brush: css hidden">
body {
font-family: sans-serif;
}</pre
>
{{EmbedLiveSample("sans-serif-example", 100, 60)}}
</td>
</tr>
<tr>
<td><code>monospace</code></td>
<td>
Fonts where every character has the same width, typically used in code
listings.
</td>
<td id="monospace-example">
<pre class="brush: html hidden">My big red elephant</pre>
<pre class="brush: css hidden">
body {
font-family: monospace;
}</pre
>
{{EmbedLiveSample("monospace-example", 100, 60)}}
</td>
</tr>
<tr>
<td><code>cursive</code></td>
<td>
Fonts that are intended to emulate handwriting, with flowing, connected
strokes.
</td>
<td id="cursive-example">
<pre class="brush: html hidden">My big red elephant</pre>
<pre class="brush: css hidden">
body {
font-family: cursive;
}</pre
>
{{EmbedLiveSample("cursive-example", 100, 60)}}
</td>
</tr>
<tr>
<td><code>fantasy</code></td>
<td>Fonts that are intended to be decorative.</td>
<td id="fantasy-example">
<pre class="brush: html hidden">My big red elephant</pre>
<pre class="brush: css hidden">
body {
font-family: fantasy;
}</pre
>
{{EmbedLiveSample("fantasy-example", 100, 60)}}
</td>
</tr>
</tbody>
</table>
#### Font stacks
Since you can't guarantee the availability of the fonts you want to use on your webpages (even a web font _could_ fail for some reason), you can supply a **font stack** so that the browser has multiple fonts it can choose from. This involves a `font-family` value consisting of multiple font names separated by commas, e.g.,
```css
p {
font-family: "Trebuchet MS", Verdana, sans-serif;
}
```
In such a case, the browser starts at the beginning of the list and looks to see if that font is available on the machine. If it is, it applies that font to the selected elements. If not, it moves on to the next font, and so on.
It is a good idea to provide a suitable generic font name at the end of the stack so that if none of the listed fonts are available, the browser can at least provide something approximately suitable. To emphasize this point, paragraphs are given the browser's default serif font if no other option is available β which is usually Times New Roman β this is no good for a sans-serif font!
> **Note:** While you can use font family names that contain a space, such as `Trebuchet MS`, without quoting the name, to avoid mistakes in escaping, it is recommended to quote font family names that contain white space, digits, or punctuation characters other than hyphens.
> **Warning:** Any font family name which could be misinterpreted as a generic family name or a CSS-wide keyword must be quoted. While the font-family names can be included as a {{cssxref("custom-ident")}} or a {{cssxref("string")}}, font family names that happen to be the same as a CSS-wide property value, like `initial`, or `inherit`, or CSS have the same name as one to the generic font family names, like `sans-serif` or `fantasy`, must be included as a quoted string. Otherwise, the font family name will be interpreted as being the equivalent CSS keyword or generic family name. When used as keywords, the generic font family names β`serif`, `sans-serif`, `monospace`, `cursive`, and `fantasy` β and the global CSS keywords MUST NOT be quoted, as strings are not interpreted as CSS keywords.
#### A font-family example
Let's add to our previous example, giving the paragraphs a sans-serif font:
```css
p {
color: red;
font-family: Helvetica, Arial, sans-serif;
}
```
This gives us the following result:
```html hidden
<h1>Tommy the cat</h1>
<p>Well I remember it as though it were a meal agoβ¦</p>
<p>
Said Tommy the Cat as he reeled back to clear whatever foreign matter may have
nestled its way into his mighty throat. Many a fat alley rat had met its
demise while staring point blank down the cavernous barrel of this awesome
prowling machine. Truly a wonder of nature this urban predator β Tommy the cat
had many a story to tell. But it was a rare occasion such as this that he did.
</p>
```
{{ EmbedLiveSample('A_font-family_example', '100%', 220) }}
### Font size
In our previous module's [CSS values and units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units) article, we reviewed length and size units. Font size (set with the {{cssxref("font-size")}} property) can take values measured in most of these units (and others, such as [percentages](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#percentages)); however, the most common units you'll use to size text are:
- `px` (pixels): The number of pixels high you want the text to be. This is an absolute unit β it results in the same final computed value for the font on the page in pretty much any situation.
- `em`s: 1 `em` is equal to the font size set on the parent element of the current element we are styling (more specifically, the width of a capital letter M contained inside the parent element). This can become tricky to work out if you have a lot of nested elements with different font sizes set, but it is doable, as you'll see below. Why bother? It is quite natural once you get used to it, and you can use `em` to size everything, not just text. You can have an entire website sized using `em`, which makes maintenance easy.
- `rem`s: These work just like `em`, except that 1 `rem` is equal to the font size set on the root element of the document (i.e. {{htmlelement("html")}}), not the parent element. This makes doing the maths to work out your font sizes much easier, although if you want to support really old browsers, you might struggle β `rem` is not supported in Internet Explorer 8 and below.
The `font-size` of an element is inherited from that element's parent element. This all starts with the root element of the entire document β {{htmlelement("html")}} β the standard `font-size` of which is set to `16px` across browsers. Any paragraph (or another element that doesn't have a different size set by the browser) inside the root element will have a final size of `16px`. Other elements may have different default sizes. For example, an {{htmlelement("Heading_Elements", "h1")}} element has a size of `2em` set by default, so it will have a final size of `32px`.
Things become more tricky when you start altering the font size of nested elements. For example, if you had an {{htmlelement("article")}} element in your page, and set its `font-size` to 1.5 `em` (which would compute to 24 `px` final size), and then wanted the paragraphs inside the `<article>` elements to have a computed font size of 20 `px`, what `em` value would you use?
```html
<!-- document base font-size is 16px -->
<article>
<!-- If my font-size is 1.5em -->
<p>My paragraph</p>
<!-- How do I compute to 20px font-size? -->
</article>
```
You would need to set its `em` value to 20/24, or 0.83333333 `em`. The maths can be complicated, so you need to be careful about how you style things. It is best to use `rem` where you can to keep things simple, and avoid setting the `font-size` of container elements where possible.
### Font style, font weight, text transform, and text decoration
CSS provides four common properties to alter the visual weight/emphasis of text:
- {{cssxref("font-style")}}: Used to turn italic text on or off. Possible values are as follows (you'll rarely use this, unless you want to turn some italic styling off for some reason):
- `normal`: Sets the text to the normal font (turns existing italics off).
- `italic`: Sets the text to use the italic version of the font, if available; if not, it will simulate italics with oblique instead.
- `oblique`: Sets the text to use a simulated version of an italic font, created by slanting the normal version.
- {{cssxref("font-weight")}}: Sets how bold the text is. This has many values available in case you have many font variants available (such as _-light_, _-normal_, _-bold_, _-extrabold_, _-black_, etc.), but realistically you'll rarely use any of them except for `normal` and `bold`:
- `normal`, `bold`: Normal and bold font weight.
- `lighter`, `bolder`: Sets the current element's boldness to be one step lighter or heavier than its parent element's boldness.
- `100` β `900`: Numeric boldness values that provide finer grained control than the above keywords, if needed.
- {{cssxref("text-transform")}}: Allows you to set your font to be transformed. Values include:
- `none`: Prevents any transformation.
- `uppercase`: Transforms all text to capitals.
- `lowercase`: Transforms all text to lower case.
- `capitalize`: Transforms all words to have the first letter capitalized.
- `full-width`: Transforms all glyphs to be written inside a fixed-width square, similar to a monospace font, allowing aligning of, e.g., Latin characters along with Asian language glyphs (like Chinese, Japanese, Korean).
- {{cssxref("text-decoration")}}: Sets/unsets text decorations on fonts (you'll mainly use this to unset the default underline on links when styling them). Available values are:
- `none`: Unsets any text decorations already present.
- `underline`: Underlines the text.
- `overline`: Gives the text an overline.
- `line-through`: Puts a strikethrough over the text.
You should note that {{cssxref("text-decoration")}} can accept multiple values at once if you want to add multiple decorations simultaneously, for example, `text-decoration: underline overline`. Also note that {{cssxref("text-decoration")}} is a shorthand property for {{cssxref("text-decoration-line")}}, {{cssxref("text-decoration-style")}}, and {{cssxref("text-decoration-color")}}. You can use combinations of these property values to create interesting effects, for example: `text-decoration: line-through red wavy`.
Let's look at adding a couple of these properties to our example:
Our new result is like so:
```html hidden
<h1>Tommy the cat</h1>
<p>Well I remember it as though it were a meal agoβ¦</p>
<p>
Said Tommy the Cat as he reeled back to clear whatever foreign matter may have
nestled its way into his mighty throat. Many a fat alley rat had met its
demise while staring point blank down the cavernous barrel of this awesome
prowling machine. Truly a wonder of nature this urban predator β Tommy the cat
had many a story to tell. But it was a rare occasion such as this that he did.
</p>
```
```css
html {
font-size: 10px;
}
h1 {
font-size: 5rem;
text-transform: capitalize;
}
h1 + p {
font-weight: bold;
}
p {
font-size: 1.5rem;
color: red;
font-family: Helvetica, Arial, sans-serif;
}
```
{{ EmbedLiveSample('Font_style_font_weight_text_transform_and_text_decoration', '100%', 260) }}
### Text drop shadows
You can apply drop shadows to your text using the {{cssxref("text-shadow")}} property. This takes up to four values, as shown in the example below:
```css
text-shadow: 4px 4px 5px red;
```
The four properties are as follows:
1. The horizontal offset of the shadow from the original text β this can take most available CSS [length and size units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#length_and_size), but you'll most commonly use `px`; positive values move the shadow right, and negative values left. This value has to be included.
2. The vertical offset of the shadow from the original text. This behaves similarly to the horizontal offset, except that it moves the shadow up/down, not left/right. This value has to be included.
3. The blur radius: a higher value means the shadow is dispersed more widely. If this value is not included, it defaults to 0, which means no blur. This can take most available CSS [length and size units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#length_and_size).
4. The base color of the shadow, which can take any [CSS color unit](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#colors). If not included, it defaults to [`currentcolor`](/en-US/docs/Web/CSS/color_value#currentcolor_keyword), i.e. the shadow's color is taken from the element's [`color`](/en-US/docs/Web/CSS/color) property.
#### Multiple shadows
You can apply multiple shadows to the same text by including multiple shadow values separated by commas, for example:
```css
h1 {
text-shadow:
1px 1px 1px red,
2px 2px 1px red;
}
```
If we applied this to the {{htmlelement("Heading_Elements", "h1")}} element in our Tommy The Cat example, we'd end up with this:
```html hidden
<h1>Tommy the cat</h1>
<p>Well I remember it as though it were a meal agoβ¦</p>
<p>
Said Tommy the Cat as he reeled back to clear whatever foreign matter may have
nestled its way into his mighty throat. Many a fat alley rat had met its
demise while staring point blank down the cavernous barrel of this awesome
prowling machine. Truly a wonder of nature this urban predator β Tommy the cat
had many a story to tell. But it was a rare occasion such as this that he did.
</p>
```
```css hidden
html {
font-size: 10px;
}
h1 {
font-size: 5rem;
text-transform: capitalize;
}
h1 + p {
font-weight: bold;
}
p {
font-size: 1.5rem;
color: red;
font-family: Helvetica, Arial, sans-serif;
}
```
{{ EmbedLiveSample('Multiple_shadows', '100%', 260) }}
> **Note:** You can see more interesting examples of `text-shadow` usage in the Sitepoint article [Moonlighting with CSS text-shadow](https://www.sitepoint.com/moonlighting-css-text-shadow/).
## Text layout
With basic font properties out of the way, let's have a look at properties we can use to affect text layout.
### Text alignment
The {{cssxref("text-align")}} property is used to control how text is aligned within its containing content box. The available values are listed below. They work in pretty much the same way as they do in a regular word processor application:
- `left`: Left-justifies the text.
- `right`: Right-justifies the text.
- `center`: Centers the text.
- `justify`: Makes the text spread out, varying the gaps in between the words so that all lines of text are the same width. You need to use this carefully β it can look terrible, especially when applied to a paragraph with lots of long words in it. If you are going to use this, you should also think about using something else along with it, such as {{cssxref("hyphens")}}, to break some of the longer words across lines.
If we applied `text-align: center;` to the {{htmlelement("Heading_Elements", "h1")}} in our example, we'd end up with this:
```html hidden
<h1>Tommy the cat</h1>
<p>Well I remember it as though it were a meal agoβ¦</p>
<p>
Said Tommy the Cat as he reeled back to clear whatever foreign matter may have
nestled its way into his mighty throat. Many a fat alley rat had met its
demise while staring point blank down the cavernous barrel of this awesome
prowling machine. Truly a wonder of nature this urban predator β Tommy the cat
had many a story to tell. But it was a rare occasion such as this that he did.
</p>
```
```css
html {
font-size: 10px;
}
h1 {
font-size: 5rem;
text-transform: capitalize;
text-shadow:
1px 1px 1px red,
2px 2px 1px red;
text-align: center;
}
h1 + p {
font-weight: bold;
}
p {
font-size: 1.5rem;
color: red;
font-family: Helvetica, Arial, sans-serif;
}
```
{{ EmbedLiveSample('Text_alignment', '100%', 260) }}
### Line height
The {{cssxref("line-height")}} property sets the height of each line of text. This property can not only take most [length and size units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#length_and_size), but can also take a unitless value, which acts as a multiplier and is generally considered the best option. With a unitless value, the {{cssxref("font-size")}} gets multiplied and results in the `line-height`. Body text generally looks nicer and is easier to read when the lines are spaced apart. The recommended line height is around 1.5 β 2 (double spaced). To set our lines of text to 1.6 times the height of the font, we'd use:
```css
p {
line-height: 1.6;
}
```
Applying this to the {{htmlelement("p")}} elements in our example would give us this result:
```html hidden
<h1>Tommy the cat</h1>
<p>Well I remember it as though it were a meal agoβ¦</p>
<p>
Said Tommy the Cat as he reeled back to clear whatever foreign matter may have
nestled its way into his mighty throat. Many a fat alley rat had met its
demise while staring point blank down the cavernous barrel of this awesome
prowling machine. Truly a wonder of nature this urban predator β Tommy the cat
had many a story to tell. But it was a rare occasion such as this that he did.
</p>
```
```css
html {
font-size: 10px;
}
h1 {
font-size: 5rem;
text-transform: capitalize;
text-shadow:
1px 1px 1px red,
2px 2px 1px red;
text-align: center;
}
h1 + p {
font-weight: bold;
}
p {
font-size: 1.5rem;
color: red;
font-family: Helvetica, Arial, sans-serif;
line-height: 1.6;
}
```
{{ EmbedLiveSample('Line_height', '100%', 300) }}
### Letter and word spacing
The {{cssxref("letter-spacing")}} and {{cssxref("word-spacing")}} properties allow you to set the spacing between letters and words in your text. You won't use these very often, but might find a use for them to obtain a specific look, or to improve the legibility of a particularly dense font. They can take most [length and size units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#length_and_size).
To illustrate, we could apply some word- and letter-spacing to the first line of each {{htmlelement("p")}} element in our HTML sample with:
```css
p::first-line {
letter-spacing: 4px;
word-spacing: 4px;
}
```
This renders our HTML as:
```html hidden
<h1>Tommy the cat</h1>
<p>Well I remember it as though it were a meal agoβ¦</p>
<p>
Said Tommy the Cat as he reeled back to clear whatever foreign matter may have
nestled its way into his mighty throat. Many a fat alley rat had met its
demise while staring point blank down the cavernous barrel of this awesome
prowling machine. Truly a wonder of nature this urban predator β Tommy the cat
had many a story to tell. But it was a rare occasion such as this that he did.
</p>
```
```css
html {
font-size: 10px;
}
h1 {
font-size: 5rem;
text-transform: capitalize;
text-shadow:
1px 1px 1px red,
2px 2px 1px red;
text-align: center;
letter-spacing: 2px;
}
h1 + p {
font-weight: bold;
}
p {
font-size: 1.5rem;
color: red;
font-family: Helvetica, Arial, sans-serif;
line-height: 1.6;
letter-spacing: 1px;
}
```
{{ EmbedLiveSample('Letter_and_word_spacing', '100%', 330) }}
### Other properties worth looking at
The above properties give you an idea of how to start styling text on a webpage, but there are many more properties you could use. We just wanted to cover the most important ones here. Once you've become used to using the above, you should also explore the following:
Font styles:
- {{cssxref("font-variant")}}: Switch between small caps and normal font alternatives.
- {{cssxref("font-kerning")}}: Switch font kerning options on and off.
- {{cssxref("font-feature-settings")}}: Switch various [OpenType](https://en.wikipedia.org/wiki/OpenType) font features on and off.
- {{cssxref("font-variant-alternates")}}: Control the use of alternate glyphs for a given font-face.
- {{cssxref("font-variant-caps")}}: Control the use of alternate capital glyphs.
- {{cssxref("font-variant-east-asian")}}: Control the usage of alternate glyphs for East Asian scripts, like Japanese and Chinese.
- {{cssxref("font-variant-ligatures")}}: Control which ligatures and contextual forms are used in text.
- {{cssxref("font-variant-numeric")}}: Control the usage of alternate glyphs for numbers, fractions, and ordinal markers.
- {{cssxref("font-variant-position")}}: Control the usage of alternate glyphs of smaller sizes positioned as superscript or subscript.
- {{cssxref("font-size-adjust")}}: Adjust the visual size of the font independently of its actual font size.
- {{cssxref("font-stretch")}}: Switch between possible alternative stretched versions of a given font.
- {{cssxref("text-underline-position")}}: Specify the position of underlines set using the `text-decoration-line` property `underline` value.
- {{cssxref("text-rendering")}}: Try to perform some text rendering optimization.
Text layout styles:
- {{cssxref("text-indent")}}: Specify how much horizontal space should be left before the beginning of the first line of the text content.
- {{cssxref("text-overflow")}}: Define how overflowed content that is not displayed is signaled to users.
- {{cssxref("white-space")}}: Define how whitespace and associated line breaks inside the element are handled.
- {{cssxref("word-break")}}: Specify whether to break lines within words.
- {{cssxref("direction")}}: Define the text direction. (This depends on the language and usually it's better to let HTML handle that part as it is tied to the text content.)
- {{cssxref("hyphens")}}: Switch on and off hyphenation for supported languages.
- {{cssxref("line-break")}}: Relax or strengthen line breaking for Asian languages.
- {{cssxref("text-align-last")}}: Define how the last line of a block or a line, right before a forced line break, is aligned.
- {{cssxref("text-orientation")}}: Define the orientation of the text in a line.
- {{cssxref("overflow-wrap")}}: Specify whether or not the browser may break lines within words in order to prevent overflow.
- {{cssxref("writing-mode")}}: Define whether lines of text are laid out horizontally or vertically and the direction in which subsequent lines flow.
## Font shorthand
Many font properties can also be set through the shorthand property {{cssxref("font")}}. These are written in the following order: {{cssxref("font-style")}}, {{cssxref("font-variant")}}, {{cssxref("font-weight")}}, {{cssxref("font-stretch")}}, {{cssxref("font-size")}}, {{cssxref("line-height")}}, and {{cssxref("font-family")}}.
Among all those properties, only `font-size` and `font-family` are required when using the `font` shorthand property.
A forward slash has to be put in between the {{cssxref("font-size")}} and {{cssxref("line-height")}} properties.
A full example would look like this:
```css
font:
italic normal bold normal 3em/1.5 Helvetica,
Arial,
sans-serif;
```
## Active learning: Playing with styling text
In this active learning session we don't have any specific exercises for you to do. We'd just like you to have a good play with some font/text layout properties. See for yourself what you can come up with! You can either do this using offline HTML/CSS files, or enter your code into the live editable example below.
If you make a mistake, you can always reset it using the _Reset_ button.
```html hidden
<div
class="body-wrapper"
style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;">
<h2>HTML Input</h2>
<textarea
id="code"
class="html-input"
style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
<p>Some sample text for your delight</p>
</textarea>
<h2>CSS Input</h2>
<textarea
id="code"
class="css-input"
style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
p {
}
</textarea>
<h2>Output</h2>
<div
class="output"
style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div>
<div class="controls">
<input
id="reset"
type="button"
value="Reset"
style="margin: 10px 10px 0 0;" />
</div>
</div>
```
```js hidden
const htmlInput = document.querySelector(".html-input");
const cssInput = document.querySelector(".css-input");
const reset = document.getElementById("reset");
let htmlCode = htmlInput.value;
let cssCode = cssInput.value;
const output = document.querySelector(".output");
const styleElem = document.createElement("style");
const headElem = document.querySelector("head");
headElem.appendChild(styleElem);
function drawOutput() {
output.innerHTML = htmlInput.value;
styleElem.textContent = cssInput.value;
}
reset.addEventListener("click", () => {
htmlInput.value = htmlCode;
cssInput.value = cssCode;
drawOutput();
});
htmlInput.addEventListener("input", drawOutput);
cssInput.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);
```
{{ EmbedLiveSample('Active_learning_Playing_with_styling_text', 700, 800) }}
## Summary
We hope you enjoyed playing with text in this article! The next article will provide you with all you need to know about [styling HTML lists](/en-US/docs/Learn/CSS/Styling_text/Styling_lists).
{{NextMenu("Learn/CSS/Styling_text/Styling_lists", "Learn/CSS/Styling_text")}}
| 0 |
data/mdn-content/files/en-us/learn/css/styling_text | data/mdn-content/files/en-us/learn/css/styling_text/styling_links/index.md | ---
title: Styling links
slug: Learn/CSS/Styling_text/Styling_links
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Styling_text/Styling_lists", "Learn/CSS/Styling_text/Web_fonts", "Learn/CSS/Styling_text")}}
When styling [links](/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks), it's important to understand how to make use of pseudo-classes to style their states effectively. It's also important to know how to style links for use in common interface features whose content varies, such as navigation menus and tabs. We'll look at both these topics in this article.
<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
>), CSS basics (study
<a href="/en-US/docs/Learn/CSS/First_steps">Introduction to CSS</a>),
<a href="/en-US/docs/Learn/CSS/Styling_text/Fundamentals"
>CSS text and font fundamentals</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to style link states, and how to use links effectively in
common UI features like navigation menus.
</td>
</tr>
</tbody>
</table>
## Let's look at some links
We looked at how links are implemented in your HTML according to best practices in [Creating hyperlinks](/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks). In this article we'll build on this knowledge, showing you the best practices for styling them.
### Link states
The first thing to understand is the concept of link states β different states that links can exist in. These can be styled using different [pseudo-classes](/en-US/docs/Learn/CSS/Building_blocks/Selectors#pseudo-classes):
- **Link**: A link that has a destination (i.e., not just a named anchor), styled using the {{cssxref(":link")}} pseudo class.
- **Visited**: A link that has already been visited (exists in the browser's history), styled using the {{cssxref(":visited")}} pseudo class.
- **Hover**: A link that is hovered over by a user's mouse pointer, styled using the {{cssxref(":hover")}} pseudo class.
- **Focus**: A link that is focused (e.g., moved to by a keyboard user using the
<kbd>Tab</kbd>
key or something similar, or programmatically focused using {{domxref("HTMLElement.focus()")}}) β this is styled using the {{cssxref(":focus")}} pseudo class.
- **Active**: A link that is activated (e.g., clicked on), styled using the {{cssxref(":active")}} pseudo class.
### Default styles
The example below illustrates what a link will look and behave like by default; though the CSS is enlarging and centering the text to make it stand out more. You can compare the look and behavior of the default stylings in the example with the look and behavior of other links on this page which have more CSS styles applied. Default links have the following properties:
- Links are underlined.
- Unvisited links are blue.
- Visited links are purple.
- Hovering a link makes the mouse pointer change to a little hand icon.
- Focused links have an outline around them β you should be able to focus on the links on this page with the keyboard by pressing the tab key. (On Mac, you'll need to use
<kbd>option</kbd>
\+
<kbd>tab</kbd>
, or enable the [Full Keyboard Access: All controls](https://support.apple.com/en-us/guide/mac-help/mchlp1399/mac) option by pressing
<kbd>Ctrl</kbd>
\+
<kbd>F7</kbd>
.)
- Active links are red. Try holding down the mouse button on the link as you click it.
```html
<p><a href="#">A simple link</a></p>
```
```css
p {
font-size: 2rem;
text-align: center;
}
```
{{ EmbedLiveSample('Default_styles', '100%', 130) }}
> **Note:** All the link examples on this page link to the top of their window. The empty fragment (`href="#"`) is used to create simple examples and ensure the live examples, which are each contained in an {{HTMLElement("iframe")}}, don't break.
Interestingly enough, these default styles are nearly the same as they were back in the early days of browsers in the mid-1990s. This is because users know and have come to expect this behavior β if links were styled differently, it would confuse a lot of people. This doesn't mean that you shouldn't style links at all. It just means that you shouldn't stray too far from the expected behavior. You should at least:
- Use underlining for links, but not for other things. If you don't want to underline links, at least highlight them in some other way.
- Make them react in some way when hovered/focused, and in a slightly different way when activated.
The default styles can be turned off/changed using the following CSS properties:
- {{cssxref("color")}} for the text color.
- {{cssxref("cursor")}} for the mouse pointer style β you shouldn't turn this off unless you've got a very good reason.
- {{cssxref("outline")}} for the text outline. An outline is similar to a border. The only difference is that a border takes up space in the box and an outline doesn't; it just sits over the top of the background. The outline is a useful accessibility aid, so should not be removed without adding another method of indicating the focused link.
> **Note:** You are not just limited to the above properties to style your links β you are free to use any properties you like.
### Styling some links
Now that we've looked at the default states in some detail, let's look at a typical set of link styles.
To start off with, we'll write out our empty rulesets:
```css
a {
}
a:link {
}
a:visited {
}
a:focus {
}
a:hover {
}
a:active {
}
```
This order is important because link styles build on one another. For example, the styles in the first rule will apply to all the subsequent ones. When a link is activated, it's usually also hovered over. If you put these in the wrong order, and you're changing the same properties in each ruleset, things won't work as you expect. To remember the order, you could try using a mnemonic like **L**o**V**e **F**ears **HA**te.
Now let's add some more information to get this styled properly:
```css
body {
width: 300px;
margin: 0 auto;
font-size: 1.2rem;
font-family: sans-serif;
}
p {
line-height: 1.4;
}
a {
outline-color: transparent;
}
a:link {
color: #6900ff;
}
a:visited {
color: #a5c300;
}
a:focus {
text-decoration: none;
background: #bae498;
}
a:hover {
text-decoration: none;
background: #cdfeaa;
}
a:active {
background: #6900ff;
color: #cdfeaa;
}
```
We'll also provide some sample HTML to apply the CSS to:
```html
<p>
There are several browsers available, such as <a href="#">Mozilla Firefox</a>,
<a href="#">Google Chrome</a>, and <a href="#">Microsoft Edge</a>.
</p>
```
Putting the two together gives us this result:
{{ EmbedLiveSample('Styling_some_links', '100%', 200) }}
So what did we do here? This certainly looks different to the default styling, but it still provides a familiar enough experience for users to know what's going on:
- The first two rules are not that interesting to this discussion.
- The third rule uses the `a` selector to get rid of the focus outline (which varies across browsers anyway).
- Next, we use the `a:link` and `a:visited` selectors to set a couple of color variations on unvisited and visited links, so they are distinct.
- The next two rules use `a:focus` and `a:hover` to set focused and hovered links to have no underline and different background colors.
- Finally, `a:active` is used to give the links an inverted color scheme while they are being activated, to make it clear something important is happening!
### Active learning: Style your own links
In this active learning session, we'd like you to take our empty set of rules and add your own declarations to make the links look really cool. Use your imagination, go wild. We are sure you can come up with something cooler and just as functional as our example above.
If you make a mistake, you can always reset it using the _Reset_ button. If you get really stuck, press the _Show solution_ button to insert the example we showed above.
```html hidden
<div
class="body-wrapper"
style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;">
<h2>HTML Input</h2>
<textarea
id="code"
class="html-input"
style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
<p>There are several browsers available, such as <a href="#">Mozilla
Firefox</a>, <a href="#">Google Chrome</a>, and
<a href="#">Microsoft Edge</a>.</p>
</textarea>
<h2>CSS Input</h2>
<textarea
id="code"
class="css-input"
style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
a {
}
a:link {
}
a:visited {
}
a:focus {
}
a:hover {
}
a:active {
}
</textarea>
<h2>Output</h2>
<div
class="output"
style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div>
<div class="controls">
<input
id="reset"
type="button"
value="Reset"
style="margin: 10px 10px 0 0;" />
<input
id="solution"
type="button"
value="Show solution"
style="margin: 10px 0 0 10px;" />
</div>
</div>
```
```js hidden
const htmlInput = document.querySelector(".html-input");
const cssInput = document.querySelector(".css-input");
const reset = document.getElementById("reset");
const htmlCode = htmlInput.value;
const cssCode = cssInput.value;
const output = document.querySelector(".output");
const solution = document.getElementById("solution");
const styleElem = document.createElement("style");
const headElem = document.querySelector("head");
headElem.appendChild(styleElem);
function drawOutput() {
output.innerHTML = htmlInput.value;
styleElem.textContent = cssInput.value;
}
reset.addEventListener("click", () => {
htmlInput.value = htmlCode;
cssInput.value = cssCode;
drawOutput();
});
solution.addEventListener("click", () => {
htmlInput.value = htmlCode;
cssInput.value = `p {
font-size: 1.2rem;
font-family: sans-serif;
line-height: 1.4;
}
a {
outline-color: transparent;
text-decoration: none;
padding: 2px 1px 0;
}
a:link {
color: #265301;
}
a:visited {
color: #437A16;
}
a:focus {
border-bottom: 1px solid;
background: #BAE498;
}
a:hover {
border-bottom: 1px solid;
background: #CDFEAA;
}
a:active {
background: #265301;
color: #CDFEAA;
}`;
drawOutput();
});
htmlInput.addEventListener("input", drawOutput);
cssInput.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);
```
{{ EmbedLiveSample('Active_learning_Style_your_own_links', 700, 800) }}
## Including icons on links
A common practice is to include icons on links to provide more of an indicator as to what kind of content the link points to. Let's look at a really simple example that adds an icon to external links (links that lead to other sites). Such an icon usually looks like a little arrow pointing out of a box. For this example, we'll use [this great example from icons8.com](https://icons8.com/icon/741/external-link).
Let's look at some HTML and CSS that will give us the effect we want. First, some simple HTML to style:
```html-nolint
<p>
For more information on the weather, visit our <a href="#">weather page</a>,
look at <a href="https://en.wikipedia.org/">weather on Wikipedia</a>, or check
out
<a href="https://www.nationalgeographic.org/topics/resource-library-weather/">
weather on National Geographic</a>.
</p>
```
Next, the CSS:
```css
body {
width: 300px;
margin: 0 auto;
font-family: sans-serif;
}
p {
line-height: 1.4;
}
a {
outline-color: transparent;
text-decoration: none;
padding: 2px 1px 0;
}
a:link {
color: blue;
}
a:visited {
color: purple;
}
a:focus,
a:hover {
border-bottom: 1px solid;
}
a:active {
color: red;
}
a[href^="http"] {
background: url("external-link-52.png") no-repeat 100% 0;
background-size: 16px 16px;
padding-right: 19px;
}
```
{{ EmbedLiveSample('Including_icons_on_links', '100%', 150) }}
So what's going on here? We'll skip over most of the CSS, as it's just the same information you've looked at before. The last rule, however, is interesting: we're inserting a custom background image on external links in a similar manner to how we handled [custom bullets on list items](/en-US/docs/Learn/CSS/Styling_text/Styling_lists#using_a_custom_bullet_image) in the last article. This time, however, we're using the {{cssxref("background")}} shorthand instead of the individual properties. We set the path to the image we want to insert, specify `no-repeat` so we only get one copy inserted, and then specify the position as 100% of the way to the right of the text content, and 0 pixels from the top.
We also use {{cssxref("background-size")}} to specify the size we want the background image to be shown at. It's useful to have a larger icon and then resize it like this as needed for responsive web design purposes. This does, however, only work with IE 9 and later. So if you need to support older browsers, you'll just have to resize the image and insert it as is.
Finally, we set some {{cssxref("padding-right")}} on the links to make space for the background image to appear in, so we aren't overlapping it with the text.
A final word: how did we select just external links? Well, if you are writing your [HTML links](/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks) properly, you should only be using absolute URLs for external links β it is more efficient to use relative links to link to other parts of your own site (as with the first link). The text "http" should therefore only appear in external links (like the second and third ones), and we can select this with an [attribute selector](/en-US/docs/Learn/CSS/Building_blocks/Selectors#attribute_selectors): `a[href^="http"]` selects {{htmlelement("a")}} elements, but only if they have an [`href`](/en-US/docs/Web/HTML/Element/a#href) attribute with a value that begins with "http".
So that's it. Try revisiting the active learning section above and trying this new technique out!
> **Note:** The `href` values look strange β we've used dummy links here that don't really go anywhere. The reason for this is that if we used real links, you would be able to load an external site in the `<iframe>` the live example is embedded in, thereby losing the example.
> **Note:** Don't worry if you are not familiar with [backgrounds](/en-US/docs/Learn/CSS/Building_blocks) and [responsive web design](/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design) yet; these are explained in other places.
## Styling links as buttons
The tools you've explored so far in this article can also be used in other ways. For example, states like hover can be used to style many different elements, not just links β you might want to style the hover state of paragraphs, list items, or other things.
In addition, links are quite commonly styled to look and behave like buttons in certain circumstances. A website navigation menu can be marked up as a set of links, and this can be styled to look like a set of control buttons or tabs that provide the user with access to other parts of the site. Let's explore how.
First, some HTML:
```html
<nav class="container">
<a href="#">Home</a>
<a href="#">Pizza</a>
<a href="#">Music</a>
<a href="#">Wombats</a>
<a href="#">Finland</a>
</nav>
```
And now our CSS:
```css
body,
html {
margin: 0;
font-family: sans-serif;
}
.container {
display: flex;
gap: 0.625%;
}
a {
flex: 1;
text-decoration: none;
outline-color: transparent;
text-align: center;
line-height: 3;
color: black;
}
a:link,
a:visited,
a:focus {
background: palegoldenrod;
color: black;
}
a:hover {
background: orange;
}
a:active {
background: darkred;
color: white;
}
```
This gives us the following result:
{{ EmbedLiveSample('Styling_links_as_buttons', '100%', 120) }}
The HTML defines a {{HTMLElement("nav")}} element with a `"container"` class. The `<nav>` contains our links.
The CSS includes the styling for the container and the links it contains.
- The second rule says:
- The container is a [flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox). The items it contains β the links, in this case β will be _flex items_.
- The gap between the flex items will be `0.625%` of the container's width.
- The third rule styles the links:
- The first declaration, `flex: 1`, means that the widths of the items will be adjusted so they use all the available space in the container.
- Next, we turn off the default {{cssxref("text-decoration")}} and {{cssxref("outline")}} β we don't want those spoiling our look.
- The last three declarations are to center the text inside each link, set the {{cssxref("line-height")}} to 3 to give the buttons some height (which also has the advantage of centering the text vertically), and set the text color to black.
## Summary
We hope this article has provided you with all you'll need to know about links β for now! The final article in our Styling text module details how to use [custom fonts](/en-US/docs/Learn/CSS/Styling_text/Web_fonts) on your websites (or web fonts, as they are better known).
{{PreviousMenuNext("Learn/CSS/Styling_text/Styling_lists", "Learn/CSS/Styling_text/Web_fonts", "Learn/CSS/Styling_text")}}
| 0 |
data/mdn-content/files/en-us/learn/css/styling_text | data/mdn-content/files/en-us/learn/css/styling_text/web_fonts/index.md | ---
title: Web fonts
slug: Learn/CSS/Styling_text/Web_fonts
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Styling_text/Styling_links", "Learn/CSS/Styling_text/Typesetting_a_homepage", "Learn/CSS/Styling_text")}}
In the first article of the module, we explored the basic CSS features available for styling fonts and text. In this article we will go further, exploring web fonts in detail. We'll see how to use custom fonts with your web page to allow for more varied, custom text styling.
<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
>), CSS basics (study
<a href="/en-US/docs/Learn/CSS/First_steps">Introduction to CSS</a>),
<a href="/en-US/docs/Learn/CSS/Styling_text/Fundamentals"
>CSS text and font fundamentals</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to apply web fonts to a web page, using either a third
party service, or by writing your own code.
</td>
</tr>
</tbody>
</table>
## Font families recap
As we looked at in [Fundamental text and font styling](/en-US/docs/Learn/CSS/Styling_text/Fundamentals), the fonts applied to your HTML can be controlled using the {{cssxref("font-family")}} property. This takes one or more font family names. When displaying a webpage, a browser will travel down a list of font-family values until it finds a font available on the system it is running on:
```css
p {
font-family: Helvetica, "Trebuchet MS", Verdana, sans-serif;
}
```
This system works well, but traditionally web developers' font choices were limited. There are only a handful of fonts that you can guarantee to be available across all common systems β the so-called [Web-safe fonts](/en-US/docs/Learn/CSS/Styling_text/Fundamentals#web_safe_fonts). You can use the font stack to specify preferred fonts, followed by web-safe alternatives, followed by the default system font. However, this increases your workload because of the testing required to make sure that your designs work with each font.
## Web fonts
But there is an alternative that works very well. CSS allows you to specify font files, available on the web, to be downloaded along with your website as it's accessed. This means that any browser supporting this CSS feature can display the fonts you've specifically chosen. Amazing! The syntax required looks something like this:
First of all, you have a {{cssxref("@font-face")}} ruleset at the start of the CSS, which specifies the font file(s) to download:
```css
@font-face {
font-family: "myFont";
src: url("myFont.woff2");
}
```
Below this you use the font family name specified inside {{cssxref("@font-face")}} to apply your custom font to anything you like, as normal:
```css
html {
font-family: "myFont", "Bitstream Vera Serif", serif;
}
```
The syntax does get a bit more complex than this. We'll go into more detail below.
Here are some important things to bear in mind about web fonts:
1. Fonts generally aren't free to use. You have to pay for them and/or follow other license conditions, such as crediting the font creator in your code (or on your site). You shouldn't steal fonts and use them without giving proper credit.
2. All major browsers support WOFF/WOFF2 (Web Open Font Format versions 1 and 2). Even older browsers such as IE9 (released in 2011) support the WOFF format.
3. WOFF2 supports the entirety of the TrueType and OpenType specifications, including variable fonts, chromatic fonts, and font collections.
4. The order in which you list font files is important. If you provide the browser with a list of multiple font files to download, the browser will choose the first font file it's able to use. That's why the format you list first should be the preferred format β that is, WOFF2 β with the older formats listed after that. Browsers that don't understand one format will then fall back to the next format in the list.
5. If you need to work with legacy browsers, you should provide EOT (Embedded Open Type), TTF (TrueType Font), and SVG web fonts for download. This article explains how to use the Fontsquirrel Webfont Generator to generate the required files.
You can use the [Firefox Font Editor](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/edit_fonts/index.html) to investigate and manipulate the fonts in use on your page, whether they are web fonts or not. This video provides a nice walkthrough:
{{EmbedYouTube("UazfLa1O94M")}}
## Active learning: A web font example
With this in mind, let's build up a basic web font example from first principles. It's difficult to demonstrate this using an embedded live example. So instead we would like you to follow the steps detailed in the below sections to get an idea of the process.
You should use the [web-font-start.html](https://github.com/mdn/learning-area/blob/main/css/styling-text/web-fonts/web-font-start.html) and [web-font-start.css](https://github.com/mdn/learning-area/blob/main/css/styling-text/web-fonts/web-font-start.css) files as a starting point to add your code to (see the [live example](https://mdn.github.io/learning-area/css/styling-text/web-fonts/web-font-start.html)). Make a copy of these files in a new directory on your computer now. In the `web-font-start.css` file, you'll find some minimal CSS to deal with the basic layout and typesetting of the example.
### Finding fonts
For this example, we'll use two web fonts: one for the headings and one for the body text. To start with, we need to find the font files that contain the fonts. Fonts are created by font foundries and are stored in different file formats. There are generally three types of sites where you can obtain fonts:
- A free font distributor: This is a site that makes free fonts available for download (there may still be some license conditions, such as crediting the font creator). Examples include [Font Squirrel](https://www.fontsquirrel.com/), [dafont](https://www.dafont.com/), and [Everything Fonts](https://everythingfonts.com/).
- A paid font distributor: This is a site that makes fonts available for a charge, such as [fonts.com](https://www.fonts.com/) or [myfonts.com](https://www.myfonts.com/). You can also buy fonts directly from font foundries, for example [Linotype](https://www.linotype.com/), [Monotype](https://www.monotype.com), or [Exljbris](https://www.exljbris.com/).
- An online font service: This is a site that stores and serves the fonts for you, making the whole process easier. See the [Using an online font service](#using_an_online_font_service) section for more details.
Let's find some fonts! Go to [Font Squirrel](https://www.fontsquirrel.com/) and choose two fonts: a nice interesting font for the headings (maybe a nice display or slab serif font), and a slightly less flashy and more readable font for the paragraphs. When you've found a font, press the download button and save the file inside the same directory as the HTML and CSS files you saved earlier. It doesn't matter whether they are TTF (True Type Fonts) or OTF (Open Type Fonts).
Unzip the two font packages (Web fonts are usually distributed in ZIP files containing the font file(s) and licensing information). You may find multiple font files in the package β some fonts are distributed as a family with different variants available, for example thin, medium, bold, italic, thin italic, etc. For this example, we just want you to concern yourself with a single font file for each choice.
> **Note:** In Font Squirrel, under the "Find fonts" section in the right-hand column, you can click on the different tags and classifications to filter the displayed choices.
### Generating the required code
Now you'll need to generate the required code (and font formats). For each font, follow these steps:
1. Make sure you have satisfied any licensing requirement if you are going to use this in a commercial and/or Web project.
2. Go to the Fontsquirrel [Webfont Generator](https://www.fontsquirrel.com/tools/webfont-generator).
3. Upload your two font files using the _Upload Fonts_ button.
4. Check the checkbox labeled "Yes, the fonts I'm uploading are legally eligible for web embedding."
5. Click _Download your kit_.
After the generator has finished processing, you should get a ZIP file to download. Save it in the same directory as your HTML and CSS.
If you need to support legacy browsers, select the "Expert" mode in the Fontsquirrel Webfont Generator, select SVG, EOT, and TTF formats before downloading your kit.
Web services for font generation typically limit file sizes. In such a case, consider using tools such as:
1. [sfnt2woff-zopfli](https://github.com/bramstein/sfnt2woff-zopfli) for converting ttf to woff
2. [fontforge](https://fontforge.org/) for converting from ttf to svg
3. [batik ttf2svg](https://people.apache.org/~clay/batik/ttf2svg.html) for converting from ttf to svg
4. [woff2](https://github.com/google/woff2) for converting from ttf to woff2
### Implementing the code in your demo
At this point, unzip the webfont kit you just generated. Inside the unzipped directory you'll see some useful items:
- Two versions of each font: the `.woff`, `.woff2` files.
- A demo HTML file for each font β load these in your browser to see what the font will look like in different usage contexts.
- A `stylesheet.css` file, which contains the generated @font-face code you'll need.
To implement these fonts in your demo, follow these steps:
1. Rename the unzipped directory to something easy and simple, like `fonts`.
2. Open up the `stylesheet.css` file and copy the two `@font-face` rulesets into your `web-font-start.css` file β you need to put them at the very top, before any of your CSS, as the fonts need to be imported before you can use them on your site.
3. Each of the `url()` functions points to a font file that we want to import into our CSS. We need to make sure the paths to the files are correct, so add `fonts/` to the start of each path (adjust as necessary).
4. Now you can use these fonts in your font stacks, just like any web safe or default system font. For example:
```css
@font-face {
font-family: "zantrokeregular";
src:
url("fonts/zantroke-webfont.woff2") format("woff2"),
url("fonts/zantroke-webfont.woff") format("woff");
font-weight: normal;
font-style: normal;
}
```
```css
font-family: "zantrokeregular", serif;
```
You should end up with a demo page with some nice fonts implemented on them. Because different fonts are created at different sizes, you may have to adjust the size, spacing, etc., to sort out the look and feel.

> **Note:** If you have any problems getting this to work, feel free to compare your version to our finished files β see [web-font-finished.html](https://github.com/mdn/learning-area/blob/main/css/styling-text/web-fonts/web-font-finished.html) and [web-font-finished.css](https://github.com/mdn/learning-area/blob/main/css/styling-text/web-fonts/web-font-finished.css). You can also download the [code from GitHub](https://github.com/mdn/learning-area/tree/main/css/styling-text/web-fonts) or [run the finished example live](https://mdn.github.io/learning-area/css/styling-text/web-fonts/web-font-finished.html).
## Using an online font service
Online font services generally store and serve fonts for you so you don't have to worry about writing the `@font-face` code. Instead, you generally just need to insert a simple line or two of code into your site to make everything work. Examples include [Adobe Fonts](https://fonts.adobe.com/) and [Cloud.typography](https://www.typography.com/webfonts). Most of these services are subscription-based, with the notable exception of [Google Fonts](https://fonts.google.com/), a useful free service, especially for rapid testing work and writing demos.
Most of these services are easy to use, so we won't cover them in great detail. Let's have a quick look at Google Fonts so you can get the idea. Again, use copies of `web-font-start.html` and `web-font-start.css` as your starting point.
1. Go to [Google Fonts](https://fonts.google.com/).
2. Search for your favorite fonts or use the filters at the top of the page to display the kinds of fonts you want to choose and select a couple of fonts that you like.
3. To select a font family, click on the font preview and press the β button alongside the font.
4. When you've chosen the font families, press the _View your selected families_ button in the top right corner of the page.
5. In the resulting screen, you first need to copy the line of HTML code shown and paste it into the head of your HTML file. Put it above the existing {{htmlelement("link")}} element, so that the font is imported before you try to use it in your CSS.
6. You then need to copy the CSS declarations listed into your CSS as appropriate, to apply the custom fonts to your HTML.
> **Note:** You can find a completed version at [google-font.html](https://github.com/mdn/learning-area/blob/main/css/styling-text/web-fonts/google-font.html) and [google-font.css](https://github.com/mdn/learning-area/blob/main/css/styling-text/web-fonts/google-font.css), if you need to check your work against ours ([see it live](https://mdn.github.io/learning-area/css/styling-text/web-fonts/google-font.html)).
## @font-face in more detail
Let's explore that `@font-face` syntax generated for you by Fontsquirrel. This is what one of the rulesets looks like:
```css
@font-face {
font-family: "zantrokeregular";
src:
url("zantroke-webfont.woff2") format("woff2"),
url("zantroke-webfont.woff") format("woff");
font-weight: normal;
font-style: normal;
}
```
Let's go through it to see what it does:
- `font-family`: This line specifies the name you want to refer to the font as. This can be anything you like as long as you use it consistently throughout your CSS.
- `src`: These lines specify the paths to the font files to be imported into your CSS (the `url` part), and the format of each font file (the `format` part). The latter part in each case is optional, but is useful to declare because it allows browsers to more quickly determine which font they can use. Multiple declarations can be listed, separated by commas. Because the browser will search through them according to the rules of the cascade, it's best to state your preferred formats, like WOFF2, at the beginning.
- {{cssxref("font-weight")}}/{{cssxref("font-style")}}: These lines specify what weight the font has and whether it is italic or not. If you are importing multiple weights of the same font, you can specify what their weight/style is and then use different values of {{cssxref("font-weight")}}/{{cssxref("font-style")}} to choose between them, rather than having to call all the different members of the font family different names. [@font-face tip: define font-weight and font-style to keep your CSS simple](https://www.456bereastreet.com/archive/201012/font-face_tip_define_font-weight_and_font-style_to_keep_your_css_simple/) by Roger Johansson shows what to do in more detail.
> **Note:** You can also specify particular {{cssxref("font-variant")}} and {{cssxref("font-stretch")}} values for your web fonts. In newer browsers, you can also specify a {{cssxref("@font-face/unicode-range", "unicode-range")}} value, which is a specific range of characters you might want to use out of the web font. In supporting browsers, the font will only be downloaded if the page contains those specified characters, saving unnecessary downloading. [Creating Custom Font Stacks with Unicode-Range](https://24ways.org/2011/creating-custom-font-stacks-with-unicode-range/) by Drew McLellan provides some useful ideas on how to make use of this.
## Variable fonts
There is a newer font technology available in browsers called variable fonts. These are fonts that allow many different variations of a typeface to be incorporated into a single file, rather than having a separate font file for every width, weight, or style. They are somewhat advanced for our beginner's course, but if you fancy stretching yourself and looking into them, read our [Variable fonts guide](/en-US/docs/Web/CSS/CSS_fonts/Variable_fonts_guide).
## Summary
Now that you have worked through our articles on text styling fundamentals, it's time to test your comprehension with our assessment for the module: [Typesetting a community school homepage](/en-US/docs/Learn/CSS/Styling_text/Typesetting_a_homepage).
{{PreviousMenuNext("Learn/CSS/Styling_text/Styling_links", "Learn/CSS/Styling_text/Typesetting_a_homepage", "Learn/CSS/Styling_text")}}
| 0 |
data/mdn-content/files/en-us/learn/css/styling_text | data/mdn-content/files/en-us/learn/css/styling_text/styling_lists/index.md | ---
title: Styling lists
slug: Learn/CSS/Styling_text/Styling_lists
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Styling_text/Fundamentals", "Learn/CSS/Styling_text/Styling_links", "Learn/CSS/Styling_text")}}
[Lists](/en-US/docs/Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals#lists) behave like any other text for the most part, but there are some CSS properties specific to lists that you need to know about, as well as some best practices to consider. This article explains all.
<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
>), CSS basics (study
<a href="/en-US/docs/Learn/CSS/First_steps">Introduction to CSS</a>),
<a href="/en-US/docs/Learn/CSS/Styling_text/Fundamentals"
>CSS text and font fundamentals</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To become familiar with the best practices and properties related to
styling lists.
</td>
</tr>
</tbody>
</table>
## A simple list example
To begin with, let's look at a simple list example. Throughout this article, we'll look at unordered, ordered, and description lists β all have styling features that are similar, as well as some that are particular to themselves. The unstyled example is [available on GitHub](https://mdn.github.io/learning-area/css/styling-text/styling-lists/unstyled-list.html) (check out the [source code](https://github.com/mdn/learning-area/blob/main/css/styling-text/styling-lists/unstyled-list.html) too.)
The HTML for our list example looks like so:
```html
<h2>Shopping (unordered) list</h2>
<p>
Paragraph for reference, paragraph for reference, paragraph for reference,
paragraph for reference, paragraph for reference, paragraph for reference.
</p>
<ul>
<li>Hummus</li>
<li>Pita</li>
<li>Green salad</li>
<li>Halloumi</li>
</ul>
<h2>Recipe (ordered) list</h2>
<p>
Paragraph for reference, paragraph for reference, paragraph for reference,
paragraph for reference, paragraph for reference, paragraph for reference.
</p>
<ol>
<li>Toast pita, leave to cool, then slice down the edge.</li>
<li>
Fry the halloumi in a shallow, non-stick pan, until browned on both sides.
</li>
<li>Wash and chop the salad.</li>
<li>Fill pita with salad, hummus, and fried halloumi.</li>
</ol>
<h2>Ingredient description list</h2>
<p>
Paragraph for reference, paragraph for reference, paragraph for reference,
paragraph for reference, paragraph for reference, paragraph for reference.
</p>
<dl>
<dt>Hummus</dt>
<dd>
A thick dip/sauce generally made from chick peas blended with tahini, lemon
juice, salt, garlic, and other ingredients.
</dd>
<dt>Pita</dt>
<dd>A soft, slightly leavened flatbread.</dd>
<dt>Halloumi</dt>
<dd>
A semi-hard, unripened, brined cheese with a higher-than-usual melting
point, usually made from goat/sheep milk.
</dd>
<dt>Green salad</dt>
<dd>That green healthy stuff that many of us just use to garnish kebabs.</dd>
</dl>
```
If you go to the live example now and investigate the list elements using [browser developer tools](/en-US/docs/Learn/Common_questions/Tools_and_setup/What_are_browser_developer_tools), you'll notice a couple of styling defaults:
- The {{htmlelement("ul")}} and {{htmlelement("ol")}} elements have a top and bottom {{cssxref("margin")}} of `16px` (`1em`) and a {{cssxref("padding-left")}} of `40px` (`2.5em`). If the directionality attribute [`dir`](/en-US/docs/Web/HTML/Global_attributes/dir) is set to right-to-left (`rtl`) for `ul` and `ol` elements, in that case {{cssxref("padding-right")}} comes into effect and its default value is `40px` (`2.5em`) .
- The list items ({{htmlelement("li")}} elements) have no set defaults for spacing.
- The {{htmlelement("dl")}} element has a top and bottom {{cssxref("margin")}} of `16px` (`1em`), but no padding set.
- The {{htmlelement("dd")}} elements have {{cssxref("margin-left")}} of `40px` (`2.5em`).
- The {{htmlelement("p")}} elements we've included for reference have a top and bottom {{cssxref("margin")}} of `16px` (`1em`) β the same as the different list types.
## Handling list spacing
When styling lists, you need to adjust their styles so they keep the same vertical spacing as their surrounding elements (such as paragraphs and images; sometimes called vertical rhythm), and the same horizontal spacing as each other (you can see the [finished styled example](https://mdn.github.io/learning-area/css/styling-text/styling-lists/) on GitHub, and [find the source code](https://github.com/mdn/learning-area/blob/main/css/styling-text/styling-lists/index.html) too).
The CSS used for the text styling and spacing is as follows:
```css
/* General styles */
html {
font-family: Helvetica, Arial, sans-serif;
font-size: 10px;
}
h2 {
font-size: 2rem;
}
ul,
ol,
dl,
p {
font-size: 1.5rem;
}
li,
p {
line-height: 1.5;
}
/* Description list styles */
dd,
dt {
line-height: 1.5;
}
dt {
font-weight: bold;
}
```
- The first rule sets a sitewide font and a baseline font size of 10px. These are inherited by everything on the page.
- Rules 2 and 3 set relative font sizes for the headings, different list types (the children of the list elements inherit these), and paragraphs. This means that each paragraph and list will have the same font size and top and bottom spacing, helping to keep the vertical rhythm consistent.
- Rule 4 sets the same {{cssxref("line-height")}} on the paragraphs and list items β so the paragraphs and each individual list item will have the same spacing between lines. This will also help to keep the vertical rhythm consistent.
- Rules 5 and 6 apply to the description list. We set the same `line-height` on the description list terms and descriptions as we did with the paragraphs and list items. Again, consistency is good! We also make the description terms have bold font, so they visually stand out easier.
## List-specific styles
Now that we've looked at general spacing techniques for lists, let's explore some list-specific properties. There are three properties you should know about to start with, which can be set on {{htmlelement("ul")}} or {{htmlelement("ol")}} elements:
- {{cssxref("list-style-type")}}: Sets the type of bullets to use for the list, for example, square or circle bullets for an unordered list, or numbers, letters, or roman numerals for an ordered list.
- {{cssxref("list-style-position")}}: Sets whether the bullets, at the start of each item, appear inside or outside the lists.
- {{cssxref("list-style-image")}}: Allows you to use a custom image for the bullet, rather than a simple square or circle.
### Bullet styles
As mentioned above, the {{cssxref("list-style-type")}} property allows you to set what type of bullet to use for the bullet points. In our example, we've set the ordered list to use uppercase roman numerals with:
```css
ol {
list-style-type: upper-roman;
}
```
This gives us the following look:

You can find a lot more options by checking out the {{cssxref("list-style-type")}} reference page.
### Bullet position
The {{cssxref("list-style-position")}} property sets whether the bullets appear inside the list items, or outside them before the start of each item. The default value is `outside`, which causes the bullets to sit outside the list items, as seen above.
If you set the value to `inside`, the bullets will sit inside the lines:
```css
ol {
list-style-type: upper-roman;
list-style-position: inside;
}
```

### Using a custom bullet image
The {{cssxref("list-style-image")}} property allows you to use a custom image for your bullet. The syntax is pretty simple:
```css
ul {
list-style-image: url(star.svg);
}
```
However, this property is a bit limited in terms of controlling the position, size, etc. of the bullets. You are better off using the {{cssxref("background")}} family of properties, which you've learned in the [Backgrounds and borders](/en-US/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders) article. For now, here's a taster!
In our finished example, we have styled the unordered list like so (on top of what you've already seen above):
```css
ul {
padding-left: 2rem;
list-style-type: none;
}
ul li {
padding-left: 2rem;
background-image: url(star.svg);
background-position: 0 0;
background-size: 1.6rem 1.6rem;
background-repeat: no-repeat;
}
```
Here we've done the following:
- Set the {{cssxref("padding-left")}} of the {{htmlelement("ul")}} down from the default `40px` to `20px`, then set the same amount on the list items. This is so that, overall, the list items are still lined up with the ordered list items and the description list descriptions, but the list items have some padding for the background images to sit inside. If we didn't do this, the background images would overlap with the list item text, which would look messy.
- Set the {{cssxref("list-style-type")}} to `none`, so that no bullet appears by default. We're going to use {{cssxref("background")}} properties to handle the bullets instead.
- Inserted a bullet onto each unordered list item. The relevant properties are as follows:
- {{cssxref("background-image")}}: This references the path to the image file you want to use as the bullet.
- {{cssxref("background-position")}}: This defines where in the background of the selected element the image will appear β in this case we are saying `0 0`, which means the bullet will appear in the very top left of each list item.
- {{cssxref("background-size")}}: This sets the size of the background image. We ideally want the bullets to be the same size as the list items (or very slightly smaller or larger). We are using a size of `1.6rem` (`16px`), which fits very nicely with the `20px` padding we've allowed for the bullet to sit inside β 16px plus 4px of space between the bullet and the list item text works well.
- {{cssxref("background-repeat")}}: By default, background images repeat until they fill up the available background space. We only want one copy of the image inserted in each case, so we set this to a value of `no-repeat`.
This gives us the following result:

### list-style shorthand
The three properties mentioned above can all be set using a single shorthand property, {{cssxref("list-style")}}. For example, the following CSS:
```css
ul {
list-style-type: square;
list-style-image: url(example.png);
list-style-position: inside;
}
```
Could be replaced by this:
```css
ul {
list-style: square url(example.png) inside;
}
```
The values can be listed in any order, and you can use one, two, or all three (the default values used for the properties that are not included are `disc`, `none`, and `outside`). If both a `type` and an `image` are specified, the type is used as a fallback if the image can't be loaded for some reason.
## Controlling list counting
Sometimes you might want to count differently on an ordered list β e.g., starting from a number other than 1, or counting backwards, or counting in steps of more than 1. HTML and CSS have some tools to help you here.
### start
The [`start`](/en-US/docs/Web/HTML/Element/ol#start) attribute allows you to start the list counting from a number other than 1. The following example:
```html
<ol start="4">
<li>Toast pita, leave to cool, then slice down the edge.</li>
<li>
Fry the halloumi in a shallow, non-stick pan, until browned on both sides.
</li>
<li>Wash and chop the salad.</li>
<li>Fill pita with salad, hummus, and fried halloumi.</li>
</ol>
```
Gives you this output:
{{ EmbedLiveSample('start', '100%', 150) }}
### reversed
The [`reversed`](/en-US/docs/Web/HTML/Element/ol#reversed) attribute will start the list counting down instead of up. The following example:
```html
<ol start="4" reversed>
<li>Toast pita, leave to cool, then slice down the edge.</li>
<li>
Fry the halloumi in a shallow, non-stick pan, until browned on both sides.
</li>
<li>Wash and chop the salad.</li>
<li>Fill pita with salad, hummus, and fried halloumi.</li>
</ol>
```
Gives you this output:
{{ EmbedLiveSample('reversed', '100%', 150) }}
> **Note:** If there are more list items in a reversed list than the value of the `start` attribute, the count will continue to zero and then into negative values.
### value
The [`value`](/en-US/docs/Web/HTML/Element/li#value) attribute allows you to set your list items to specific numerical values. The following example:
```html
<ol>
<li value="2">Toast pita, leave to cool, then slice down the edge.</li>
<li value="4">
Fry the halloumi in a shallow, non-stick pan, until browned on both sides.
</li>
<li value="6">Wash and chop the salad.</li>
<li value="8">Fill pita with salad, hummus, and fried halloumi.</li>
</ol>
```
Gives you this output:
{{ EmbedLiveSample('value', '100%', 150) }}
> **Note:** Even if you are using a non-number {{cssxref("list-style-type")}}, you still need to use the equivalent numerical values in the `value` attribute.
## Active learning: Styling a nested list
In this active learning session, we want you to take what you've learned above and have a go at styling a nested list. We've provided you with the HTML, and we want you to:
1. Give the unordered list square bullets.
2. Give the unordered list items and the ordered list items a line-height of 1.5 of their font-size.
3. Give the ordered list lower alphabetical bullets.
4. Feel free to play with the list example as much as you like, experimenting with bullet types, spacing, or whatever else you can find.
If you make a mistake, you can always reset it using the _Reset_ button. If you get really stuck, press the _Show solution_ button to see a potential answer.
```html hidden
<div
class="body-wrapper"
style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;">
<h2>HTML Input</h2>
<textarea
id="code"
class="html-input"
style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
<ul>
<li>First, light the candle.</li>
<li>Next, open the box.</li>
<li>Finally, place the three magic items in the box, in this exact order, to complete the spell:
<ol>
<li>The book of spells</li>
<li>The shiny rod</li>
<li>The goblin statue</li>
</ol>
</li>
</ul>
</textarea>
<h2>CSS Input</h2>
<textarea
id="code"
class="css-input"
style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></textarea>
<h2>Output</h2>
<div
class="output"
style="width: 90%;height: 12em;padding: 10px;border: 1px solid #0095dd;overflow: auto;"></div>
<div class="controls">
<input
id="reset"
type="button"
value="Reset"
style="margin: 10px 10px 0 0;" />
<input
id="solution"
type="button"
value="Show solution"
style="margin: 10px 0 0 10px;" />
</div>
</div>
```
```js hidden
const htmlInput = document.querySelector(".html-input");
const cssInput = document.querySelector(".css-input");
const reset = document.getElementById("reset");
const htmlCode = htmlInput.value;
const cssCode = cssInput.value;
const output = document.querySelector(".output");
const solution = document.getElementById("solution");
const styleElem = document.createElement("style");
const headElem = document.querySelector("head");
headElem.appendChild(styleElem);
function drawOutput() {
output.innerHTML = htmlInput.value;
styleElem.textContent = cssInput.value;
}
reset.addEventListener("click", () => {
htmlInput.value = htmlCode;
cssInput.value = cssCode;
drawOutput();
});
solution.addEventListener("click", () => {
htmlInput.value = htmlCode;
cssInput.value = `ul {
list-style-type: square;
}
ul li,
ol li {
line-height: 1.5;
}
ol {
list-style-type: lower-alpha;
}`;
drawOutput();
});
htmlInput.addEventListener("input", drawOutput);
cssInput.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);
```
{{ EmbedLiveSample('Active_learning_Styling_a_nested_list', 700, 800) }}
## Summary
Lists are relatively easy to get the hang of styling once you know a few associated basic principles and specific properties. In the next article, we'll move on to [link styling techniques](/en-US/docs/Learn/CSS/Styling_text/Styling_links).
## See also
CSS counters provide advanced tools for customizing list counting and styling, but they are quite complex. We recommend looking into these if you want to stretch yourself. See:
- {{cssxref("@counter-style")}}
- {{cssxref("counter-increment")}}
- {{cssxref("counter-reset")}}
{{PreviousMenuNext("Learn/CSS/Styling_text/Fundamentals", "Learn/CSS/Styling_text/Styling_links", "Learn/CSS/Styling_text")}}
| 0 |
data/mdn-content/files/en-us/learn/css | data/mdn-content/files/en-us/learn/css/css_layout/index.md | ---
title: CSS layout
slug: Learn/CSS/CSS_layout
page-type: learn-module
---
{{LearnSidebar}}
At this point, we've looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to correctly arrange your boxes in relation to the viewport as well as to one another. We've covered the necessary prerequisites, so let's dive deep into CSS layout, looking at such various features as: different display settings, positioning, modern layout tools like flexbox and CSS grid, and some of the legacy techniques you might still want to know about.
> **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 already:
1. Have basic familiarity with HTML, as discussed in the [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) module.
2. Be comfortable with CSS fundamentals, as discussed in [Introduction to CSS](/en-US/docs/Learn/CSS/First_steps).
3. Understand how to [style boxes](/en-US/docs/Learn/CSS/Building_blocks).
> **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
These articles will provide instruction on the fundamental layout tools and techniques available in CSS. At the end of the lessons is an assessment to help you check your understanding of layout methods by laying out a webpage.
- [Introduction to CSS layout](/en-US/docs/Learn/CSS/CSS_layout/Introduction)
- : This article will recap some of the CSS layout features we've already touched upon in previous modules β such as different {{cssxref("display")}} values β and introduce some of the concepts we'll be covering throughout this module.
- [Normal flow](/en-US/docs/Learn/CSS/CSS_layout/Normal_Flow)
- : Elements on webpages lay themselves out according to _normal flow_ - until we do something to change that. This article explains the basics of normal flow as a grounding for learning how to change it.
- [Flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox)
- : [Flexbox](/en-US/docs/Web/CSS/CSS_flexible_box_layout/Typical_use_cases_of_flexbox) is a one-dimensional layout method for laying out items in rows or columns. Items flex to fill additional space and shrink to fit into smaller spaces. This article explains all the fundamentals. After studying this guide you can [test your flexbox skills](/en-US/docs/Learn/CSS/CSS_layout/Flexbox_skills) to check your understanding before moving on.
- [Grids](/en-US/docs/Learn/CSS/CSS_layout/Grids)
- : CSS Grid Layout is a two-dimensional layout system for the web. It lets you lay content out in rows and columns, and has many features that make building complex layouts straightforward. This article will give you all you need to know to get started with page layout, then [test your grid skills](/en-US/docs/Learn/CSS/CSS_layout/Grid_skills) before moving on.
- [Floats](/en-US/docs/Learn/CSS/CSS_layout/Floats)
- : Originally for floating images inside blocks of text, the {{cssxref("float")}} property became one of the most commonly used tools for creating multiple column layouts on webpages. With the advent of Flexbox and Grid it has now returned to its original purpose, as this article explains.
- [Positioning](/en-US/docs/Learn/CSS/CSS_layout/Positioning)
- : Positioning allows you to take elements out of the normal document layout flow and make them behave differently, for example, by sitting on top of one another, or by always remaining in the same place inside the browser viewport. This article explains the different {{cssxref("position")}} values and how to use them.
- [Multiple-column layout](/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout)
- : The multiple-column layout specification gives you a method of laying content out in columns, as you might see in a newspaper. This article explains how to use this feature.
- [Responsive design](/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design)
- : As more diverse screen sizes have appeared on web-enabled devices, the concept of responsive web design (RWD) has appeared: a set of practices that allows web pages to alter their layout and appearance to suit different screen widths, resolutions, etc. It is an idea that changed the way we design for a multi-device web, and in this article we'll help you understand the main techniques you need to know to master it.
- [Beginner's guide to media queries](/en-US/docs/Learn/CSS/CSS_layout/Media_queries)
- : The **CSS Media Query** gives you a way to apply CSS only when the browser and device environment matches a rule that you specify, for example, "viewport is wider than 480 pixels". Media queries are a key part of responsive web design because they allow you to create different layouts depending on the size of the viewport. They can also be used to detect other features of the environment your site is running on, for example, whether the user is using a touchscreen rather than a mouse. In this lesson, you will first learn about the syntax used in media queries, and then you will use them in an interactive example showing how a simple design might be made responsive.
- [Legacy layout methods](/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods)
- : Grid systems are a very common feature used in CSS layouts. Prior to **CSS Grid Layout**, they tended to be implemented using floats or other layout features. You'd first imagine your layout as a set number of columns (e.g., 4, 6, or 12), and then you'd fit your content columns inside these imaginary columns. In this article, we'll explore how these older methods work so that you understand how they were used if you work on an older project.
- [Supporting older browsers](/en-US/docs/Learn/CSS/CSS_layout/Supporting_Older_Browsers)
- : In this module, we recommend using Flexbox and Grid as the main layout methods for your designs. However, there are bound to be visitors to a site you develop in the future who use older browsers, or browsers which do not support the methods you have used. This will always be the case on the web β as new features are developed, different browsers will prioritize different features. This article explains how to use modern web techniques without excluding users of older technology.
## Assessments
The following assessment will test your understanding of the CSS layout methods covered in the guides above.
- [Fundamental layout comprehension](/en-US/docs/Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension)
- : An assessment to test your knowledge of different layout methods by laying out a webpage.
## See also
- [Practical positioning examples](/en-US/docs/Learn/CSS/CSS_layout/Practical_positioning_examples)
- : This article shows how to build some real-world examples to illustrate what kinds of things you can do with positioning.
- [CSS layout cookbook](/en-US/docs/Web/CSS/Layout_cookbook)
- : The CSS layout cookbook aims to bring together recipes for common layout patterns, things you might need to implement in your sites. In addition to providing code you can use as a starting point in your projects, these recipes highlight the different ways layout specifications can be used and the choices you can make as a developer.
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/position_skills/index.md | ---
title: "Test your skills: Positioning"
slug: Learn/CSS/CSS_layout/Position_skills
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand [positioning in CSS](/en-US/docs/Learn/CSS/CSS_layout/Positioning) using the CSS {{CSSxRef("position")}} property and values. You will be working through two small tasks that use different elements of the material you have just covered.
> **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 position the item with a class of `target` to the top and right of the container, which has the 5px grey border.
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/position/position1.html", '100%', 1000)}}
Additional question:
- As an extra challenge, can you change the target to display underneath the text?
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/position/position1-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, if you scroll the box in the example below, the sidebar scrolls with the content. Change it so that the sidebar stays in place and only the content scrolls.

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/position/position2.html", '100%', 1300)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/position/position2-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/flexbox/index.md | ---
title: Flexbox
slug: Learn/CSS/CSS_layout/Flexbox
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Normal_Flow", "Learn/CSS/CSS_layout/Grids", "Learn/CSS/CSS_layout")}}
[Flexbox](/en-US/docs/Web/CSS/CSS_flexible_box_layout) is a one-dimensional layout method for arranging items in rows or columns. Items _flex_ (expand) to fill additional space or shrink to fit into smaller spaces. This article explains all the fundamentals.
<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">Introduction to CSS</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to use the Flexbox layout system to create web layouts.
</td>
</tr>
</tbody>
</table>
## Why Flexbox?
For a long time, the only reliable cross-browser compatible tools available for creating CSS layouts were features like [floats](/en-US/docs/Learn/CSS/CSS_layout/Floats) and [positioning](/en-US/docs/Learn/CSS/CSS_layout/Positioning). These work, but in some ways they're also limiting and frustrating.
The following simple layout designs are either difficult or impossible to achieve with such tools in any kind of convenient, flexible way:
- Vertically centering a block of content inside its parent.
- Making all the children of a container take up an equal amount of the available width/height, regardless of how much width/height is available.
- Making all columns in a multiple-column layout adopt the same height even if they contain a different amount of content.
As you'll see in subsequent sections, flexbox makes a lot of layout tasks much easier. Let's dig in!
## Introducing a simple example
In this article, you'll work through a series of exercises to help you understand how flexbox works. To get started, you should make a local copy of the first starter file β [flexbox0.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/flexbox/flexbox0.html) from our GitHub repo. Load it in a modern browser (like Firefox or Chrome) and have a look at the code in your code editor. You can also [see it live here](https://mdn.github.io/learning-area/css/css-layout/flexbox/flexbox0.html).

You'll see that we have a {{htmlelement("header")}} element with a top level heading inside it and a {{htmlelement("section")}} element containing three {{htmlelement("article")}}s. We're going to use these to create a fairly standard three column layout.
## Specifying what elements to lay out as flexible boxes
To start with, we need to select which elements are to be laid out as flexible boxes. To do this, we set a special value of {{cssxref("display")}} on the parent element of the elements you want to affect. In this case we want to lay out the {{htmlelement("article")}} elements, so we set this on the {{htmlelement("section")}}:
```css
section {
display: flex;
}
```
This causes the `<section>` element to become a **flex container** and its children become **flex items**. This is what it looks like:

This single declaration gives us everything we need. Incredible, right? We have a multiple column layout with equal-sized columns, and the columns are all the same height. This is because the default values given to flex items (the children of the flex container) are set up to solve common problems such as this.
Let's recap what's happening here. Adding a {{cssxref("display")}} value of `flex` to an element makes it a flex container. The container is displayed as [Block-level content](/en-US/docs/Glossary/Block-level_content) in terms of how it interacts with the rest of the page. When the element is converted to a flex container, its children are converted to (and laid out as) flex items.
You can make the container inline using an [outside `display` value](/en-US/docs/Web/CSS/display#outside) (e.g., `display: inline flex`), which affects how the container itself is laid out in the page.
The legacy `inline-flex` display value displays the container as inline as well.
We'll focus on how the contents of the container behave in this tutorial, but if you want to see the effect of inline versus block layout, you can have a look at the [value comparison](/en-US/docs/Web/CSS/display#display_value_comparison) on the `display` property page.
The next sections explain in more detail what flex items are and what happens inside an element when you make it a flex container.
## The flex model
When elements are laid out as flex items, they are laid out along two axes:

- The **main axis** is the axis running in the direction the flex items are laid out in (for example, as a row across the page, or a column down the page.) The start and end of this axis are called the **main start** and **main end**.
- The **cross axis** is the axis running perpendicular to the direction the flex items are laid out in. The start and end of this axis are called the **cross start** and **cross end**.
- The parent element that has `display: flex` set on it (the {{htmlelement("section")}} in our example) is called the **flex container**.
- The items laid out as flexible boxes inside the flex container are called **flex items** (the {{htmlelement("article")}} elements in our example).
Bear this terminology in mind as you go through subsequent sections. You can always refer back to it if you get confused about any of the terms being used.
## Columns or rows?
Flexbox provides a property called {{cssxref("flex-direction")}} that specifies which direction the main axis runs (which direction the flexbox children are laid out in). By default this is set to `row`, which causes them to be laid out in a row in the direction your browser's default language works in (left to right, in the case of an English browser).
Try adding the following declaration to your {{htmlelement("section")}} rule:
```css
flex-direction: column;
```
You'll see that this puts the items back in a column layout, much like they were before we added any CSS. Before you move on, delete this declaration from your example.
> **Note:** You can also lay out flex items in a reverse direction using the `row-reverse` and `column-reverse` values. Experiment with these values too!
## Wrapping
One issue that arises when you have a fixed width or height in your layout is that eventually your flexbox children will overflow their container, breaking the layout. Have a look at our [flexbox-wrap0.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/flexbox/flexbox-wrap0.html) example and try [viewing it live](https://mdn.github.io/learning-area/css/css-layout/flexbox/flexbox-wrap0.html) (take a local copy of this file now if you want to follow along with this example):

Here we see that the children are indeed breaking out of their container. One way in which you can fix this is to add the following declaration to your {{htmlelement("section")}} rule:
```css
flex-wrap: wrap;
```
Also, add the following declaration to your {{htmlelement("article")}} rule:
```css
flex: 200px;
```
Try this now. You'll see that the layout looks much better with this included:

We now have multiple rows. Each row has as many flexbox children fitted into it as is sensible. Any overflow is moved down to the next line. The `flex: 200px` declaration set on the articles means that each will be at least 200px wide. We'll discuss this property in more detail later on. You might also notice that the last few children on the last row are each made wider so that the entire row is still filled.
But there's more we can do here. First of all, try changing your {{cssxref("flex-direction")}} property value to `row-reverse`. Now you'll see that you still have your multiple row layout, but it starts from the opposite corner of the browser window and flows in reverse.
## flex-flow shorthand
At this point it's worth noting that a shorthand exists for {{cssxref("flex-direction")}} and {{cssxref("flex-wrap")}}: {{cssxref("flex-flow")}}. So, for example, you can replace
```css
flex-direction: row;
flex-wrap: wrap;
```
with
```css
flex-flow: row wrap;
```
## Flexible sizing of flex items
Let's now return to our first example and look at how we can control what proportion of space flex items take up compared to the other flex items. Fire up your local copy of [flexbox0.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/flexbox/flexbox0.html), or take a copy of [flexbox1.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/flexbox/flexbox1.html) as a new starting point ([see it live](https://mdn.github.io/learning-area/css/css-layout/flexbox/flexbox1.html)).
First, add the following rule to the bottom of your CSS:
```css
article {
flex: 1;
}
```
This is a unitless proportion value that dictates how much available space along the main axis each flex item will take up compared to other flex items. In this case, we're giving each {{htmlelement("article")}} element the same value (a value of 1), which means they'll all take up an equal amount of the spare space left after properties like padding and margin have been set. This value is proportionally shared among the flex items: giving each flex item a value of 400000 would have exactly the same effect.
Now add the following rule below the previous one:
```css
article:nth-of-type(3) {
flex: 2;
}
```
Now when you refresh, you'll see that the third {{htmlelement("article")}} takes up twice as much of the available width as the other two. There are now four proportion units available in total (since 1 + 1 + 2 = 4). The first two flex items have one unit each, so they each take 1/4 of the available space. The third one has two units, so it takes up 2/4 of the available space (or one-half).
You can also specify a minimum size value within the flex value. Try updating your existing article rules like so:
```css
article {
flex: 1 200px;
}
article:nth-of-type(3) {
flex: 2 200px;
}
```
This basically states, "Each flex item will first be given 200px of the available space. After that, the rest of the available space will be shared according to the proportion units." Try refreshing and you'll see a difference in how the space is shared.

The real value of flexbox can be seen in its flexibility/responsiveness. If you resize the browser window or add another {{htmlelement("article")}} element, the layout continues to work just fine.
## flex: shorthand versus longhand
{{cssxref("flex")}} is a shorthand property that can specify up to three different values:
- The unitless proportion value we discussed above. This can be specified separately using the {{cssxref("flex-grow")}} longhand property.
- A second unitless proportion value, {{cssxref("flex-shrink")}}, which comes into play when the flex items are overflowing their container. This value specifies how much an item will shrink in order to prevent overflow. This is quite an advanced flexbox feature and we won't be covering it any further in this article.
- The minimum size value we discussed above. This can be specified separately using the {{cssxref("flex-basis")}} longhand value.
We'd advise against using the longhand flex properties unless you really have to (for example, to override something previously set). They lead to a lot of extra code being written, and they can be somewhat confusing.
## Horizontal and vertical alignment
You can also use flexbox features to align flex items along the main or cross axis. Let's explore this by looking at a new example: [flex-align0.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/flexbox/flex-align0.html) ([see it live also](https://mdn.github.io/learning-area/css/css-layout/flexbox/flex-align0.html)). We're going to turn this into a neat, flexible button/toolbar. At the moment you'll see a horizontal menu bar with some buttons jammed into the top left-hand corner.

First, take a local copy of this example.
Now, add the following to the bottom of the example's CSS:
```css
div {
display: flex;
align-items: center;
justify-content: space-around;
}
```

Refresh the page and you'll see that the buttons are now nicely centered horizontally and vertically. We've done this via two new properties.
{{cssxref("align-items")}} controls where the flex items sit on the cross axis.
- By default, the value is `stretch`, which stretches all flex items to fill the parent in the direction of the cross axis. If the parent doesn't have a fixed height in the cross axis direction, then all flex items will become as tall as the tallest flex item. This is how our first example had columns of equal height by default.
- The `center` value that we used in our above code causes the items to maintain their intrinsic dimensions, but be centered along the cross axis. This is why our current example's buttons are centered vertically.
- You can also have values like `flex-start` and `flex-end`, which will align all items at the start and end of the cross axis respectively. See {{cssxref("align-items")}} for the full details.
You can override the {{cssxref("align-items")}} behavior for individual flex items by applying the {{cssxref("align-self")}} property to them. For example, try adding the following to your CSS:
```css
button:first-child {
align-self: flex-end;
}
```

Have a look at what effect this has and remove it again when you've finished.
{{cssxref("justify-content")}} controls where the flex items sit on the main axis.
- The default value is `flex-start`, which makes all the items sit at the start of the main axis.
- You can use `flex-end` to make them sit at the end.
- `center` is also a value for `justify-content`. It'll make the flex items sit in the center of the main axis.
- The value we've used above, `space-around`, is useful β it distributes all the items evenly along the main axis with a bit of space left at either end.
- There is another value, `space-between`, which is very similar to `space-around` except that it doesn't leave any space at either end.
The [`justify-items`](/en-US/docs/Web/CSS/justify-items) property is ignored in flexbox layouts.
We'd like to encourage you to play with these values to see how they work before you continue.
## Ordering flex items
Flexbox also has a feature for changing the layout order of flex items without affecting the source order. This is another thing that is impossible to do with traditional layout methods.
The code for this is simple. Try adding the following CSS to your button bar example code:
```css
button:first-child {
order: 1;
}
```
Refresh and you'll see that the "Smile" button has moved to the end of the main axis. Let's talk about how this works in a bit more detail:
- By default, all flex items have an {{cssxref("order")}} value of 0.
- Flex items with higher specified order values will appear later in the display order than items with lower order values.
- Flex items with the same order value will appear in their source order. So if you have four items whose order values have been set as 2, 1, 1, and 0 respectively, their display order would be 4th, 2nd, 3rd, then 1st.
- The 3rd item appears after the 2nd because it has the same order value and is after it in the source order.
You can set negative order values to make items appear earlier than items whose value is 0. For example, you could make the "Blush" button appear at the start of the main axis using the following rule:
```css
button:last-child {
order: -1;
}
```
## Nested flex boxes
It's possible to create some pretty complex layouts with flexbox. It's perfectly OK to set a flex item to also be a flex container, so that its children are also laid out like flexible boxes. Have a look at [complex-flexbox.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/flexbox/complex-flexbox.html) ([see it live also](https://mdn.github.io/learning-area/css/css-layout/flexbox/complex-flexbox.html)).

The HTML for this is fairly simple. We've got a {{htmlelement("section")}} element containing three {{htmlelement("article")}}s. The third {{htmlelement("article")}} contains three {{htmlelement("div")}}s, and the first {{htmlelement("div")}} contains five {{htmlelement("button")}}s:
```plain
section - article
article
article - div - button
div button
div button
button
button
```
Let's look at the code we've used for the layout.
First of all, we set the children of the {{htmlelement("section")}} to be laid out as flexible boxes.
```css
section {
display: flex;
}
```
Next, we set some flex values on the {{htmlelement("article")}}s themselves. Take special note of the second rule here: we're setting the third {{htmlelement("article")}} to have its children laid out like flex items too, but this time we're laying them out like a column.
```css
article {
flex: 1 200px;
}
article:nth-of-type(3) {
flex: 3 200px;
display: flex;
flex-flow: column;
}
```
Next, we select the first {{htmlelement("div")}}. We first use `flex: 1 100px;` to effectively give it a minimum height of 100px, then we set its children (the {{htmlelement("button")}} elements) to also be laid out like flex items. Here we lay them out in a wrapping row and align them in the center of the available space as we did with the individual button example we saw earlier.
```css
article:nth-of-type(3) div:first-child {
flex: 1 100px;
display: flex;
flex-flow: row wrap;
align-items: center;
justify-content: space-around;
}
```
Finally, we set some sizing on the button. This time by giving it a flex value of 1 auto. This has a very interesting effect, which you'll see if you try resizing your browser window width. The buttons will take up as much space as they can. As many will fit on a line as is comfortable; beyond that, they'll drop to a new line.
```css
button {
flex: 1 auto;
margin: 5px;
font-size: 18px;
line-height: 1.5;
}
```
## 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: Flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox_skills).
## Summary
That concludes our tour of the basics of Flexbox. We hope you had fun and will have a good play around with it as you proceed further with your learning. Next, we'll have a look at another important aspect of CSS layouts: [CSS Grids](/en-US/docs/Learn/CSS/CSS_layout/Grids).
## See also
- [CSS-Tricks Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) β an article explaining everything about Flexbox in a visually appealing way
- [Flexbox Froggy](https://flexboxfroggy.com/) β an educational game to learn and better understand the basics of Flexbox
{{PreviousMenuNext("Learn/CSS/CSS_layout/Normal_Flow", "Learn/CSS/CSS_layout/Grids", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/responsive_design/index.md | ---
title: Responsive design
slug: Learn/CSS/CSS_layout/Responsive_Design
page-type: learn-module-chapter
---
{{learnsidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Multiple-column_Layout", "Learn/CSS/CSS_layout/Media_queries", "Learn/CSS/CSS_layout")}}
_Responsive web design_ (RWD) is a web design approach to make web pages render well on all screen sizes and resolutions while ensuring good usability. It is the way to design for a multi-device web. In this article, we'll help you understand some techniques that can be used to master it.
<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> and
<a href="/en-US/docs/Learn/CSS/Building_blocks">CSS building blocks</a
>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the fundamental purposed and CSS features used to implement responsive designs.
</td>
</tr>
</tbody>
</table>
## Precursor to responsive design: mobile web design
Before responsive web design became the standard approach for making websites work across different device types, web developers used to talk about mobile web design, mobile web development, or sometimes, mobile-friendly design. These are basically the same as responsive web design β the goals are to make sure that websites work well across devices with different physical attributes (screen size, resolution) in terms of layout, content (text and media), and performance.
The difference is mainly to do with the devices involved, and the technologies available to create solutions:
- We used to talk about desktop or mobile, but now there are many different types of device available such as desktop, laptop, mobile, tablets, watches, etc. Instead of catering for a few different screen sizes, we now need to design sites defensively to cater for common screen sizes and resolutions, plus unknowns.
- Mobile devices used to be low-powered in terms of CPU/GPU and available bandwidth. Some didn't support CSS or even HTML, and as a result, it was common to perform server-side browser sniffing to determine device/browser type before then serving a site that the device would be able to cope with. Mobile devices often had really simple, basic experiences served to them because it was all they could handle. These days, mobile devices are able to handle the same technologies as desktop computers, so such techniques are less common.
- You should still use the techniques discussed in this article to serve mobile users a suitable experience, as there are still constraints such as battery life and bandwidth to worry about.
- User experience is also a concern. A mobile user of a travel site might just want to check flight times and delay information, for example, and not be presented with a 3D animated globe showing flight paths and your company history. This can be handled using responsive design techniques, however.
- Modern technologies are much better for creating responsive experiences. For example, [responsive images/media technologies](#responsive_imagesmedia) now allow appropriate media to be served to different devices without having to rely on techniques like server-side sniffing.
## Introducing responsive web design
HTML is fundamentally responsive, or _fluid_. If you create a web page containing only HTML, with no CSS, and resize the window, the browser will automatically reflow the text to fit the viewport.
While the default responsive behavior may sound like no solution is needed, long lines of text displayed full screen on a wide monitor can be difficult to read. If wide screen line length is reduced with CSS, such as by creating columns or adding significant padding, the site may look squashed for the user who narrows their browser window or opens the site on a mobile device.

Creating a non-resizable web page by setting a fixed width doesn't work either; that leads to scroll bars on narrow devices and too much empty space on wide screens.
Responsive web design, or RWD, is a design approach that addresses the range of devices and device sizes, enabling automatic adaption to the screen, whether the content is viewed on a tablet, phone, television, or watch.
Responsive web design isn't a separate technology β it is an approach. It is a term used to describe a set of best practices used to create a layout that can _respond_ to any device being used to view the content.
The term _responsive design_, [coined by Ethan Marcotte in 2010](https://alistapart.com/article/responsive-web-design/), described using fluid grids, fluid images, and media queries to create responsive content, as discussed in Zoe Mickley Gillenwater's book [Flexible Web Design](http://flexiblewebbook.com/).
At the time, the recommendation was to use CSS `float` for layout and media queries to query the browser width, creating layouts for different breakpoints. Fluid images are set to not exceed the width of their container; they have their `max-width` property set to `100%`. Fluid images scale down when their containing column narrows but do not grow larger than their intrinsic size when the column grows. This enables an image to scale down to fit its content, rather than overflow it, but not grow larger and become pixelated if the container becomes wider than the image.
Modern CSS layout methods are inherently responsive, and, since the publication of Gillenwater's book and Marcotte's article, we have a multitude of features built into the web platform to make designing responsive sites easier.
The rest of this article will point you to the various web platform features you might want to use when creating a responsive site.
## Media Queries
[Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) allow us to run a series of tests (e.g. whether the user's screen is greater than a certain width, or a certain resolution) and apply CSS selectively to style the page appropriately for the user's needs.
For example, the following media query tests to see if the current web page is being displayed as screen media (therefore not a printed document) and the viewport is at least `80rem` wide. The CSS for the `.container` selector will only be applied if these two things are true.
```css
@media screen and (min-width: 80rem) {
.container {
margin: 1em 2em;
}
}
```
You can add multiple media queries within a stylesheet, tweaking your whole layout or parts of it to best suit the various screen sizes. The points at which a media query is introduced, and the layout changed, are known as _breakpoints_.
A common approach when using Media Queries is to create a simple single-column layout for narrow-screen devices (e.g. mobile phones), then check for wider screens and implement a multiple-column layout when you know that you have enough screen width to handle it. Designing for mobile first is known as **mobile first** design.
If using breakpoints, best practices encourage defining media query breakpoints with [relative units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#relative_length_units) rather than absolute sizes of an individual device.
There are different approaches to the styles defined within a media query block; ranging from using media queries to {{htmlelement("link")}} style sheets based on browser size ranges to only including custom properties variables to store values associated with each breakpoint.
Find out more in the MDN documentation for [Media Queries](/en-US/docs/Web/CSS/CSS_media_queries).
Media queries can help with RWD, but are not a requirement. Flexible grids, relative units, and minimum and maximum unit values can be used without queries.
## Responsive layout technologies
Responsive sites are built on flexible grids, meaning you don't need to target every possible device size with pixel perfect layouts.
By using a flexible grid, you can change a feature or add in a breakpoint and change the design at the point where the content starts to look bad. For example, to ensure line lengths don't become unreadably long as the screen size increases you can use {{cssxref('columns')}}; if a box becomes squashed with two words on each line as it narrows you can set a breakpoint.
Several layout methods, including [Multiple-column layout](/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout), [Flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox), and [Grid](/en-US/docs/Learn/CSS/CSS_layout/Grids) are responsive by default. They all assume that you are trying to create a flexible grid and give you easier ways to do so.
### Multicol
With multicol, you specify a `column-count` to indicate the maximum number of columns you want your content to be split into. The browser then works out the size of these, a size that will change according to the screen size.
```css
.container {
column-count: 3;
}
```
If you instead specify a `column-width`, you are specifying a _minimum_ width. The browser will create as many columns of that width as will comfortably fit into the container, then share out the remaining space between all the columns. Therefore the number of columns will change according to how much space there is.
```css
.container {
column-width: 10em;
}
```
You can use the {{cssxref('columns')}} shorthand to provide a maximum number of columns and a minimum column width. This can ensure line lengths don't become unreadably long as the screen size increases or too narrow as the screen size decreases.
### Flexbox
In Flexbox, flex items shrink or grow, distributing space between the items according to the space in their container. By changing the values for `flex-grow` and `flex-shrink` you can indicate how you want the items to behave when they encounter more or less space around them.
In the example below the flex items will each take an equal amount of space in the flex container, using the shorthand of `flex: 1` as described in the layout topic [Flexbox: Flexible sizing of flex items](/en-US/docs/Learn/CSS/CSS_layout/Flexbox#flexible_sizing_of_flex_items).
```css
.container {
display: flex;
}
.item {
flex: 1;
}
```
> **Note:** As an example, we have built a simple responsive layout above using flexbox. We use a breakpoint to switch to multiple columns when the screen grows, and limit the size of the main content with {{cssxref('max-width')}}: [example](https://mdn.github.io/css-examples/learn/rwd/flex-based-rwd.html), [source code](https://github.com/mdn/css-examples/blob/main/learn/rwd/flex-based-rwd.html).
### CSS grid
In CSS Grid Layout the `fr` unit allows the distribution of available space across grid tracks. The next example creates a grid container with three tracks sized at `1fr`. This will create three column tracks, each taking one part of the available space in the container. You can find out more about this approach to create a grid in the Learn Layout Grids topic, under [Flexible grids with the fr unit](/en-US/docs/Learn/CSS/CSS_layout/Grids#flexible_grids_with_the_fr_unit).
```css
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
```
> **Note:** The grid layout version is even simpler as we can define the columns on the .wrapper: [example](https://mdn.github.io/css-examples/learn/rwd/grid-based-rwd.html), [source code](https://github.com/mdn/css-examples/blob/main/learn/rwd/grid-based-rwd.html).
## Responsive images/media
To ensure media is never larger than its responsive container, the following approach can be used:
```css
img,
picture,
video {
max-width: 100%;
}
```
This scales media to ensure they never overflow their containers. Using a single large image and scaling it down to fit small devices wastes bandwidth by downloading images larger than what is needed.
Responsive Images, using the {{htmlelement("picture")}} element and the {{htmlelement("img")}} `srcset` and `sizes` attributes enables serving images targeted to the user's viewport and the device's resolution. For example, you can include a square image for mobile, but show the same scene as a landscape image on desktop.
The `<picture>` element enables providing multiple sizes along with "hints" (metadata that describes the screen size and resolution the image is best suited for), and the browser will choose the most appropriate image for each device, ensuring that a user will download an image size appropriate for the device they are using. Using `<picture>` along with `max-width` removes the need for sizing images with media queries. It enables targeting images with different aspect ratios to different viewport sizes.
You can also _art direct_ images used at different sizes, thus providing a different crop or completely different image to different screen sizes.
You can find a detailed [guide to Responsive Images in the Learn HTML section](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images) here on MDN.
Other useful tips:
- Always make sure to use an appropriate image format for your website images (such as PNG or JPG), and make sure to optimize the file size using a graphics editor before you put them on your website.
- You can make use of CSS features like [gradients](/en-US/docs/Web/CSS/CSS_images/Using_CSS_gradients) and [shadows](/en-US/docs/Web/CSS/box-shadow) to implement visual effects without using images.
- You can use media queries inside the media attribute on {{htmlelement("source")}} elements nested inside {{htmlelement("video")}}/{{htmlelement("audio")}} elements to serve video/audio files as appropriate for different devices (responsive video/audio).
## Responsive typography
Responsive typography describes changing font sizes within media queries or using viewport units to reflect lesser or greater amounts of screen real estate.
### Using media queries for responsive typography
In this example, we want to set our level 1 heading to be `4rem`, meaning it will be four times our base font size. That's a really large heading! We only want this jumbo heading on larger screen sizes, therefore we first create a smaller heading then use media queries to overwrite it with the larger size if we know that the user has a screen size of at least `1200px`.
```css
html {
font-size: 1em;
}
h1 {
font-size: 2rem;
}
@media (min-width: 1200px) {
h1 {
font-size: 4rem;
}
}
```
We have edited our responsive grid example above to also include responsive type using the method outlined. You can see how the heading switches sizes as the layout goes to the two column version.
On mobile the heading is smaller:

On desktop, however, we see the larger heading size:

> **Note:** See this example in action: [example](https://mdn.github.io/css-examples/learn/rwd/type-rwd.html), [source code](https://github.com/mdn/css-examples/blob/main/learn/rwd/type-rwd.html).
As this approach to typography shows, you do not need to restrict media queries to only changing the layout of the page. They can be used to tweak any element to make it more usable or attractive at alternate screen sizes.
### Using viewport units for responsive typography
Viewport units `vw` can also be used to enable responsive typography, without the need for setting breakpoints with media queries. `1vw` is equal to one percent of the viewport width, meaning that if you set your font size using `vw`, it will always relate to the size of the viewport.
```css
h1 {
font-size: 6vw;
}
```
The problem with doing the above is that the user loses the ability to zoom any text set using the `vw` unit, as that text is always related to the size of the viewport. **Therefore you should never set text using viewport units alone**.
There is a solution, and it involves using [`calc()`](/en-US/docs/Web/CSS/calc). If you add the `vw` unit to a value set using a fixed size such as `em`s or `rem`s then the text will still be zoomable. Essentially, the `vw` unit adds on top of that zoomed value:
```css
h1 {
font-size: calc(1.5rem + 3vw);
}
```
This means that we only need to specify the font size for the heading once, rather than set it up for mobile and redefine it in the media queries. The font then gradually increases as you increase the size of the viewport.
> **Note:** See an example of this in action: [example](https://mdn.github.io/css-examples/learn/rwd/type-vw.html), [source code](https://github.com/mdn/css-examples/blob/main/learn/rwd/type-vw.html).
## The viewport meta tag
If you look at the HTML source of a responsive page, you will usually see the following {{htmlelement("meta")}} tag in the `<head>` of the document.
```html
<meta name="viewport" content="width=device-width,initial-scale=1" />
```
This [viewport](/en-US/docs/Web/HTML/Viewport_meta_tag) meta tag tells mobile browsers that they should set the width of the viewport to the device width, and scale the document to 100% of its intended size, which shows the document at the mobile-optimized size that you intended.
Why is this needed? Because mobile browsers tend to lie about their viewport width.
This meta tag exists because when smartphones first arrived, most sites were not mobile optimized. The mobile browser would, therefore, set the viewport width to 980 pixels, render the page at that width, and show the result as a zoomed-out version of the desktop layout. Users could zoom in and pan around the website to view the bits they were interested in, but it looked bad.
By setting `width=device-width` you are overriding a mobile device's default, like Apple's default `width=980px`, with the actual width of the device. Without it, your responsive design with breakpoints and media queries may not work as intended on mobile browsers. If you've got a narrow screen layout that kicks in at 480px viewport width or less, but the device is saying it is 980px wide, that user will not see your narrow screen layout.
**So you should _always_ include the viewport meta tag in the head of your documents.**
## Summary
Responsive design refers to a site or application design that responds to the environment in which it is viewed. It encompasses a number of CSS and HTML features and techniques and is now essentially just how we build websites by default. Consider the sites that you visit on your phone β it is probably fairly unusual to come across a site that is the desktop version scaled down, or where you need to scroll sideways to find things. This is because the web has moved to this approach of designing responsively.
It has also become much easier to achieve responsive designs with the help of the layout methods you have learned in these lessons. If you are new to web development today you have many more tools at your disposal than in the early days of responsive design. It is therefore worth checking the age of any materials you are using. While the historical articles are still useful, modern use of CSS and HTML makes it far easier to create elegant and useful designs, no matter what device your visitor views the site with.
## See also
- Working with touchscreen devices:
- [Touch events](/en-US/docs/Web/API/Touch_events) provide the ability to interpret finger (or stylus) activity on touch screens or trackpads, enabling quality support for complex touch-based user interfaces.
- Use the [pointer](/en-US/docs/Web/CSS/@media/pointer) or [any-pointer](/en-US/docs/Web/CSS/@media/any-pointer) media queries to load different CSS on touch-enabled devices.
- [CSS-Tricks Guide to Media Queries](https://css-tricks.com/a-complete-guide-to-css-media-queries/)
{{PreviousMenuNext("Learn/CSS/CSS_layout/Multiple-column_Layout", "Learn/CSS/CSS_layout/Media_queries", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/floats/index.md | ---
title: Floats
slug: Learn/CSS/CSS_layout/Floats
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Grids", "Learn/CSS/CSS_layout/Positioning", "Learn/CSS/CSS_layout")}}
Originally for floating images inside blocks of text, the {{cssxref("float")}} property became one of the most commonly used tools for creating multiple column layouts on webpages. With the advent of flexbox and grid it's now returned to its original purpose, as this article explains.
<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">Introduction to CSS</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to create floated features on webpages and to use the clear
property as well as other methods for clearing floats.
</td>
</tr>
</tbody>
</table>
## The background of floats
The {{cssxref("float")}} property was introduced to allow web developers to implement layouts involving an image floating inside a column of text, with the text wrapping around the left or right of it. The kind of thing you might get in a newspaper layout.
But web developers quickly realized that you can float anything, not just images, so the use of float broadened, for example, to fun layout effects such as [drop-caps](https://css-tricks.com/snippets/css/drop-caps/).
Floats have commonly been used to create entire website layouts featuring multiple columns of information floated so they sit alongside one another (the default behavior would be for the columns to sit below one another in the same order as they appear in the source). There are newer, better layout techniques available. Using floats in this way should be regarded as a [legacy technique](/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods).
In this article we'll just concentrate on the proper uses of floats.
## A float example
Let's explore the use of floats. We'll start with an example involving floating a block of text around an element. You can follow along by creating a new `index.html` file on your computer, filling it with an [HTML template](https://github.com/mdn/learning-area/blob/main/html/introduction-to-html/getting-started/index.html), and inserting the below code into it at the appropriate places. At the bottom of the section, you can see a live example of what the final code should look like.
First, we'll start off with some HTML. Add the following to your HTML body, removing anything that was inside there before:
```html
<h1>Float example</h1>
<div class="box">Float</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam
dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus
ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus
laoreet sit amet.
</p>
<p>
Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet
orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare
ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse
ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis
ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et
a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus
sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
```
Now apply the following CSS to your HTML (using a {{htmlelement("style")}} element or a {{htmlelement("link")}} to a separate `.css` file β your choice):
```css
body {
width: 90%;
max-width: 900px;
margin: 0 auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.box {
width: 150px;
height: 100px;
border-radius: 5px;
background-color: rgb(207 232 220);
padding: 1em;
}
```
If you save and refresh, you'll see something much like what you'd expect: the box is sitting above the text, in normal flow.
### Floating the box
To float the box, add the {{cssxref("float")}} and {{cssxref("margin-right")}} properties to the `.box` rule:
```html hidden
<h1>Float example</h1>
<div class="box">Float</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam
dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus
ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus
laoreet sit amet.
</p>
<p>
Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet
orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare
ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse
ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis
ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et
a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus
sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
```
```css
.box {
float: left;
margin-right: 15px;
width: 150px;
height: 100px;
border-radius: 5px;
background-color: rgb(207 232 220);
padding: 1em;
}
```
Now if you save and refresh you'll see something like the following:
{{EmbedLiveSample('Floating_the_box', '100%', 500)}}
Let's think about how the float works. The element with the float set on it (the {{htmlelement("div")}} element in this case) is taken out of the normal layout flow of the document and stuck to the left-hand side of its parent container ({{htmlelement("body")}}, in this case). Any content that would come below the floated element in the normal layout flow will now wrap around it instead, filling up the space to the right-hand side of it as far up as the top of the floated element. There, it will stop.
Floating the content to the right has exactly the same effect, but in reverse: the floated element will stick to the right, and the content will wrap around it to the left. Try changing the float value to `right` and replace {{cssxref("margin-right")}} with {{cssxref("margin-left")}} in the last ruleset to see what the result is.
### Visualizing the float
While we can add a margin to the float to push the text away, we can't add a margin to the text to move it away from the float. This is because a floated element is taken out of normal flow and the boxes of the following items actually run behind the float. You can see this by making some changes to your example.
Add a class of `special` to the first paragraph of text, the one immediately following the floated box, then in your CSS add the following rules. These will give our following paragraph a background color.
```css
.special {
background-color: rgb(148 255 172);
padding: 10px;
color: purple;
}
```
To make the effect easier to see, change the `margin-right` on your float to `margin` so you get space all around the float. You'll be able to see the background on the paragraph running right underneath the floated box, as in the example below.
```html hidden
<h1>Float example</h1>
<div class="box">Float</div>
<p class="special">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam
dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus
ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus
laoreet sit amet.
</p>
<p>
Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet
orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare
ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse
ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis
ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et
a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus
sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
```
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 0 auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.box {
float: left;
margin: 15px;
width: 150px;
height: 150px;
border-radius: 5px;
background-color: rgb(207 232 220);
padding: 1em;
}
```
{{EmbedLiveSample('Visualizing_the_float', '100%', 500)}}
The [line boxes](/en-US/docs/Web/CSS/Visual_formatting_model#line_boxes) of our following element have been shortened so the text runs around the float, but due to the float being removed from normal flow the box around the paragraph still remains full width.
## Clearing floats
We've seen that a float is removed from normal flow and that other elements will display beside it. If we want to stop the following element from moving up, we need to _clear_ it; this is achieved with the {{cssxref("clear")}} property.
In your HTML from the previous example, add a class of `cleared` to the second paragraph below the floated item. Then add the following to your CSS:
```css
.cleared {
clear: left;
}
```
```html hidden
<h1>Float example</h1>
<div class="box">Float</div>
<p class="special">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam
dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus
ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus
laoreet sit amet.
</p>
<p class="cleared">
Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet
orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare
ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse
ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis
ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et
a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus
sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
```
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 0 auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.box {
float: left;
margin: 15px;
width: 150px;
height: 150px;
border-radius: 5px;
background-color: rgb(207 232 220);
padding: 1em;
}
.special {
background-color: rgb(148 255 172);
padding: 10px;
color: purple;
}
.cleared {
clear: left;
}
```
{{EmbedLiveSample('Clearing_floats', '100%', 600)}}
You should see that the second paragraph now clears the floated element and no longer comes up alongside it. The `clear` property accepts the following values:
- `left`: Clear items floated to the left.
- `right`: Clear items floated to the right.
- `both`: Clear any floated items, left or right.
## Clearing boxes wrapped around a float
You now know how to clear something following a floated element, but let's see what happens if you have a tall float and a short paragraph, with a box wrapped around _both_ elements.
### The problem
Change your document so that the first paragraph and the floated box are jointly wrapped with a {{htmlelement("div")}}, which has a class of `wrapper`.
```html live-sample___the_problem
<div class="wrapper">
<div class="box">Float1</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at
ultricies tellus laoreet sit amet.
</p>
</div>
```
In your CSS, add the following rule for the `.wrapper` class and then reload the page:
```css live-sample___the_problem
.wrapper {
background-color: rgb(148 255 172);
padding: 10px;
color: purple;
}
```
In addition, remove the original `.cleared` class:
```css
.cleared {
clear: left;
}
```
You'll see that, just like in the example where we put a background color on the paragraph, the background color runs behind the float.
```html hidden live-sample___the_problem
<p>
Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet
orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare
ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse
ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis
ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et
a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus
sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
```
```css hidden live-sample___the_problem
body {
width: 90%;
max-width: 900px;
margin: 0 auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.box {
float: left;
margin: 15px;
width: 150px;
height: 150px;
border-radius: 5px;
background-color: rgb(207 232 220);
padding: 1em;
color: black;
}
```
{{EmbedLiveSample('the_problem', '100%', 600)}}
Once again, this is because the float has been taken out of normal flow. You might expect that by wrapping the floated box and the text of first paragraph that wraps around the float together, the subsequent content will be cleared of the box. But this is not the case, as shown above. To deal with this, the standard method is to create a [block formatting context](/en-US/docs/Web/CSS/CSS_display/Block_formatting_context) (BFC) using the {{cssxref("display")}} property.
### display: flow-root
To solve this problem is to use the value `flow-root` of the `display` property. This exists only to create a BFC without using hacks β there will be no unintended consequences when you use it.
```css
.wrapper {
background-color: rgb(148 255 172);
padding: 10px;
color: purple;
display: flow-root;
}
```
```html hidden
<h1>Float example</h1>
<div class="wrapper">
<div class="box">Float</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at
ultricies tellus laoreet sit amet.
</p>
</div>
<p class="cleared">
Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet
orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare
ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse
ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis
ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et
a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus
sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
```
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 0 auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.box {
float: left;
margin: 15px;
width: 150px;
height: 150px;
border-radius: 5px;
background-color: rgb(207 232 220);
padding: 1em;
color: black;
}
```
{{EmbedLiveSample('display_flow-root', '100%', 600)}}
## 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: Floats](/en-US/docs/Learn/CSS/CSS_layout/Floats_skills).
## Summary
You now know all there is to know about floats in modern web development. See the article on [legacy layout methods](/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods) for information on how they used to be used, which may be useful if you find yourself working on older projects.
{{PreviousMenuNext("Learn/CSS/CSS_layout/Grids", "Learn/CSS/CSS_layout/Positioning", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/flexbox_skills/index.md | ---
title: "Test your skills: Flexbox"
slug: Learn/CSS/CSS_layout/Flexbox_skills
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand how [flexbox and flex items](/en-US/docs/Learn/CSS/CSS_layout/Flexbox) behave. Below are four common design patterns that you might use flexbox to create. Your task is to build them.
> **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 list items are the navigation for a site. They should be laid out as a row, with an equal amount of space between each item.
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/flexbox/flexbox1.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/flexbox/flexbox1-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, the list items are all different sizes, but we want them to be displayed as three equal sized columns, no matter what content is in each item.
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/flexbox/flexbox2.html", '100%', 800)}}
Additional question:
- Can you now make the first item twice the size of the other items?
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/flexbox/flexbox2-download.html) to work in your own editor or in an online editor.
## Task 3
In this task, there are two elements in the HTML below, a `<div>` element with a class of `parent` which contains another `<div>` element with a class of `child`. Use flexbox to center the child inside the parent. Note that there is not just one possible solution here.
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/flexbox/flexbox3.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/flexbox/flexbox3-download.html) to work in your own editor or in an online editor.
## Task 4
In this task, we want you to arrange these items into rows as in the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/flexbox/flexbox4.html", '100%', 1100)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/flexbox/flexbox4-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/rwd_skills/index.md | ---
title: "Test your skills: Responsive web design and media queries"
slug: Learn/CSS/CSS_layout/rwd_skills
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand [how to use media queries](/en-US/docs/Learn/CSS/CSS_layout/Media_queries) and get you working with responsive web design with a practical task. Everything you need to know to complete this task is covered in the layout lessons in the [CSS layout module](/en-US/docs/Learn/CSS/CSS_layout).
> **Note:** Because you need to test your design in multiple screen sizes, we do not have interactive editors on this page.
> Download the code and work locally, or use 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
[Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/rwd/rwd-download.html). Open the downloaded HTML file in your browser and you will find a wireframed site which will load in a mobile device in a readable manner. You can drag your window smaller or use the [responsive design view in Firefox DevTools](https://firefox-source-docs.mozilla.org/devtools-user/index.html#responsive-design-mode) to view this as if on a phone.
Your task is to create a desktop version of this layout which displays when there is enough screen width to accommodate it. Your final result should look like the image below:

There are a number of ways that you could create the desktop layout, enjoy experimenting. You could also add a second breakpoint perhaps creating a layout that would work well on a tablet in portrait mode.
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/positioning/index.md | ---
title: Positioning
slug: Learn/CSS/CSS_layout/Positioning
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout/Multiple-column_Layout", "Learn/CSS/CSS_layout")}}
Positioning allows you to take elements out of normal document flow and make them behave differently, for example, by sitting on top of one another or by always remaining in the same place inside the browser viewport. This article explains the different {{cssxref("position")}} values and how to use them.
<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">Introduction to CSS</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn how CSS positioning works.</td>
</tr>
</tbody>
</table>
We'd like you to do the following exercises on your local computer. If possible, grab a copy of [`0_basic-flow.html`](https://mdn.github.io/learning-area/css/css-layout/positioning/0_basic-flow.html) from our GitHub repo ([source code here](https://github.com/mdn/learning-area/blob/main/css/css-layout/positioning/0_basic-flow.html)) and use that as a starting point.
## Introducing positioning
Positioning allows us to produce interesting results by overriding normal document flow. What if you want to slightly alter the position of some boxes from their default flow position to give a slightly quirky, distressed feel? Positioning is your tool. Or what if you want to create a UI element that floats over the top of other parts of the page and/or always sits in the same place inside the browser window no matter how much the page is scrolled? Positioning makes such layout work possible.
There are a number of different types of positioning that you can put into effect on HTML elements. To make a specific type of positioning active on an element, we use the {{cssxref("position")}} property.
## Static positioning
Static positioning is the default that every element gets. It just means "put the element into its normal position in the document flow β nothing special to see here."
To see this (and get your example set up for future sections) first add a `class` of `positioned` to the second {{htmlelement("p")}} in the HTML:
```html
<p class="positioned">β¦</p>
```
Now add the following rule to the bottom of your CSS:
```css
.positioned {
position: static;
background: yellow;
}
```
If you save and refresh, you'll see no difference at all, except for the updated background color of the 2nd paragraph. This is fine β as we said before, static positioning is the default behavior!
> **Note:** You can see the example at this point live at [`1_static-positioning.html`](https://mdn.github.io/learning-area/css/css-layout/positioning/1_static-positioning.html) ([see source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/positioning/1_static-positioning.html)).
## Relative positioning
Relative positioning is the first position type we'll take a look at. This is very similar to static positioning, except that once the positioned element has taken its place in the normal flow, you can then modify its final position, including making it overlap other elements on the page. Go ahead and update the `position` declaration in your code:
```css
position: relative;
```
If you save and refresh at this stage, you won't see a change in the result at all. So how do you modify the element's position? You need to use the {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} properties, which we'll explain in the next section.
### Introducing top, bottom, left, and right
{{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} are used alongside {{cssxref("position")}} to specify exactly where to move the positioned element to. To try this out, add the following declarations to the `.positioned` rule in your CSS:
```css
top: 30px;
left: 30px;
```
> **Note:** The values of these properties can take any [units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units) you'd reasonably expect: pixels, mm, rems, %, etc.
If you now save and refresh, you'll get a result something like this:
```html hidden
<h1>Relative positioning</h1>
<p>
I am a basic block level element. My adjacent block level elements sit on new
lines below me.
</p>
<p class="positioned">
By default we span 100% of the width of our parent element, and we are as tall
as our child content. Our total width and height is our content + padding +
border width/height.
</p>
<p>
We are separated by our margins. Because of margin collapsing, we are
separated by the width of one of our margins, not both.
</p>
<p>
Inline elements <span>like this one</span> and <span>this one</span> sit on
the same line as one another, and adjacent text nodes, if there is space on
the same line. Overflowing inline elements
<span>wrap onto a new line if possible β like this one containing text</span>,
or just go on to a new line if not, much like this image will do:
<img src="long.jpg" alt="snippet of cloth" />
</p>
```
```css hidden
body {
width: 500px;
margin: 0 auto;
}
p {
background: aqua;
border: 3px solid blue;
padding: 10px;
margin: 10px;
}
span {
background: red;
border: 1px solid black;
}
.positioned {
position: relative;
background: yellow;
top: 30px;
left: 30px;
}
```
{{ EmbedLiveSample('Introducing_top_bottom_left_and_right', '100%', 500) }}
Cool, huh? Ok, so this probably wasn't what you were expecting. Why has it moved to the bottom and to the right if we specified _top_ and _left_? This may seem counterintuitive. You need to think of it as if there's an invisible force that pushes the specified side of the positioned box, moving it in the opposite direction. So, for example, if you specify `top: 30px;`, it's as if a force will push the top of the box, causing it to move downwards by 30px.
> **Note:** You can see the example at this point live at [`2_relative-positioning.html`](https://mdn.github.io/learning-area/css/css-layout/positioning/2_relative-positioning.html) ([see source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/positioning/2_relative-positioning.html)).
## Absolute positioning
Absolute positioning brings very different results.
### Setting position: absolute
Let's try changing the position declaration in your code as follows:
```css
position: absolute;
```
If you now save and refresh, you should see something like so:
```html hidden
<h1>Absolute positioning</h1>
<p>
I am a basic block level element. My adjacent block level elements sit on new
lines below me.
</p>
<p class="positioned">
By default we span 100% of the width of our parent element, and we are as tall
as our child content. Our total width and height is our content + padding +
border width/height.
</p>
<p>
We are separated by our margins. Because of margin collapsing, we are
separated by the width of one of our margins, not both.
</p>
<p>
inline elements <span>like this one</span> and <span>this one</span> sit on
the same line as one another, and adjacent text nodes, if there is space on
the same line. Overflowing inline elements
<span>wrap onto a new line if possible β like this one containing text</span>,
or just go on to a new line if not, much like this image will do:
<img src="long.jpg" alt="snippet of cloth" />
</p>
```
```css hidden
body {
width: 500px;
margin: 0 auto;
}
p {
background: aqua;
border: 3px solid blue;
padding: 10px;
margin: 10px;
}
span {
background: red;
border: 1px solid black;
}
.positioned {
position: absolute;
background: yellow;
top: 30px;
left: 30px;
}
```
{{ EmbedLiveSample('Setting_position_absolute', '100%', 450) }}
First of all, note that the gap where the positioned element should be in the document flow is no longer there β the first and third elements have closed together like it no longer exists! Well, in a way, this is true. An absolutely positioned element no longer exists in the normal document flow. Instead, it sits on its own layer separate from everything else. This is very useful: it means that we can create isolated UI features that don't interfere with the layout of other elements on the page. For example, popup information boxes, control menus, rollover panels, UI features that can be dragged and dropped anywhere on the page, and so on.
Second, notice that the position of the element has changed. This is because {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} behave in a different way with absolute positioning. Rather than positioning the element based on its relative position within the normal document flow, they specify the distance the element should be from each of the containing element's sides. So in this case, we are saying that the absolutely positioned element should sit 30px from the top of the "containing element" and 30px from the left. (In this case, the "containing element" is the **initial containing block**. See the section below for more information)
> **Note:** You can use {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} to resize elements if you need to. Try setting `top: 0; bottom: 0; left: 0; right: 0;` and `margin: 0;` on your positioned elements and see what happens! Put it back again afterwardsβ¦
> **Note:** Yes, margins still affect positioned elements. Margin collapsing doesn't, however.
> **Note:** You can see the example at this point live at [`3_absolute-positioning.html`](https://mdn.github.io/learning-area/css/css-layout/positioning/3_absolute-positioning.html) ([see source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/positioning/3_absolute-positioning.html)).
### Positioning contexts
Which element is the "containing element" of an absolutely positioned element? This is very much dependent on the position property of the ancestors of the positioned element (See [Identifying the containing block](/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block)).
If no ancestor elements have their position property explicitly defined, then by default all ancestor elements will have a static position. The result of this is the absolutely positioned element will be contained in the **initial containing block**. The initial containing block has the dimensions of the viewport and is also the block that contains the {{htmlelement("html")}} element. In other words, the absolutely positioned element will be displayed outside of the {{htmlelement("html")}} element and be positioned relative to the initial viewport.
The positioned element is nested inside the {{htmlelement("body")}} in the HTML source, but in the final layout it's 30px away from the top and the left edges of the page. We can change the **positioning context**, that is, which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors: to one of the elements it's nested inside of (you can't position it relative to an element it's not nested inside of). To see this, add the following declaration to your `body` rule:
```css
position: relative;
```
This should give the following result:
```html hidden
<h1>Positioning context</h1>
<p>
I am a basic block level element. My adjacent block level elements sit on new
lines below me.
</p>
<p class="positioned">
Now I'm absolutely positioned relative to the
<code><body></code> element, not the <code><html></code> element!
</p>
<p>
We are separated by our margins. Because of margin collapsing, we are
separated by the width of one of our margins, not both.
</p>
<p>
inline elements <span>like this one</span> and <span>this one</span> sit on
the same line as one another, and adjacent text nodes, if there is space on
the same line. Overflowing inline elements
<span>wrap onto a new line if possible β like this one containing text</span>,
or just go on to a new line if not, much like this image will do:
<img src="long.jpg" alt="snippet of cloth" />
</p>
```
```css hidden
body {
width: 500px;
margin: 0 auto;
position: relative;
}
p {
background: aqua;
border: 3px solid blue;
padding: 10px;
margin: 10px;
}
span {
background: red;
border: 1px solid black;
}
.positioned {
position: absolute;
background: yellow;
top: 30px;
left: 30px;
}
```
{{ EmbedLiveSample('Positioning_contexts', '100%', 420) }}
The positioned element now sits relative to the {{htmlelement("body")}} element.
> **Note:** You can see the example at this point live at [`4_positioning-context.html`](https://mdn.github.io/learning-area/css/css-layout/positioning/4_positioning-context.html) ([see source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/positioning/4_positioning-context.html)).
### Introducing z-index
All this absolute positioning is good fun, but there's another feature we haven't considered yet. When elements start to overlap, what determines which elements appear over others and which elements appear under others? In the example we've seen so far, we only have one positioned element in the positioning context, and it appears on the top since positioned elements win over non-positioned elements. What about when we have more than one?
Try adding the following to your CSS to make the first paragraph absolutely positioned too:
```css
p:nth-of-type(1) {
position: absolute;
background: lime;
top: 10px;
right: 30px;
}
```
At this point you'll see the first paragraph colored lime, moved out of the document flow, and positioned a bit above from where it originally was. It's also stacked below the original `.positioned` paragraph where the two overlap. This is because the `.positioned` paragraph is the second paragraph in the source order, and positioned elements later in the source order win over positioned elements earlier in the source order.
Can you change the stacking order? Yes, you can, by using the {{cssxref("z-index")}} property. "z-index" is a reference to the z-axis. You may recall from previous points in the course where we discussed web pages using horizontal (x-axis) and vertical (y-axis) coordinates to work out positioning for things like background images and drop shadow offsets. For languages that run left to right, (0,0) is at the top left of the page (or element), and the x- and y-axes run across to the right and down the page.
Web pages also have a z-axis: an imaginary line that runs from the surface of your screen towards your face (or whatever else you like to have in front of the screen). {{cssxref("z-index")}} values affect where positioned elements sit on that axis; positive values move them higher up the stack, negative values move them lower down the stack. By default, positioned elements all have a `z-index` of `auto`, which is effectively 0.
To change the stacking order, try adding the following declaration to your `p:nth-of-type(1)` rule:
```css
z-index: 1;
```
You should now see the lime paragraph on top:
```html hidden
<h1>z-index</h1>
<p>
I am a basic block level element. My adjacent block level elements sit on new
lines below me.
</p>
<p class="positioned">
Now I'm absolutely positioned relative to the
<code><body></code> element, not the <code><html></code> element!
</p>
<p>
We are separated by our margins. Because of margin collapsing, we are
separated by the width of one of our margins, not both.
</p>
<p>
inline elements <span>like this one</span> and <span>this one</span> sit on
the same line as one another, and adjacent text nodes, if there is space on
the same line. Overflowing inline elements
<span>wrap onto a new line if possible β like this one containing text</span>,
or just go on to a new line if not, much like this image will do:
<img src="long.jpg" alt="snippet of cloth" />
</p>
```
```css hidden
body {
width: 500px;
margin: 0 auto;
position: relative;
}
p {
background: aqua;
border: 3px solid blue;
padding: 10px;
margin: 10px;
}
span {
background: red;
border: 1px solid black;
}
.positioned {
position: absolute;
background: yellow;
top: 30px;
left: 30px;
}
p:nth-of-type(1) {
position: absolute;
background: lime;
top: 10px;
right: 30px;
z-index: 1;
}
```
{{ EmbedLiveSample('Introducing_z-index', '100%', 400) }}
Note that `z-index` only accepts unitless index values; you can't specify that you want one element to be 23 pixels up the Z-axis β it doesn't work like that. Higher values will go above lower values and it's up to you what values you use. Using values of 2 or 3 would give the same effect as values of 300 or 40000.
> **Note:** You can see an example for this live at [`5_z-index.html`](https://mdn.github.io/learning-area/css/css-layout/positioning/5_z-index.html) ([see source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/positioning/5_z-index.html)).
## Fixed positioning
Let's now look at fixed positioning. This works in exactly the same way as absolute positioning, with one key difference: whereas absolute positioning fixes an element in place relative to its nearest positioned ancestor (the initial containing block if there isn't one), **fixed positioning** _usually_ fixes an element in place relative to the visible portion of the viewport. (An exception to this occurs if one of the element's ancestors is a fixed containing block because its [transform property](/en-US/docs/Web/CSS/transform) has a value other than _none_.) This means that you can create useful UI items that are fixed in place, like persistent navigation menus that are always visible no matter how much the page scrolls.
Let's put together a simple example to show what we mean. First of all, delete the existing `p:nth-of-type(1)` and `.positioned` rules from your CSS.
Now update the `body` rule to remove the `position: relative;` declaration and add a fixed height, like so:
```css
body {
width: 500px;
height: 1400px;
margin: 0 auto;
}
```
Now we're going to give the {{htmlelement("Heading_Elements", "h1")}} element `position: fixed;` and have it sit at the top of the viewport. Add the following rule to your CSS:
```css
h1 {
position: fixed;
top: 0;
width: 500px;
margin-top: 0;
background: white;
padding: 10px;
}
```
The `top: 0;` is required to make it stick to the top of the screen. We give the heading the same width as the content column and then a white background and some padding and margin so the content won't be visible underneath it.
If you save and refresh, you'll see a fun little effect of the heading staying fixed β the content appears to scroll up and disappear underneath it. But notice how some of the content is initially clipped under the heading. This is because the positioned heading no longer appears in the document flow, so the rest of the content moves up to the top. We could improve this by moving the paragraphs all down a bit. We can do this by setting some top margin on the first paragraph. Add this now:
```css
p:nth-of-type(1) {
margin-top: 60px;
}
```
You should now see the finished example:
```html hidden
<h1>Fixed positioning</h1>
<p>
I am a basic block level element. My adjacent block level elements sit on new
lines below me.
</p>
<p class="positioned">I'm not positioned any more.</p>
<p>
We are separated by our margins. Because of margin collapsing, we are
separated by the width of one of our margins, not both.
</p>
<p>
Inline elements <span>like this one</span> and <span>this one</span> sit on
the same line as one another, and adjacent text nodes, if there is space on
the same line. Overflowing inline elements
<span>wrap onto a new line if possible β like this one containing text</span>,
or just go on to a new line if not, much like this image will do:
<img src="long.jpg" alt="snippet of cloth" />
</p>
```
```css hidden
body {
width: 500px;
height: 1400px;
margin: 0 auto;
}
p {
background: aqua;
border: 3px solid blue;
padding: 10px;
margin: 10px;
}
span {
background: red;
border: 1px solid black;
}
h1 {
position: fixed;
top: 0px;
width: 500px;
background: white;
padding: 10px;
}
p:nth-of-type(1) {
margin-top: 60px;
}
```
{{ EmbedLiveSample('Fixed_positioning', '100%', 400) }}
> **Note:** You can see an example for this live at [`6_fixed-positioning.html`](https://mdn.github.io/learning-area/css/css-layout/positioning/6_fixed-positioning.html) ([see source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/positioning/6_fixed-positioning.html)).
## Sticky positioning
There is another position value available called `position: sticky`, which is somewhat newer than the others. This is basically a hybrid between relative and fixed position. It allows a positioned element to act like it's relatively positioned until it's scrolled to a certain threshold (e.g., 10px from the top of the viewport), after which it becomes fixed.
### Basic example
Sticky positioning can be used, for example, to cause a navigation bar to scroll with the page until a certain point and then stick to the top of the page.
```html hidden
<h1>Sticky positioning</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam
dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus
ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus
laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum,
tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus
neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat
volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros
pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec
lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<div class="positioned">Sticky</div>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus
sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam
dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus
ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus
laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum,
tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus
neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat
volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros
pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec
lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.
</p>
```
```css hidden
body {
width: 500px;
margin: 0 auto;
}
.positioned {
background: rgb(255 84 104 / 30%);
border: 2px solid rgb(255 84 104);
padding: 10px;
margin: 10px;
border-radius: 5px;
}
```
```css
.positioned {
position: sticky;
top: 30px;
left: 30px;
}
```
{{ EmbedLiveSample('Basic_example', '100%', 200) }}
### Scrolling index
An interesting and common use of `position: sticky` is to create a scrolling index page where different headings stick to the top of the page as they reach it. The markup for such an example might look like so:
```html
<h1>Sticky positioning</h1>
<dl>
<dt>A</dt>
<dd>Apple</dd>
<dd>Ant</dd>
<dd>Altimeter</dd>
<dd>Airplane</dd>
<dt>B</dt>
<dd>Bird</dd>
<dd>Buzzard</dd>
<dd>Bee</dd>
<dd>Banana</dd>
<dd>Beanstalk</dd>
<dt>C</dt>
<dd>Calculator</dd>
<dd>Cane</dd>
<dd>Camera</dd>
<dd>Camel</dd>
<dt>D</dt>
<dd>Duck</dd>
<dd>Dime</dd>
<dd>Dipstick</dd>
<dd>Drone</dd>
<dt>E</dt>
<dd>Egg</dd>
<dd>Elephant</dd>
<dd>Egret</dd>
</dl>
```
The CSS might look as follows. In normal flow the {{htmlelement("dt")}} elements will scroll with the content. When we add `position: sticky` to the {{htmlelement("dt")}} element, along with a {{cssxref("top")}} value of 0, supporting browsers will stick the headings to the top of the viewport as they reach that position. Each subsequent header will then replace the previous one as it scrolls up to that position.
```css
dt {
background-color: black;
color: white;
padding: 10px;
position: sticky;
top: 0;
left: 0;
margin: 1em 0;
}
```
```css hidden
body {
width: 500px;
height: 1400px;
margin: 0 auto;
}
```
```html hidden
<h1>Sticky positioning</h1>
<dl>
<dt>A</dt>
<dd>Apple</dd>
<dd>Ant</dd>
<dd>Altimeter</dd>
<dd>Airplane</dd>
<dt>B</dt>
<dd>Bird</dd>
<dd>Buzzard</dd>
<dd>Bee</dd>
<dd>Banana</dd>
<dd>Beanstalk</dd>
<dt>C</dt>
<dd>Calculator</dd>
<dd>Cane</dd>
<dd>Camera</dd>
<dd>Camel</dd>
<dt>D</dt>
<dd>Duck</dd>
<dd>Dime</dd>
<dd>Dipstick</dd>
<dd>Drone</dd>
<dt>E</dt>
<dd>Egg</dd>
<dd>Elephant</dd>
<dd>Egret</dd>
</dl>
```
{{ EmbedLiveSample('Scrolling_index', '100%', 200) }}
Sticky elements are "sticky" relative to the nearest ancestor with a "scrolling mechanism", which is determined by its ancestors' [position](/en-US/docs/Web/CSS/position) property.
> **Note:** You can see this example live at [`7_sticky-positioning.html`](https://mdn.github.io/learning-area/css/css-layout/positioning/7_sticky-positioning.html) ([see source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/positioning/7_sticky-positioning.html)).
## 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: Positioning](/en-US/docs/Learn/CSS/CSS_layout/Position_skills).
## Summary
I'm sure you had fun playing with basic positioning. While it's not an ideal method to use for entire layouts, there are many specific objectives it's suited for.
## See also
- The {{cssxref("position")}} property reference.
- [Practical positioning examples](/en-US/docs/Learn/CSS/CSS_layout/Practical_positioning_examples), for some more useful ideas.
{{PreviousMenuNext("Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout/Multiple-column_Layout", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/floats_skills/index.md | ---
title: "Test your skills: Floats"
slug: Learn/CSS/CSS_layout/Floats_skills
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand [floats in CSS](/en-US/docs/Learn/CSS/CSS_layout/Floats) using the {{CSSxRef("float")}} and {{CSSxRef("clear")}} properties and values as well as other methods for clearing floats. You will be working through three small tasks that use different elements of the material you have just covered.
> **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 need to float the two elements with a class of `float1` and `float2` left and right, respectively. The text should then appear between the two boxes, as in the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/float/float1.html", '100%', 900)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/float/float1-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, the element with a class of `float` should be floated left. Then we want the first line of text to display next to that element, but the following line of text (which has a class of `below`) to display underneath it.
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/float/float2.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/float/float2-download.html) to work in your own editor or in an online editor.
## Task 3
In this task, we have a floated element. The box wrapping the float and text is displaying behind the float. Use the most up-to-date method available to cause the box background to extend to below the float, as in the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/float/float3.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/float/float3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/grid_skills/index.md | ---
title: "Test your skills: Grid"
slug: Learn/CSS/CSS_layout/Grid_skills
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand how a [grid and grid items](/en-US/docs/Learn/CSS/CSS_layout/Grids) behave. You will be working through several small tasks that use different elements of the material you have just covered.
> **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 should create a grid into which the four child elements will auto-place. The grid should have three columns sharing the available space equally and a 20-pixel gap between the column and row tracks. After that, try adding more child containers inside the parent container with the class of `grid` and see how they behave by default.
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/grid/grid1.html", '100%', 700)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/grid/grid1-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, we already have a grid defined. By editing the CSS rules for the two child elements, cause them to span over several grid tracks each. The second item should overlay the first as in the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/grid/grid2.html", '100%', 900)}}
Additional question:
- Can you now cause the first item to display on top without changing the order of items in the source?
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/grid/grid2-download.html) to work in your own editor or in an online editor.
## Task 3
In this task, there are four direct children in this grid. The starting point has them displayed using auto-placement. Use the grid-area and grid-template-areas properties to lay the items out as shown in the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/grid/grid3.html", '100%', 800)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/grid/grid3-download.html) to work in your own editor or in an online editor.
## Task 4
In this task, you will need to use both grid layout and flexbox to recreate the example as seen in the image below. The gap between the column and row tracks should be 10px. You do not need to make any changes to the HTML in order to achieve this.

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/grid/grid4.html", '100%', 2000)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/grid/grid4-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/supporting_older_browsers/index.md | ---
title: Supporting older browsers
slug: Learn/CSS/CSS_layout/Supporting_Older_Browsers
page-type: learn-module-chapter
browser-compat: css.properties.grid-template-columns
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/CSS/CSS_layout/Legacy_Layout_methods", "Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension", "Learn/CSS/CSS_layout")}}
Visitors to your website may include users who either use older browsers or use browsers that do not support the CSS features you've implemented. This is a common scenario on the web, where new features are continuously being added to CSS. Browsers differ in their support for these features because different browsers tend to prioritize implementing different features. This article explains how you as a web developer can use modern web techniques to ensure that your website remains accessible to users with older technology.
<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">Introduction to CSS</a> and
<a href="/en-US/docs/Learn/CSS/Building_blocks">Styling boxes</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand how to provide support for your layouts on older browsers
that might not support the features you want to use.
</td>
</tr>
</tbody>
</table>
## What is the browser landscape for your site?
Every website is different in terms of its target audience. Before deciding on an approach, find out the number of visitors coming to your site using older browsers. This is straightforward if you're adding to or replacing an existing website, as you probably have analytics available that can tell you the technology your visitors are using. If you don't have analytics or you're launching a brand new site, then sites such as [Statcounter](https://gs.statcounter.com/) can provide relevant statistics, which can be filtered by location.
You should also consider the type of devices and the way people use your site. For example, you can expect a higher-than-average usage of your website on mobile devices. Always prioritize accessibility and people using assistive technology; for some sites, this may be even more critical. Developers are often very worried about the experience of 1% of users, while overlooking the far greater number who have accessibility needs.
## What is the support for the features you want to use?
{{Compat}}
The above table is included at the bottom of every feature page under the section "Browser compatibility". After identifying the browsers your site visitors use, you can assess any technology that you want to use against how well it is supported across browsers and how easily you can provide an alternative for visitors who do not have that technology available.
On MDN, we provide browser compatibility information on every CSS property page. This compatibility information, presented in a table, includes a list of major browsers along with the versions that started supporting the property. The browser names take up the column headers. For example, take a look at the above table or the page for {{cssxref("grid-template-columns")}}, with special attention to the `subgrid` (most recently supported) and `masonry` (experimental and not supported) values.
These browser compatibility tables provide information on which browsers are compatible with the technology that you are looking for and the version from which the browser started supporting that functionality. Browser and mobile phone browser compatibility information are displayed separately.
Another popular way to find out about how well a feature is supported is the [Can I Use](https://caniuse.com/) website. This site lists the majority of Web Platform features with information about their browser support status. You can view usage statistics by location β useful if you work on a site that has users mostly for a specific area of the world. You can even link your Google Analytics account to get analysis based on your user data.
Understanding the technology your users have because of the browser they're using and the cross-browser support for features that you might want to use on your website, puts you in a good place to make all of your decisions and to know how best to support all of your users.
## Feature support does not mean identical appearance
A website can't possibly look the same in all browsers. Some of your users will be viewing the site on a phone and others on a large desktop screen. Similarly, some of your users will have an old browser version, and others the latest browser. Some of your users might be hearing your content read out to them by a screen reader, while others might need to zoom in on the page to be able to read it. Supporting everyone means serving a version of your content that is designed defensively, so that it will look great on modern browsers, but will still be usable at a basic level for all users no matter how they are accessing your content.
A basic level of support comes from structuring your content well so that the normal flow of your page makes sense. For users on a limited data plan, their browsers might not load images, fonts, or even your CSS. However, the content should be presented in a way such that it is accessible and readable even when these elements are not fully loaded. A well-structured HTML document should always be your starting point. Ask yourself: _if you remove your stylesheet, does your content still make sense?_
It doesn't make commercial sense to spend time trying to give everyone an identical experience of your website. This is because user environments can vary widely and are beyond your control. There is a balance you need to strike between a plain HTML page and a fully featured website. It is helpful to test a plain, CSS-less view of your site to ensure that the fallback experience of your site is accessible. This fallback may never be viewed by people using very old or limited browsers, but may be viewed by your main target audience β users of modern browsers β when their browser or Internet connection fails temporarily. CSS simplifies creating these fallbacks. Therefore, it is better to focus on what you can control, that is, spend the time to make your site [accessible](/en-US/docs/Web/Accessibility), thereby serving more users.
## Creating fallbacks in CSS
CSS specifications contain information that explain what the browser does when two similar features, such as layout methods, are applied to the same item. For example, they define what happens if an item is floated and is also a grid item and part of a CSS grid container. There is also a definition for what happens when an element has both {{cssxref("margin-top")}} and {{cssxref("margin-block-start")}} properties set.
When a browser doesn't recognize a new feature, it discards the declaration as invalid [without throwing an error](/en-US/docs/Web/CSS/CSS_syntax/Error_handling#css_parser_errors). Because browsers discard CSS properties and values they don't support, both old and new values can coexist in the same ruleset. Just make sure to declare the old value before the new value so that, when supported, the new value overwrites the old value (the fallback).
For example, most browsers support the two-value syntax of the {{cssxref("display")}} property. If a browser doesn't, it will use the older, single-value syntax.
```css
.container {
display: inline-flex;
display: inline flex;
}
```
Similarly, this [error-handling](/en-US/docs/Web/CSS/CSS_syntax/Error_handling#vendor_prefixes) ensures old CSS code bases continue to work even if legacy {{glossary("Vendor_Prefix", "vendor-prefixed")}} features are no longer supported. While vendor prefixing is no longer commonly used, if you must include a vendor-prefixed property or value, make sure to declare the prefixed value before the standard value so that, when supported, the new value overwrites the fallback value.
### Using new selectors
Including new selectors that aren't supported in all browsers needs to be handled more carefully. If a selector in a comma-separated list of [selectors is invalid](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS#selector_support), the entire style block is ignored.
If using vendor-prefixed [pseudo-elements](/en-US/docs/Web/CSS/Pseudo-elements) or new[pseudo-classes](/en-US/docs/Web/CSS/Pseudo-classes) a browser may not yet support, include the prefixed values within a [forgiving selector list](/en-US/docs/Web/CSS/Selector_list#forgiving_selector_list) by using {{cssxref(":is", ":is()")}} or {{cssxref(":where", ":where()")}} so the entire selector block doesn't get [invalidated and ignored](/en-US/docs/Web/CSS/Selector_list#invalid_selector_list).
```css
:is(:-prefix-mistake, :unsupported-pseudo),
.valid {
font-family: sans-serif;
}
:-prefix-mistake,
:unsupported-pseudo,
.valid {
color: red;
}
```
In the above example, the `.valid` content will be `sans-serif` but not `red`.
## Feature queries
Feature queries allow you to test whether a browser supports a particular CSS feature. This means that you can write some CSS for browsers that don't support a certain feature, then check to see if the browser has support and if so, throw in your fancy new features.
We can add a feature query to test for `subgrid` support, and provide styles based on that support:
```css
* {
box-sizing: border-box;
}
.wrapper {
background-color: palegoldenrod;
padding: 10px;
max-width: 400px;
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.item {
border-radius: 5px;
background-color: rgb(207 232 220);
}
@supports (grid-template-rows: subgrid) {
.wrapper {
grid-template-rows: subgrid;
gap: 10px;
background-color: lightblue;
text-align: center;
}
}
```
```html
<div class="wrapper">
<div class="item">Item One</div>
<div class="item">Item Two</div>
<div class="item">Item Three</div>
<div class="item">Item Four</div>
<div class="item">Item Five</div>
<div class="item">Item Six</div>
</div>
```
{{ EmbedLiveSample('Feature_queries', '100%', '200') }}
Feature queries are supported in all modern browsers. Write your CSS for fully supported features first, outside of any feature queries. Once your site is usable and accessible to all users, add new features within feature query blocks. Browsers that support the feature queried can then render the newer CSS inside the feature query block. Use the approach of writing well-supported CSS first, then enhancing features based on support.
## Testing older browsers
One way is to use an online testing tool such as Sauce Labs, as detailed in the [Cross browser testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing) module.
## Summary
You now have the knowledge to provide fallback CSS for older browsers and confidently test for new features. You should now feel confident making use of any new techniques that might come along.
Now that you have worked through our articles on CSS layout, it's time to test your comprehension with our assessment for the module: [Fundamental layout comprehension](/en-US/docs/Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension).
## See also
- [`@supports`](/en-US/docs/Web/CSS/@supports) at-rule
- [CSS at-rules](/en-US/docs/Web/CSS/At-rule)
- [Using feature queries](/en-US/docs/Web/CSS/CSS_conditional_rules/Using_feature_queries)
- [CSS conditional rules](/en-US/docs/Web/CSS/CSS_conditional_rules) module
{{PreviousMenuNext("Learn/CSS/CSS_layout/Legacy_Layout_methods", "Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/fundamental_layout_comprehension/index.md | ---
title: Fundamental layout comprehension
slug: Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension
page-type: learn-module-assessment
---
{{LearnSidebar}}
{{PreviousMenu("Learn/CSS/CSS_layout/Supporting_Older_Browsers", "Learn/CSS/CSS_layout")}}
If you have worked through this module then you will have already covered the basics of what you need to know to do CSS layout today, and to work with older CSS as well. This task will test some of your knowledge by the way of developing a simple webpage layout using a variety of techniques.
<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 layout methods using Flexbox, Grid, Floating and Positioning.
</td>
</tr>
</tbody>
</table>
## Starting point
You can download the HTML, CSS, and a set of six images [here](https://github.com/mdn/learning-area/tree/main/css/css-layout/fundamental-layout-comprehension).
Save the HTML document and stylesheet into a directory on your computer, and add the images into a folder named `images`. Opening the `index.html` file in a browser should give you a page with basic styling but no layout, which should look something like the image below.

This starting point has all of the content of your layout as displayed by the browser in normal flow.
Alternatively, you could use an online editor such as [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Glitch](https://glitch.com/).
If you use an online editor, you will need to upload the images and replace the values in the `src` attributes to point to the new image locations.
> **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, basic CSS, and images β now you need to create a layout for the design.
### Your tasks
You now need to implement your layout. The tasks you need to achieve are:
1. To display the navigation items in a row, with an equal amount of space between the items.
2. The navigation bar should scroll with the content and then become stuck at the top of the viewport when it reaches it.
3. The image that is inside the article should have text wrapped around it.
4. The {{htmlelement("article")}} and {{htmlelement("aside")}} elements should display as a two column layout. The columns should be a flexible size so that if the browser window shrinks smaller the columns become narrower.
5. The photographs should display as a two column grid with a 1 pixel gap between the images.
## Hints and tips
You will not need to edit the HTML in order to achieve this layout and the techniques you should use are:
- Flexbox
- Grid
- Floating
- Positioning
There are a few ways in which you could achieve some of these tasks, and there often isn't a single right or wrong way to do things. Try a few different approaches and see which works best. Make notes as you experiment.
## Example
The following screenshot shows an example of what the finished layout for the design should look like:

{{PreviousMenu("Learn/CSS/CSS_layout/Supporting_Older_Browsers", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/practical_positioning_examples/index.md | ---
title: Practical positioning examples
slug: Learn/CSS/CSS_layout/Practical_positioning_examples
page-type: guide
---
{{LearnSidebar}}
This article shows how to build some real-world examples to illustrate what kinds of things you can do with positioning.
<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">Introduction to CSS</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To get an idea of the practicalities of positioning</td>
</tr>
</tbody>
</table>
## A tabbed info-box
The first example we'll look at is a classic tabbed info box β a very common feature used when you want to pack a lot of information into a small area. This includes information-heavy apps like strategy/war games, mobile versions of websites where the screen is narrow and space is limited, and compact information boxes where you might want to make lots of information available without having it fill the whole UI. Our simple example will look like this once we are finished:

> **Note:** You can see the finished example running live at [info-box.html](https://mdn.github.io/learning-area/css/css-layout/practical-positioning-examples/info-box.html) ([source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/practical-positioning-examples/info-box.html)). Check it out to get an idea of what you will be building in this section of the article.
You might be thinking "why not just create the separate tabs as separate webpages, and just have the tabs clicking through to the separate pages to create the effect?" This code would be simpler, yes, but then each separate "page" view would actually be a newly-loaded webpage, which would make it harder to save information across views, and integrate this feature into a larger UI design.
To start with, we'd like you to make a local copy of the starting HTML file β [info-box-start.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/practical-positioning-examples/info-box-start.html). Save this somewhere sensible on your local computer, and open it up in your text editor. Let's look at the HTML contained within the body:
```html
<section class="info-box">
<ul>
<li><a href="#" class="active-tab">Tab 1</a></li>
<li><a href="#">Tab 2</a></li>
<li><a href="#">Tab 3</a></li>
</ul>
<div class="panels">
<article class="active-panel">
<h2>The first tab</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque
turpis nibh, porttitor nec venenatis eu, pulvinar in augue. Vestibulum
et orci scelerisque, vulputate tellus quis, lobortis dui. Vivamus varius
libero at ipsum mattis efficitur ut nec nisl. Nullam eget tincidunt
metus. Donec ultrices, urna maximus consequat aliquet, dui neque
eleifend lorem, a auctor libero turpis at sem. Aliquam ut porttitor
urna. Nulla facilisi.
</p>
</article>
<article>
<h2>The second tab</h2>
<p>
This tab hasn't got any Lorem Ipsum in it. But the content isn't very
exciting all the same.
</p>
</article>
<article>
<h2>The third tab</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque
turpis nibh, porttitor nec venenatis eu, pulvinar in augue. And now an
ordered list: how exciting!
</p>
<ol>
<li>dui neque eleifend lorem, a auctor libero turpis at sem.</li>
<li>Aliquam ut porttitor urna.</li>
<li>Nulla facilisi</li>
</ol>
</article>
</div>
</section>
```
So here we've got a {{htmlelement("section")}} element with a `class` of `info-box`, which contains a {{htmlelement("ul")}} and a {{htmlelement("div")}}. The unordered list contains three list items with links inside, which will become the actual tabs to click on for displaying our content panels. The `div` contains three {{htmlelement("article")}} elements, which will make up the content panels that correspond to each tab. Each panel contains some sample content.
The idea here is that we will style the tabs to look like a standard horizontal navigation menu, and style the panels to sit on top of one another using absolute positioning. We'll also give you a bit of JavaScript to include on your page to display the corresponding panel when a tab is pressed, and style the tab itself. You won't need to understand the JavaScript itself at this stage, but you should think about learning some basic [JavaScript](/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics) as soon as possible β the more complex your UI features become, the more likely it is that you'll need some JavaScript to implement your desired functionality.
### General setup
To begin with, add the following between your opening and closing {{HTMLElement("style")}} tags:
```css
html {
font-family: sans-serif;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
}
```
This is just some general setup to set a sans-serif font on our page, use the `border-box` {{cssxref("box-sizing")}} model, and get rid of the default {{htmlelement("body")}} margin.
Next, add the following just below your previous CSS:
```css
.info-box {
width: 450px;
height: 400px;
margin: 0 auto;
}
```
This sets a specific width and height on the content, and centers it on the screen using the old `margin: 0 auto` trick. Previously in the course we advised against setting a fixed height on content containers if at all possible; it is OK in this circumstance because we have fixed content in our tabs. It also looks a bit jarring to have different tabs at different heights.
### Styling our tabs
Now we want to style tabs to look like tabs β basically, these are a horizontal navigation menu, but instead of loading different web pages when they are clicked on like we've seen previously in the course, they cause different panels to be displayed on the same page. First, add the following rule at the bottom of your CSS to remove the default {{cssxref("padding-left")}} and {{cssxref("margin-top")}} from the unordered list:
```css
.info-box ul {
padding-left: 0;
margin-top: 0;
}
```
> **Note:** We are using descendant selectors with `.info-box` at the start of the chain throughout this example β this is so that we can insert this feature into a page with other content already on it, without fear of interfering with the styles applied to other parts of the page.
Next, we'll style the horizontal tabs β the list items are all floated left to make them sit in a line together, their {{cssxref("list-style-type")}} is set to `none` to get rid of the bullets, and their {{cssxref("width")}} is set to `150px` so they will comfortably fit across the info-box. The {{htmlelement("a")}} elements are set to {{cssxref("display")}} inline-block so they will sit in a line but still be stylable, and they are styled appropriately for tab buttons, using a variety of other properties.
Add the following CSS:
```css
.info-box li {
float: left;
list-style-type: none;
width: 150px;
}
.info-box li a {
display: inline-block;
text-decoration: none;
width: 100%;
line-height: 3;
background-color: red;
color: black;
text-align: center;
}
```
Finally for this section we'll set some styles on the link states. First, we'll set the `:focus` and `:hover` states of the tabs to look different when they are focused/hovered, providing users with some visual feedback. Secondly, we'll set a rule that puts the same styling on one of the tabs when a `class` of `active-tab` is present on it. We will set this using JavaScript when a tab is clicked on. Place the following CSS below your other styles:
```css
.info-box li a:focus,
.info-box li a:hover {
background-color: #a60000;
color: white;
}
.info-box li a.active-tab {
background-color: #a60000;
color: white;
}
```
### Styling the panels
The next job is to style our panels. Let's get going!
First, of all, add the following rule to style the `.panels` {{htmlelement("div")}} container. Here we set a fixed {{cssxref("height")}} to make sure the panels fit snugly inside the info-box, {{cssxref("position")}} `relative` to set the {{htmlelement("div")}} as the positioning context, so you can then place positioned child elements relative to it and not the initial viewport, and finally we {{cssxref("clear")}} the float set in the CSS above so that it doesn't interfere with the remainder of the layout.
```css
.info-box .panels {
height: 352px;
position: relative;
clear: both;
}
```
Finally for this section, we will style the individual {{htmlelement("article")}} elements that comprise our panels. The first rule we'll add will absolutely {{cssxref("position")}} the panels, and make them all sit flush to the {{cssxref("top")}} and {{cssxref("left")}} of their {{htmlelement("div")}} container β this part is absolutely key to this whole layout feature, as it makes the panels sit on top of one another. The rule also gives the panels the same set height as the container, and gives the content some padding, a text {{cssxref("color")}}, and a {{cssxref("background-color")}}.
The second rule we'll add here makes it so that a panel with a `class` of `active-panel` set on it will have a {{cssxref("z-index")}} of 1 applied to it, which will make it sit above the other panels (positioned elements have a `z-index` of 0 by default, which would put them below). Again, we'll add this class using JavaScript at the appropriate time.
```css
.info-box article {
position: absolute;
top: 0;
left: 0;
height: 352px;
padding: 10px;
color: white;
background-color: #a60000;
}
.info-box .active-panel {
z-index: 1;
}
```
### Adding our JavaScript
The final step to getting this feature working is to add some JavaScript. Put the following block of code, exactly as written in between your opening and closing {{htmlelement("script")}} tags (you'll find these below the HTML content):
```js
const tabs = document.querySelectorAll(".info-box li a");
const panels = document.querySelectorAll(".info-box article");
for (let i = 0; i < tabs.length; i++) {
setTabHandler(tabs[i], i);
}
function setTabHandler(tab, tabPos) {
tab.onclick = () => {
for (const tab of tabs) {
tab.className = "";
}
tab.className = "active-tab";
for (const panel of panels) {
panel.className = "";
}
panels[tabPos].className = "active-panel";
};
}
```
This code does the following:
- First we save a reference to all the tabs and all the panels in two variables called `tabs` and `panels`, so we can easily do things to them later on.
- Then we use a `for` loop to cycle through all the tabs and run a function called `setTabHandler()` on each one, which sets up the functionality that should occur when each one is clicked on. When run, the function is passed a reference to the particular tab it is being run for, and an index number `i` that identifies the tab's position in the `tabs` array.
- In the `setTabHandler()` function, the tab has an `onclick` event handler set on it, so that when the tab is clicked, the following occurs:
- A `for` loop is used to cycle through all the tabs and remove any classes that are present on them.
- A `class` of `active-tab` is set on the tab that was clicked on β remember from earlier that this class has an associated rule in the CSS that sets the same {{cssxref("color")}} and {{cssxref("background-color")}} on the tab as the panels are styled with.
- A `for` loop is used to cycle through all the panels and remove any classes that are present on them.
- A class of `active-panel` is set on the panel that corresponds to the tab that was clicked on β remember from earlier that this class has an associated rule in the CSS that sets its {{cssxref("z-index")}} to 1, making it appear over the top of the other panels.
That's it for the first example. Keep your code open, as we'll be adding to it in the second one.
## A fixed position tabbed info-box
In our second example, we will take our first example β our info-box β and add it into the context of a full web page. But not only that β we'll give it fixed position so that it stays in the same position in the browser window. When the main content scrolls, the info-box will stay in the same position on the screen. Our finished example will look like this:

> **Note:** You can see the finished example running live at [fixed-info-box.html](https://mdn.github.io/learning-area/css/css-layout/practical-positioning-examples/fixed-info-box.html) ([source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/practical-positioning-examples/fixed-info-box.html)). Check it out to get an idea of what you will be building in this section of the article.
As a starting point, you can use your completed example from the first section of the article, or make a local copy of [info-box.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/practical-positioning-examples/info-box.html) from our GitHub repo.
### HTML additions
First of all, we need some additional HTML to represent the website main content. Add the following {{htmlelement("section")}} just below your opening {{htmlelement("body")}} tag, just before the existing section:
```html
<section class="fake-content">
<h1>Fake content</h1>
<p>
This is fake content. Your main web page contents would probably go here.
</p>
<p>
This is fake content. Your main web page contents would probably go here.
</p>
<p>
This is fake content. Your main web page contents would probably go here.
</p>
<p>
This is fake content. Your main web page contents would probably go here.
</p>
<p>
This is fake content. Your main web page contents would probably go here.
</p>
<p>
This is fake content. Your main web page contents would probably go here.
</p>
<p>
This is fake content. Your main web page contents would probably go here.
</p>
<p>
This is fake content. Your main web page contents would probably go here.
</p>
</section>
```
> **Note:** You can feel free to change the fake content for some real content if you like.
### Changes to the existing CSS
Next we need to make some small changes to the existing CSS, to get the info-box placed and positioned. Change your `.info-box` rule to get rid of `margin: 0 auto;` (we no longer want the info-box centered), add {{cssxref("position")}}`: fixed;`, and stick it to the {{cssxref("top")}} of the browser viewport.
It should now look like this:
```css
.info-box {
width: 450px;
height: 400px;
position: fixed;
top: 0;
}
```
### Styling the main content
The only thing left for this example is to provide the main content with some styling. Add the following rule underneath the rest of your CSS:
```css
.fake-content {
background-color: #a60000;
color: white;
padding: 10px;
height: 2000px;
margin-left: 470px;
}
```
To start with, we give the content the same {{cssxref("background-color")}}, {{cssxref("color")}}, and {{cssxref("padding")}} as the info-box panels. We then give it a large {{cssxref("margin-left")}} to move it over to the right, making space for the info-box to sit in, so it is not overlapping anything else.
This marks the end of the second example; we hope you'll find the third just as interesting.
## A sliding hidden panel
The final example we'll present here is a panel that slides on and off the screen at the press of an icon β as mentioned earlier, this is popular for situations like mobile layouts, where the available screen spaces is small, so you don't want to use up most of it by showing a menu or info panel instead of the useful content.
Our finished example will look like this:

> **Note:** You can see the finished example running live at [hidden-info-panel.html](https://mdn.github.io/learning-area/css/css-layout/practical-positioning-examples/hidden-info-panel.html) ([source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/practical-positioning-examples/hidden-info-panel.html)). Check it out to get an idea of what you will be building in this section of the article.
As a starting point, make a local copy of [hidden-info-panel-start.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/practical-positioning-examples/hidden-info-panel-start.html) from our GitHub repo. This doesn't follow on from the previous example, so a fresh start file is required. Let's have a look at the HTML in the file:
```html-nolint
<label for="toggle">β</label>
<input type="checkbox" id="toggle" />
<aside>
β¦
</aside>
```
To start with here we've got a {{htmlelement("label")}} element and an {{htmlelement("input")}} element β `<label>` elements are normally used to associate a text label with a form element for accessibility purposes (allowing a screen user to see what description goes with what form element). Here it is associated with the `<input>` checkbox using the `for` and `id` attributes.
> **Note:** We've put a special question mark character into our HTML to act as our info icon β this represents the button that will be pressed to show/hide the panel.
Here we are going to use these elements for a slightly different purpose β another useful side effect of `<label>` elements is that you can click a checkbox's label to check the checkbox, as well as just the checkbox itself. This has led to the well-known [checkbox hack](https://css-tricks.com/the-checkbox-hack/), which provides a JavaScript-free way of controlling an element by toggling a button. The element we'll be controlling is the {{htmlelement("aside")}} element that follows the other two (we've left its contents out of the above code listing for brevity).
In the below sections we'll explain how this all works.
### Styling the form elements
First let's deal with the form elements β add the following CSS in between your {{htmlelement("style")}} tags:
```css
label[for="toggle"] {
font-size: 3rem;
position: absolute;
top: 4px;
right: 5px;
z-index: 1;
cursor: pointer;
}
input[type="checkbox"] {
position: absolute;
top: -100px;
}
```
The first rule styles the `<label>`; here we've:
- Set a large {{cssxref("font-size")}} to make the icon nice and big.
- Set {{cssxref("position")}} `absolute` on it, and used {{cssxref("top")}} and {{cssxref("right")}} to position it nicely in the top-right corner.
- Set a {{cssxref("z-index")}} of 1 on it β this is so that when the info panel is styled and shown, it doesn't cover up the icon; instead the icon will sit on top of it so it can be pressed again to hide the info pane.
- Used the {{cssxref("cursor")}} property to change the mouse cursor when it is hovering over the icon to a hand pointer (like the one you see when links are hovered over), as an extra visual clue to users that the icon does something interesting.
The second rule sets {{cssxref("position")}} `absolute` on the actual checkbox `<input>` element, and hides it off the top of the screen. We don't actually want to see this on our UI.
### Styling the panel
Now it's time to style the actual sliding panel itself. Add the following rule to the bottom of your CSS:
```css
aside {
background-color: #a60000;
color: white;
width: 340px;
height: 100%;
padding: 0 20px;
position: fixed;
top: 0;
right: -370px;
transition: 0.6s all;
}
```
There's a lot going on here β let's discuss it bit by bit:
- First, we set some simple {{cssxref("background-color")}} and {{cssxref("color")}} on the info box.
- Next, we set a fixed {{cssxref("width")}} on the panel, and make its {{cssxref("height")}} the entire height of the browser viewport.
- We also include some horizontal {{cssxref("padding")}} to space it out a bit.
- Next we set {{cssxref("position")}}`: fixed;` on the panel so it will always appear in the same place, even if the page has content to scroll. We glue it to the {{cssxref("top")}} of the viewport, and set it so that by default it is offscreen to the {{cssxref("right")}}.
- Finally, we set a {{cssxref("transition")}} on the element. Transitions are an interesting feature that allow you to make changes between states happen smoothly, rather than just going "on", "off" abruptly. In this case we are intending to make the panel slide smoothly onscreen when the checkbox is checked. (Or to put it another way, when the question mark icon is clicked β remember, clicking the `<label>` will check the associated checkbox! We told you it was a hack.) You will learn a lot more aboutβ¦
### Setting the checked state
There is one final bit of CSS to add β put the following at the bottom of your CSS:
```css
input[type="checkbox"]:checked + aside {
right: 0px;
}
```
The selector is pretty complex here β we are selecting the `<aside>` element adjacent to the `<input>` element, but only when it is checked (note the use of the {{cssxref(":checked")}} pseudo-class to achieve this). When this is the case, we are setting the {{cssxref("right")}} property of the `<aside>` to `0px`, which causes the panel to appear on the screen again (smoothly due to the transition). Clicking the label again unchecks the checkbox, which hides the panel again.
So there you have it β a rather clever JavaScript-free way to create a toggling button effect. This will work in IE9 and above (the smooth transition will work in IE10 and above.) This effect does have some concerns β this is a bit of an abuse of form elements, as they weren't intended for this purpose. In addition, the effect is not great in terms of accessibility; the label is not focusable by default, and the non-semantic use of the form elements could cause issues with screen readers. JavaScript and a link or button might be more appropriate, but it is still fun to experiment with.
## Summary
So that rounds off our look at positioning β by now, you should have an idea of how the basic mechanics work, as well as understanding how to start applying these to build some interesting UI features. Don't worry if you didn't get this all immediately β positioning is a fairly advanced topic, and you can always work through the articles again to aid your understanding.
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/media_queries/index.md | ---
title: Beginner's guide to media queries
slug: Learn/CSS/CSS_layout/Media_queries
page-type: learn-module-chapter
---
{{learnsidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Responsive_Design", "Learn/CSS/CSS_layout/Legacy_Layout_Methods", "Learn/CSS/CSS_layout")}}
The **CSS Media Query** gives you a way to apply CSS only when the browser and device environment matches a rule that you specify, for example "viewport is wider than 480 pixels". Media queries are a key part of responsive web design, as they allow you to create different layouts depending on the size of the viewport, but they can also be used to detect other things about the environment your site is running on, for example whether the user is using a touchscreen rather than a mouse. In this lesson you will first learn about the syntax used in media queries, and then move on to use them in a working example showing how a simple design might be made responsive.
<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> and
<a href="/en-US/docs/Learn/CSS/Building_blocks">CSS building blocks</a
>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand how to use media queries, and the most common approach for
using them to create responsive designs.
</td>
</tr>
</tbody>
</table>
## Media Query Basics
The simplest media query syntax looks like this:
```css
@media media-type and (media-feature-rule) {
/* CSS rules go here */
}
```
It consists of:
- A media type, which tells the browser what kind of media this code is for (e.g. print, or screen).
- A media expression, which is a rule, or test that must be passed for the contained CSS to be applied.
- A set of CSS rules that will be applied if the test passes and the media type is correct.
### Media types
The possible types of media you can specify are:
- `all`
- `print`
- `screen`
The following media query will only set the body to 12pt if the page is printed. It will not apply when the page is loaded in a browser.
```css
@media print {
body {
font-size: 12pt;
}
}
```
> **Note:** The media type here is different from the so-called {{glossary("MIME type")}}.
> **Note:** There were a number of other media types defined in the Level 3 Media Queries specification; these have been deprecated and should be avoided.
> **Note:** Media types are optional; if you do not indicate a media type in your media query, then the media query will default to being for all media types.
### Media feature rules
After specifying the type, you can then target a media feature with a rule.
#### Width and height
The feature we tend to detect most often in order to create responsive designs (and that has widespread browser support) is viewport width, and we can apply CSS if the viewport is above or below a certain width β or an exact width β using the `min-width`, `max-width`, and `width` media features.
These features are used to create layouts that respond to different screen sizes. For example, to change the body text color to red if the viewport is exactly 600 pixels, you would use the following media query.
```css
@media screen and (width: 600px) {
body {
color: red;
}
}
```
[Open this example](https://mdn.github.io/css-examples/learn/media-queries/width.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/width.html).
The `width` (and `height`) media features can be used as ranges, and therefore be prefixed with `min-` or `max-` to indicate that the given value is a minimum, or a maximum. For example, to make the color blue if the viewport is 600 pixels or narrower, use `max-width`:
```css
@media screen and (max-width: 600px) {
body {
color: blue;
}
}
```
[Open this example](https://mdn.github.io/css-examples/learn/media-queries/max-width.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/max-width.html).
In practice, using minimum or maximum values is much more useful for responsive design so you will rarely see `width` or `height` used alone.
There are many other media features that you can test for, although some of the newer features introduced in Levels 4 and 5 of the media queries specification have limited browser support. Each feature is documented on MDN along with browser support information, and you can find a complete list at [Using Media Queries: Syntax](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries#syntax).
#### Orientation
One well-supported media feature is `orientation`, which allows us to test for portrait or landscape mode. To change the body text color if the device is in landscape orientation, use the following media query.
```css
@media (orientation: landscape) {
body {
color: rebeccapurple;
}
}
```
[Open this example](https://mdn.github.io/css-examples/learn/media-queries/orientation.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/orientation.html).
A standard desktop view has a landscape orientation, and a design that works well in this orientation may not work as well when viewed on a phone or tablet in portrait mode. Testing for orientation can help you to create a layout which is optimized for devices in portrait mode.
#### Use of pointing devices
As part of the Level 4 specification, the `hover` media feature was introduced. This feature means you can test if the user has the ability to hover over an element, which essentially means they are using some kind of pointing device; touchscreen and keyboard navigation does not hover.
```css
@media (hover: hover) {
body {
color: rebeccapurple;
}
}
```
[Open this example](https://mdn.github.io/css-examples/learn/media-queries/hover.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/hover.html).
If we know the user cannot hover, we could display some interactive features by default. For users who can hover, we might choose to make them available when a link is hovered over.
Also in Level 4 is the `pointer` media feature. This takes three possible values, `none`, `fine` and `coarse`. A `fine` pointer is something like a mouse or trackpad. It enables the user to precisely target a small area. A `coarse` pointer is your finger on a touchscreen. The value `none` means the user has no pointing device; perhaps they are navigating with the keyboard only or with voice commands.
Using `pointer` can help you to design better interfaces that respond to the type of interaction a user is having with a screen. For example, you could create larger hit areas if you know that the user is interacting with the device as a touchscreen.
#### Using ranged syntax
One common case is to check if the viewport width is between two values:
```css
@media (min-width: 30em) and (max-width: 50em) {
/* β¦ */
}
```
If you want to improve the readability of this, you can use "range" syntax:
```css
@media (30em <= width <= 50em) {
/* β¦ */
}
```
So in this case, styles are applied when the viewport width is between `30em` and `50em`.
For more information on using this style, see [Using Media Queries: Syntax improvements in Level 4](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries#syntax_improvements_in_level_4)
## More complex media queries
With all of the different possible media queries, you may want to combine them, or create lists of queries β any of which could be matched.
### "and" logic in media queries
To combine media features you can use `and` in much the same way as we have used `and` above to combine a media type and feature. For example, we might want to test for a `min-width` and `orientation`. The body text will only be blue if the viewport is at least 600 pixels wide and the device is in landscape mode.
```css
@media screen and (min-width: 600px) and (orientation: landscape) {
body {
color: blue;
}
}
```
[Open this example](https://mdn.github.io/css-examples/learn/media-queries/and.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/and.html).
### "or" logic in media queries
If you have a set of queries, any of which could match, then you can comma separate these queries. In the below example the text will be blue if the viewport is at least 600 pixels wide OR the device is in landscape orientation. If either of these things are true the query matches.
```css
@media screen and (min-width: 600px), screen and (orientation: landscape) {
body {
color: blue;
}
}
```
[Open this example](https://mdn.github.io/css-examples/learn/media-queries/or.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/or.html).
### "not" logic in media queries
You can negate an entire media query by using the `not` operator. This reverses the meaning of the entire media query. Therefore in this next example the text will only be blue if the orientation is portrait.
```css
@media not all and (orientation: landscape) {
body {
color: blue;
}
}
```
[Open this example](https://mdn.github.io/css-examples/learn/media-queries/not.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/not.html).
## How to choose breakpoints
In the early days of responsive design, many designers would attempt to target very specific screen sizes. Lists of the sizes of the screens of popular phones and tablets were published in order that designs could be created to neatly match those viewports.
There are now far too many devices, with a huge variety of sizes, to make that feasible. This means that instead of targeting specific sizes for all designs, a better approach is to change the design at the size where the content starts to break in some way. Perhaps the line lengths become far too long, or a boxed out sidebar gets squashed and hard to read. That's the point at which you want to use a media query to change the design to a better one for the space you have available. This approach means that it doesn't matter what the exact dimensions are of the device being used, every range is catered for. The points at which a media query is introduced are known as **breakpoints**.
The [Responsive Design Mode](https://firefox-source-docs.mozilla.org/devtools-user/responsive_design_mode/index.html) in Firefox DevTools is very useful for working out where these breakpoints should go. You can easily make the viewport smaller and larger to see where the content would be improved by adding a media query and tweaking the design.

## Active learning: mobile first responsive design
Broadly, you can take two approaches to a responsive design. You can start with your desktop or widest view and then add breakpoints to move things around as the viewport becomes smaller, or you can start with the smallest view and add layout as the viewport becomes larger. This second approach is described as **mobile first** responsive design and is quite often the best approach to follow.
The view for the very smallest devices is quite often a simple single column of content, much as it appears in normal flow. This means that you probably don't need to do a lot of layout for small devices β order your source well and you will have a readable layout by default.
The below walkthrough takes you through this approach with a very simple layout. In a production site you are likely to have more things to adjust within your media queries, however the approach would be exactly the same.
### Walkthrough: a simple mobile-first layout
Our starting point is an HTML document with some CSS applied to add background colors to the various parts of the layout.
```css
* {
box-sizing: border-box;
}
body {
width: 90%;
margin: 2em auto;
font:
1em/1.3 Arial,
Helvetica,
sans-serif;
}
a:link,
a:visited {
color: #333;
}
nav ul,
aside ul {
list-style: none;
padding: 0;
}
nav a:link,
nav a:visited {
background-color: rgb(207 232 220 / 20%);
border: 2px solid rgb(79 185 227);
text-decoration: none;
display: block;
padding: 10px;
color: #333;
font-weight: bold;
}
nav a:hover {
background-color: rgb(207 232 220 / 70%);
}
.related {
background-color: rgb(79 185 227 / 30%);
border: 1px solid rgb(79 185 227);
padding: 10px;
}
.sidebar {
background-color: rgb(207 232 220 / 50%);
padding: 10px;
}
article {
margin-bottom: 1em;
}
```
We've made no layout changes, however the source of the document is ordered in a way that makes the content readable. This is an important first step and one which ensures that if the content were to be read out by a screen reader, it would be understandable.
```html
<body>
<div class="wrapper">
<header>
<nav>
<ul>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
<li><a href="">Meet the team</a></li>
<li><a href="">Blog</a></li>
</ul>
</nav>
</header>
<main>
<article>
<div class="content">
<h1>Veggies!</h1>
<p>β¦</p>
</div>
<aside class="related">
<p>β¦</p>
</aside>
</article>
<aside class="sidebar">
<h2>External vegetable-based links</h2>
<ul>
<li>β¦</li>
</ul>
</aside>
</main>
<footer><p>©2019</p></footer>
</div>
</body>
```
This simple layout also works well on mobile. If we view the layout in Responsive Design Mode in DevTools we can see that it works pretty well as a straightforward mobile view of the site.
[Open step 1](https://mdn.github.io/css-examples/learn/media-queries/step1.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/step1.html).
**If you want to follow on and implement this example as we go, make a local copy of [step1.html](https://github.com/mdn/css-examples/blob/main/learn/media-queries/step1.html) on your computer.**
From this point, start to drag the Responsive Design Mode view wider until you can see that the line lengths are becoming quite long, and we have space for the navigation to display in a horizontal line. This is where we'll add our first media query. We'll use ems, as this will mean that if the user has increased their text size, the breakpoint will happen at a similar line-length but wider viewport, than someone with a smaller text size.
**Add the below code into the bottom of your step1.html CSS.**
```css
@media screen and (min-width: 40em) {
article {
display: grid;
grid-template-columns: 3fr 1fr;
column-gap: 20px;
}
nav ul {
display: flex;
}
nav li {
flex: 1;
}
}
```
This CSS gives us a two-column layout inside the article, of the article content and related information in the aside element. We have also used flexbox to put the navigation into a row.
[Open step 2](https://mdn.github.io/css-examples/learn/media-queries/step2.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/step2.html).
Let's continue to expand the width until we feel there is enough room for the sidebar to also form a new column. Inside a media query we'll make the main element into a two column grid. We then need to remove the {{cssxref("margin-bottom")}} on the article in order that the two sidebars align with each other, and we'll add a {{cssxref("border")}} to the top of the footer. Typically these small tweaks are the kind of thing you will do to make the design look good at each breakpoint.
**Again, add the below code into the bottom of your step1.html CSS.**
```css
@media screen and (min-width: 70em) {
main {
display: grid;
grid-template-columns: 3fr 1fr;
column-gap: 20px;
}
article {
margin-bottom: 0;
}
footer {
border-top: 1px solid #ccc;
margin-top: 2em;
}
}
```
[Open step 3](https://mdn.github.io/css-examples/learn/media-queries/step3.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/step3.html).
If you look at the final example at different widths you can see how the design responds and works as a single column, two columns, or three columns, depending on the available width. This is a very simple example of a mobile first responsive design.
## The viewport meta tag
If you look at the HTML source in the above example, you'll see the following element included in the head of the document:
```html
<meta name="viewport" content="width=device-width,initial-scale=1" />
```
This is the [viewport meta tag](/en-US/docs/Web/HTML/Viewport_meta_tag) β it exists as a way to control how mobile browsers render content. This is needed because by default, most mobile browsers lie about their viewport width. Non-responsive sites commonly look really bad when rendered in a narrow viewport, so mobile browsers usually render the site with a viewport width wider than the real device width by default (usually 980 pixels), and then shrink the rendered result so that it fits in the display.
This is all well and good, but it means that responsive sites are not going to work as expected. If the viewport width is reported as 980 pixels, then mobile layouts (for example created using a media query of `@media screen and (max-width: 600px) { }`) are not going to render as expected.
To remedy this, including a viewport meta tag like the one above on your page tells the browser "don't render the content with a 980 pixel viewport β render it using the real device width instead, and set a default initial scale level for better consistency." The media queries will then kick in as expected.
There are a number of other options you can put inside the `content` attribute of the viewport meta tag β see [Using the viewport meta tag to control layout on mobile browsers](/en-US/docs/Web/HTML/Viewport_meta_tag) for more details.
## Do you really need a media query?
Flexbox, Grid, and multi-column layout all give you ways to create flexible and even responsive components without the need for a media query. It's always worth considering whether these layout methods can achieve what you want without adding media queries. For example, you might want a set of cards that are at least 200 pixels wide, with as many of these 200 pixels as will fit into the main article. This can be achieved with grid layout, using no media queries at all.
This could be achieved using the following:
```html
<ul class="grid">
<li>
<h2>Card 1</h2>
<p>β¦</p>
</li>
<li>
<h2>Card 2</h2>
<p>β¦</p>
</li>
<li>
<h2>Card 3</h2>
<p>β¦</p>
</li>
<li>
<h2>Card 4</h2>
<p>β¦</p>
</li>
<li>
<h2>Card 5</h2>
<p>β¦</p>
</li>
</ul>
```
```css
.grid {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 20px;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
.grid li {
border: 1px solid #666;
padding: 10px;
}
```
[Open the grid layout example](https://mdn.github.io/css-examples/learn/media-queries/grid.html) in the browser, or [view the source](https://github.com/mdn/css-examples/blob/main/learn/media-queries/grid.html).
With the example open in your browser, make the screen wider and narrower to see the number of column tracks change. The nice thing about this method is that grid is not looking at the viewport width, but the width it has available for this component. It might seem strange to wrap up a section about media queries with a suggestion that you might not need one at all! However, in practice you will find that good use of modern layout methods, enhanced with media queries, will give the best results.
## Test your skills!
You've reached the end of this article, but can you remember the most important information? You can find a test to verify that you've retained this information before you move on β see [Test your skills: Responsive web design and media queries](/en-US/docs/Learn/CSS/CSS_layout/rwd_skills).
## Summary
In this lesson you have learned about media queries, and also discovered how to use them in practice to create a mobile first responsive design.
You could use the starting point that we have created to test out more media queries. For example, perhaps you could change the size of the navigation if you detect that the visitor has a coarse pointer, using the `pointer` media feature.
You could also experiment with adding different components and seeing whether the addition of a media query, or using a layout method like flexbox or grid is the most appropriate way to make the components responsive. Very often there is no right or wrong way β you should experiment and see which works best for your design and content.
{{PreviousMenuNext("Learn/CSS/CSS_layout/Responsive_Design", "Learn/CSS/CSS_layout/Legacy_Layout_Methods", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/normal_flow/index.md | ---
title: Normal Flow
slug: Learn/CSS/CSS_layout/Normal_Flow
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/CSS/CSS_layout/Introduction", "Learn/CSS/CSS_layout/Flexbox", "Learn/CSS/CSS_layout")}}
This article explains normal flow, or the way that webpage elements lay themselves out if you haven't changed their layout.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
The basics of HTML (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">Introduction to CSS</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To explain how browsers layout web pages by default, before we begin to
make changes.
</td>
</tr>
</tbody>
</table>
As detailed in the last lesson introducing layout, elements on a webpage lay out in normal flow if you haven't applied any CSS to change the way they behave. And, as we began to discover, you can change how elements behave either by adjusting their position in normal flow or by removing them from it altogether. Starting with a solid, well-structured document that's readable in normal flow is the best way to begin any webpage. It ensures that your content is readable even if the user's using a very limited browser or a device such as a screen reader that reads out the content of the page. In addition, since normal flow is designed to make a readable document, by starting in this way you're working _with_ the document rather than struggling _against_ it as you make changes to the layout.
Before digging deeper into different layout methods, it's worth revisiting some of the things you have studied in previous modules with regard to normal document flow.
## How are elements laid out by default?
The process begins as the boxes of individual elements are laid out in such a way that any padding, border, or margin they happen to have is added to their content. This is what we call the **box model**.
By default, a [block-level element](/en-US/docs/Glossary/Block-level_content)'s content fills the available inline space of the parent element containing it, growing along the block dimension to accommodate its content. The size of [inline-level elements](/en-US/docs/Glossary/Inline-level_content) is just the size of their content. You can set {{cssxref("width")}} or {{cssxref("height")}} on some elements that have a default {{cssxref("display")}} property value of `inline`, like {{HTMLElement("img")}}, but `display` value will still remain `inline`.
If you want to control the `display` property of an inline-level element in this manner, use CSS to set it to behave like a block-level element (e.g., with `display: block;` or `display: inline-block;`, which mixes characteristics from both).
That explains how elements are structured individually, but how about the way they're structured when they interact with one another? The normal layout flow (mentioned in the layout introduction article) is the system by which elements are placed inside the browser's viewport. By default, block-level elements are laid out in the _block flow direction_, which is based on the parent's [writing mode](/en-US/docs/Web/CSS/writing-mode) (_initial_: horizontal-tb). Each element will appear on a new line below the last one, with each one separated by whatever margin that's been specified. In English, for example, (or any other horizontal, top to bottom writing mode) block-level elements are laid out vertically.
Inline elements behave differently. They don't appear on new lines; instead, they all sit on the same line along with any adjacent (or wrapped) text content as long as there is space for them to do so inside the width of the parent block level element. If there isn't space, then the overflowing content will move down to a new line.
If two vertically adjacent elements both have a margin set on them and their margins touch, the larger of the two margins remains and the smaller one disappears. This is known as [**margin collapsing**](/en-US/docs/Web/CSS/CSS_box_model/Mastering_margin_collapsing).
Collapsing margins is only relevant in the **vertical direction**.
Let's look at a simple example that explains all of this:
```html
<h1>Basic document flow</h1>
<p>
I am a basic block level element. My adjacent block level elements sit on new
lines below me.
</p>
<p>
By default we span 100% of the width of our parent element, and we are as tall
as our child content. Our total width and height is our content + padding +
border width/height.
</p>
<p>
We are separated by our margins. Because of margin collapsing, we are
separated by the width of one of our margins, not both.
</p>
<p>
Inline elements <span>like this one</span> and <span>this one</span> sit on
the same line along with adjacent text nodes, if there is space on the same
line. Overflowing inline elements will
<span>wrap onto a new line if possible (like this one containing text)</span>,
or just go on to a new line if not, much like this image will do:
<img src="long.jpg" alt="snippet of cloth" />
</p>
```
```css
body {
width: 500px;
margin: 0 auto;
}
p {
background: rgb(255 84 104 / 30%);
border: 2px solid rgb(255 84 104);
padding: 10px;
margin: 10px;
}
span {
background: white;
border: 1px solid black;
}
```
{{ EmbedLiveSample('How_are_elements_laid_out_by_default', '100%', 600) }}
## Summary
In this lesson you've learned the basics of normal flow β the default layout for CSS elements. By understanding how inline elements, block elements, and margins behave by default, it'll be easier to modify their behavior in the future.
In the next article, we'll build on this knowledge by making changes to CSS elements using [flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox).
{{PreviousMenuNext("Learn/CSS/CSS_layout/Introduction", "Learn/CSS/CSS_layout/Flexbox", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/multicol_skills/index.md | ---
title: "Test your skills: Multicol"
slug: Learn/CSS/CSS_layout/Multicol_skills
page-type: learn-module-assessment
---
{{LearnSidebar}}
The aim of this skill test is to assess whether you understand [CSS multiple-column layout](/en-US/docs/Learn/CSS/CSS_layout/Multiple-column_Layout), including the {{CSSxRef("column-count")}}, {{CSSxRef("column-width")}}, {{CSSxRef("column-gap")}}, {{CSSxRef("column-span")}} and {{CSSxRef("column-rule")}} properties and values. You will be working through three small tasks that use different elements of the material you have just covered.
> **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 create three columns, with a 50px gap between each column.
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/multicol/multicol1.html", '100%', 1000)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/multicol/multicol1-download.html) to work in your own editor or in an online editor.
## Task 2
In this task, we want you to create columns which have a minimum width of 200px. Then, add a 5px grey rule between each column, ensuring there is 10px of space between the edge of the rule and the column content.
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/multicol/multicol2.html", '100%', 1000)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/multicol/multicol2-download.html) to work in your own editor or in an online editor.
## Task 3
In this task, we want you to cause the element containing the heading and subheading to span across all columns so it looks like the image below:

Try updating the live code below to recreate the finished example:
{{EmbedGHLiveSample("css-examples/learn/tasks/multicol/multicol3.html", '100%', 1000)}}
> **Callout:**
>
> [Download the starting point for this task](https://github.com/mdn/css-examples/blob/main/learn/tasks/multicol/multicol3-download.html) to work in your own editor or in an online editor.
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/legacy_layout_methods/index.md | ---
title: Legacy layout methods
slug: Learn/CSS/CSS_layout/Legacy_Layout_Methods
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/CSS/CSS_layout/Media_queries", "Learn/CSS/CSS_layout/Supporting_Older_Browsers", "Learn/CSS/CSS_layout")}}
Grid systems are a very common feature used in CSS layouts, and before CSS Grid Layout they tended to be implemented using floats or other layout features. You imagine your layout as a set number of columns (e.g. 4, 6, or 12), and then fit your content columns inside these imaginary columns. In this article we'll explore how these older methods work, in order that you understand how they were used if you work on an older project.
<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">Introduction to CSS</a> and
<a href="/en-US/docs/Learn/CSS/Building_blocks">Styling boxes</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the fundamental concepts behind the grid layout systems
used prior to CSS Grid Layout being available in browsers.
</td>
</tr>
</tbody>
</table>
## Layout and grid systems before CSS Grid Layout
It may seem surprising to anyone coming from a design background that CSS didn't have an inbuilt grid system until very recently, and instead we seemed to be using a variety of sub-optimal methods to create grid-like designs. We now refer to these as "legacy" methods.
For new projects, in most cases CSS Grid Layout will be used in combination with one or more other modern layout methods to form the basis for any layout. You will however encounter "grid systems" using these legacy methods from time to time. It is worth understanding how they work, and why they are different to CSS Grid Layout.
This lesson will explain how grid systems and grid frameworks based on floats and flexbox work. Having studied Grid Layout you will probably be surprised how complicated this all seems! This knowledge will be helpful to you if you need to create fallback code for browsers that do not support newer methods, in addition to allowing you to work on existing projects which use these types of systems.
It is worth bearing in mind, as we explore these systems, that none of them actually create a grid in the way that CSS Grid Layout creates a grid. They work by giving items a size, and pushing them around to line them up in a way that _looks_ like a grid.
## A two column layout
Let's start with the simplest possible example β a two column layout. You can follow along by creating a new `index.html` file on your computer, filling it with a [simple HTML template](https://github.com/mdn/learning-area/blob/main/html/introduction-to-html/getting-started/index.html), and inserting the below code into it at the appropriate places. At the bottom of the section you can see a live example of what the final code should look like.
First of all, we need some content to put into our columns. Replace whatever is inside the body currently with the following:
```html
<h1>2 column layout example</h1>
<div>
<h2>First column</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at
ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer
ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur
vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus.
Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus
sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus.
Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis,
eget fermentum sapien.
</p>
</div>
<div>
<h2>Second column</h2>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies
lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
</div>
```
Each one of the columns needs an outer element to contain its content and let us manipulate all of it at once. In this example case we've chosen {{htmlelement("div")}}s, but you could choose something more semantically appropriate like {{htmlelement("article")}}s, {{htmlelement("section")}}s, and {{htmlelement("aside")}}, or whatever.
Now for the CSS. First, of all, apply the following to your HTML to provide some basic setup:
```css
body {
width: 90%;
max-width: 900px;
margin: 0 auto;
}
```
The body will be 90% of the viewport wide until it gets to 900px wide, in which case it will stay fixed at this width and center itself in the viewport. By default, its children (the {{htmlelement("Heading_Elements", "h1")}} and the two {{htmlelement("div")}}s) will span 100% of the width of the body. If we want the two {{htmlelement("div")}}s to be floated alongside one another, we need to set their widths to total 100% of the width of their parent element or smaller so they can fit alongside one another. Add the following to the bottom of your CSS:
```css
div:nth-of-type(1) {
width: 48%;
}
div:nth-of-type(2) {
width: 48%;
}
```
Here we've set both to be 48% of their parent's width β this totals 96%, leaving us 4% free to act as a gutter between the two columns, giving the content some space to breathe. Now we just need to float the columns, like so:
```css
div:nth-of-type(1) {
width: 48%;
float: left;
}
div:nth-of-type(2) {
width: 48%;
float: right;
}
```
Putting this all together should give us a result like so:
{{ EmbedLiveSample('A_two_column_layout', '100%', 520) }}
You'll notice here that we are using percentages for all the widths β this is quite a good strategy, as it creates a **liquid layout**, one that adjusts to different screen sizes and keeps the same proportions for the column widths at smaller screen sizes. Try adjusting the width of your browser window to see for yourself. This is a valuable tool for responsive web design.
> **Note:** You can see this example running at [0_two-column-layout.html](https://mdn.github.io/learning-area/css/css-layout/floats/0_two-column-layout.html) (see also [the source code](https://github.com/mdn/learning-area/blob/main/css/css-layout/floats/0_two-column-layout.html)).
## Creating simple legacy grid frameworks
The majority of legacy frameworks use the behavior of the {{cssxref("float")}} property to float one column up next to another in order to create something that looks like a grid. Working through the process of creating a grid with floats shows you how this works and also introduces some more advanced concepts to build on the things you learned in the lesson on [floats and clearing](/en-US/docs/Learn/CSS/CSS_layout/Floats).
The easiest type of grid framework to create is a fixed width one β we just need to work out how much total width we want our design to be, how many columns we want, and how wide the gutters and columns should be. If we instead decided to lay out our design on a grid with columns that grow and shrink according to browser width, we would need to calculate percentage widths for the columns and gutters between them.
In the next sections we will look at how to create both. We will create a 12 column grid β a very common choice that is seen to be very adaptable to different situations given that 12 is nicely divisible by 6, 4, 3, and 2.
### A simple fixed width grid
Lets first create a grid system that uses fixed width columns.
Start out by making a local copy of our sample [simple-grid.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/simple-grid.html) file, which contains the following markup in its body.
```html
<div class="wrapper">
<div class="row">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
<div class="col">4</div>
<div class="col">5</div>
<div class="col">6</div>
<div class="col">7</div>
<div class="col">8</div>
<div class="col">9</div>
<div class="col">10</div>
<div class="col">11</div>
<div class="col">12</div>
</div>
<div class="row">
<div class="col span1">13</div>
<div class="col span6">14</div>
<div class="col span3">15</div>
<div class="col span2">16</div>
</div>
</div>
```
The aim is to turn this into a demonstration grid of two rows on a twelve column grid β the top row demonstrating the size of the individual columns, the second row some different sized areas on the grid.

In the {{htmlelement("style")}} element, add the following code, which gives the wrapper container a width of 980 pixels, with padding on the right-hand side of 20 pixels. This leaves us with 960 pixels for our total column/gutter widths β in this case, the padding is subtracted from the total content width because we have set {{cssxref("box-sizing")}} to `border-box` on all elements on the site (see [The alternative CSS box model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model#the_alternative_css_box_model) for more explanation).
```css
* {
box-sizing: border-box;
}
body {
width: 980px;
margin: 0 auto;
}
.wrapper {
padding-right: 20px;
}
```
Now use the row container that is wrapped around each row of the grid to clear one row from another. Add the following rule below your previous one:
```css
.row {
clear: both;
}
```
Applying this clearing means that we don't need to completely fill each row with elements making the full twelve columns. The rows will remain separated, and not interfere with each other.
The gutters between the columns are 20 pixels wide. We create these gutters as a margin on the left side of each column β including the first column, to balance out the 20 pixels of padding on the right-hand side of the container. So we have 12 gutters in total β 12 x 20 = 240.
We need to subtract that from our total width of 960 pixels, giving us 720 pixels for our columns. If we now divide that by 12, we know that each column should be 60 pixels wide.
Our next step is to create a rule for the class `.col`, floating it left, giving it a {{cssxref("margin-left")}} of 20 pixels to form the gutter, and a {{cssxref("width")}} of 60 pixels. Add the following rule to the bottom of your CSS:
```css
.col {
float: left;
margin-left: 20px;
width: 60px;
background: rgb(255 150 150);
}
```
The top row of single columns will now lay out neatly as a grid.
> **Note:** We've also given each column a light red color so you can see exactly how much space each one takes up.
Layout containers that we want to span more than one column need to be given special classes to adjust their {{cssxref("width")}} values to the required number of columns (plus gutters in between). We need to create an additional class to allow containers to span 2 to 12 columns. Each width is the result of adding up the column width of that number of columns plus the gutter widths, which will always number one less than the number of columns.
Add the following at the bottom of your CSS:
```css
/* Two column widths (120px) plus one gutter width (20px) */
.col.span2 {
width: 140px;
}
/* Three column widths (180px) plus two gutter widths (40px) */
.col.span3 {
width: 220px;
}
/* And so on⦠*/
.col.span4 {
width: 300px;
}
.col.span5 {
width: 380px;
}
.col.span6 {
width: 460px;
}
.col.span7 {
width: 540px;
}
.col.span8 {
width: 620px;
}
.col.span9 {
width: 700px;
}
.col.span10 {
width: 780px;
}
.col.span11 {
width: 860px;
}
.col.span12 {
width: 940px;
}
```
With these classes created we can now lay out different width columns on the grid. Try saving and loading the page in your browser to see the effects.
> **Note:** If you are having trouble getting the above example to work, try comparing it against our [finished version](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/simple-grid-finished.html) on GitHub ([see it running live](https://mdn.github.io/learning-area/css/css-layout/grids/simple-grid-finished.html) also).
Try modifying the classes on your elements or even adding and removing some containers, to see how you can vary the layout. For example, you could make the second row look like this:
```html
<div class="row">
<div class="col span8">13</div>
<div class="col span4">14</div>
</div>
```
Now you've got a grid system working, you can define the rows and the number of columns in each row, then fill each container with your required content. Great!
### Creating a fluid grid
Our grid works nicely, but it has a fixed width. We really want a flexible (fluid) grid that will grow and shrink with the available space in the browser {{Glossary("viewport")}}. To achieve this we can turn the reference pixel widths into percentages.
The equation that turns a fixed width into a flexible percentage-based one is as follows.
```plain
target / context = result
```
For our column width, our **target width** is 60 pixels and our **context** is the 960 pixel wrapper. We can use the following to calculate a percentage.
```plain
60 / 960 = 0.0625
```
We then move the decimal point 2 places giving us a percentage of 6.25%. So, in our CSS we can replace the 60 pixel column width with 6.25%.
We need to do the same with our gutter width:
```plain
20 / 960 = 0.02083333333
```
So we need to replace the 20 pixel {{cssxref("margin-left")}} on our `.col` rule and the 20 pixel {{cssxref("padding-right")}} on `.wrapper` with 2.08333333%.
#### Updating our grid
To get started in this section, make a new copy of your previous example page, or make a local copy of our [simple-grid-finished.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/simple-grid-finished.html) code to use as a starting point.
Update the second CSS rule (with the `.wrapper` selector) as follows:
```css
body {
width: 90%;
max-width: 980px;
margin: 0 auto;
}
.wrapper {
padding-right: 2.08333333%;
}
```
Not only have we given it a percentage {{cssxref("width")}}, we have also added a {{cssxref("max-width")}} property in order to stop the layout becoming too wide.
Next, update the fourth CSS rule (with the `.col` selector) like so:
```css
.col {
float: left;
margin-left: 2.08333333%;
width: 6.25%;
background: rgb(255 150 150);
}
```
Now comes the slightly more laborious part β we need to update all our `.col.span` rules to use percentages rather than pixel widths. This takes a bit of time with a calculator; to save you some effort, we've done it for you below.
Update the bottom block of CSS rules with the following:
```css
/* Two column widths (12.5%) plus one gutter width (2.08333333%) */
.col.span2 {
width: 14.58333333%;
}
/* Three column widths (18.75%) plus two gutter widths (4.1666666) */
.col.span3 {
width: 22.91666666%;
}
/* And so on⦠*/
.col.span4 {
width: 31.24999999%;
}
.col.span5 {
width: 39.58333332%;
}
.col.span6 {
width: 47.91666665%;
}
.col.span7 {
width: 56.24999998%;
}
.col.span8 {
width: 64.58333331%;
}
.col.span9 {
width: 72.91666664%;
}
.col.span10 {
width: 81.24999997%;
}
.col.span11 {
width: 89.5833333%;
}
.col.span12 {
width: 97.91666663%;
}
```
Now save your code, load it in a browser, and try changing the viewport width β you should see the column widths adjust nicely to suit.
> **Note:** If you are having trouble getting the above example to work, try comparing it against our [finished version on GitHub](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/fluid-grid.html) ([see it running live](https://mdn.github.io/learning-area/css/css-layout/grids/fluid-grid.html) also).
### Easier calculations using the calc() function
You could use the {{cssxref("calc", "calc()")}} function to do the math right inside your CSS β this allows you to insert simple mathematical equations into your CSS values, to calculate what a value should be. It is especially useful when there is complex math to be done, and you can even compute a calculation that uses different units, for example "I want this element's height to always be 100% of its parent's height, minus 50px". See [this example from a MediaStream Recording API tutorial](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API#keeping_the_interface_constrained_to_the_viewport_regardless_of_device_height_with_calc).
Anyway, back to our grids! Any column that spans more than one column of our grid has a total width of 6.25% multiplied by the number of columns spanned plus 2.08333333% multiplied by the number of gutters (which will always be the number of columns minus 1). The `calc()` function allows us to do this calculation right inside the width value, so for any item spanning 4 columns we can do this, for example:
```css
.col.span4 {
width: calc((6.25% * 4) + (2.08333333% * 3));
}
```
Try replacing your bottom block of rules with the following, then reload it in the browser to see if you get the same result:
```css
.col.span2 {
width: calc((6.25% * 2) + 2.08333333%);
}
.col.span3 {
width: calc((6.25% * 3) + (2.08333333% * 2));
}
.col.span4 {
width: calc((6.25% * 4) + (2.08333333% * 3));
}
.col.span5 {
width: calc((6.25% * 5) + (2.08333333% * 4));
}
.col.span6 {
width: calc((6.25% * 6) + (2.08333333% * 5));
}
.col.span7 {
width: calc((6.25% * 7) + (2.08333333% * 6));
}
.col.span8 {
width: calc((6.25% * 8) + (2.08333333% * 7));
}
.col.span9 {
width: calc((6.25% * 9) + (2.08333333% * 8));
}
.col.span10 {
width: calc((6.25% * 10) + (2.08333333% * 9));
}
.col.span11 {
width: calc((6.25% * 11) + (2.08333333% * 10));
}
.col.span12 {
width: calc((6.25% * 12) + (2.08333333% * 11));
}
```
> **Note:** You can see our finished version in [fluid-grid-calc.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/fluid-grid-calc.html) (also [see it live](https://mdn.github.io/learning-area/css/css-layout/grids/fluid-grid-calc.html)).
### Semantic versus "unsemantic" grid systems
Adding classes to your markup to define layout means that your content and markup becomes tied to your visual presentation. You will sometimes hear this use of CSS classes described as being "unsemantic" β describing how the content looks β rather than a semantic use of classes that describes the content. This is the case with our `span2`, `span3`, etc., classes.
These are not the only approach. You could instead decide on your grid and then add the sizing information to the rules for existing semantic classes. For example, if you had a {{htmlelement("div")}} with a class of `content` on it that you wanted to span 8 columns, you could copy across the width from the `span8` class, giving you a rule like so:
```css
.content {
width: calc((6.25% * 8) + (2.08333333% * 7));
}
```
> **Note:** If you were to use a preprocessor such as [Sass](https://sass-lang.com/), you could create a simple mixin to insert that value for you.
### Enabling offset containers in our grid
The grid we have created works well as long as we want to start all of the containers flush with the left-hand side of the grid. If we wanted to leave an empty column space before the first container β or between containers β we would need to create an offset class to add a left margin to our site to push it across the grid visually. More math!
Let's try this out.
Start with your previous code, or use our [fluid-grid.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/fluid-grid.html) file as a starting point.
Let's create a class in our CSS that will offset a container element by one column width. Add the following to the bottom of your CSS:
```css
.offset-by-one {
margin-left: calc(6.25% + (2.08333333% * 2));
}
```
Or if you prefer to calculate the percentages yourself, use this one:
```css
.offset-by-one {
margin-left: 10.41666666%;
}
```
You can now add this class to any container you want to leave a one column wide empty space on the left-hand side of it. For example, if you have this in your HTML:
```html
<div class="col span6">14</div>
```
Try replacing it with
```html
<div class="col span5 offset-by-one">14</div>
```
> **Note:** Notice that you need to reduce the number of columns spanned, to make room for the offset!
Try loading and refreshing to see the difference, or check out our [fluid-grid-offset.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/fluid-grid-offset.html) example (see it [running live](https://mdn.github.io/learning-area/css/css-layout/grids/fluid-grid-offset.html) also). The finished example should look like this:

> **Note:** As an extra exercise, can you implement an `offset-by-two` class?
### Floated grid limitations
When using a system like this you do need to take care that your total widths add up correctly, and that you don't include elements in a row that span more columns than the row can contain. Due to the way floats work, if the number of grid columns becomes too wide for the grid, the elements on the end will drop down to the next line, breaking the grid.
Also bear in mind that if the content of the elements gets wider than the rows they occupy, it will overflow and look a mess.
The biggest limitation of this system is that it is essentially one dimensional. We are dealing with columns, and spanning elements across columns, but not rows. It is very difficult with these older layout methods to control the height of elements without explicitly setting a height, and this is a very inflexible approach too β it only works if you can guarantee that your content will be a certain height.
## Flexbox grids?
If you read our previous article about [flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox), you might think that flexbox is the ideal solution for creating a grid system. There are many flexbox-based grid systems available and flexbox can solve many of the issues that we've already discovered when creating our grid above.
However, flexbox was never designed as a grid system and poses a new set of challenges when used as one. As a simple example of this, we can take the same example markup we used above and use the following CSS to style the `wrapper`, `row`, and `col` classes:
```css
body {
width: 90%;
max-width: 980px;
margin: 0 auto;
}
.wrapper {
padding-right: 2.08333333%;
}
.row {
display: flex;
}
.col {
margin-left: 2.08333333%;
margin-bottom: 1em;
width: 6.25%;
flex: 1 1 auto;
background: rgb(255 150 150);
}
```
You can try making these replacements in your own example, or look at our [flexbox-grid.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/flexbox-grid.html) example code (see it [running live](https://mdn.github.io/learning-area/css/css-layout/grids/flexbox-grid.html) also).
Here we are turning each row into a flex container. With a flexbox-based grid we still need rows in order to allow us to have elements that add up to less than 100%. We set that container to `display: flex`.
On `.col` we set the {{cssxref("flex")}} property's first value ({{cssxref("flex-grow")}}) to 1 so our items can grow, the second value ({{cssxref("flex-shrink")}}) to 1 so the items can shrink, and the third value ({{cssxref("flex-basis")}}) to `auto`. As our element has a {{cssxref("width")}} set, `auto` will use that width as the `flex-basis` value.
On the top line we get twelve neat boxes on the grid and they grow and shrink equally as we change the viewport width. On the next line, however, we only have four items and these also grow and shrink from that 60px basis. With only four of them they can grow a lot more than the items in the row above, the result being that they all occupy the same width on the second row.

To fix this we still need to include our `span` classes to provide a width that will replace the value used by `flex-basis` for that element.
They also don't respect the grid used by the items above because they don't know anything about it.
Flexbox is **one-dimensional** by design. It deals with a single dimension, that of a row or a column. We can't create a strict grid for columns and rows, meaning that if we are to use flexbox for our grid, we still need to calculate percentages as for the floated layout.
In your project you might still choose to use a flexbox 'grid' due to the additional alignment and space distribution capabilities flexbox provides over floats. You should, however, be aware that you are still using a tool for something other than what it was designed for. So you may feel like it is making you jump through additional hoops to get the end result you want.
## Third party grid systems
Now that we understand the math behind our grid calculations, we are in a good place to look at some of the third party grid systems in common use. If you search for "CSS Grid framework" on the Web, you will find a huge list of options to choose from. Popular frameworks such as [Bootstrap](https://getbootstrap.com/) and [Foundation](https://get.foundation/) include a grid system. There are also standalone grid systems, either developed using CSS or using preprocessors.
Let's take a look at one of these standalone systems as it demonstrates common techniques for working with a grid framework. The grid we will be using is part of Skeleton, a simple CSS framework.
To get started visit the [Skeleton website](http://getskeleton.com/), and choose "Download" to download the ZIP file. Unzip this and copy the skeleton.css and normalize.css files into a new directory.
Make a copy of our [html-skeleton.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/html-skeleton.html) file and save it in the same directory as the skeleton and normalize CSS.
Include the skeleton and normalize CSS in the HTML page, by adding the following to its head:
```html
<link href="normalize.css" rel="stylesheet" />
<link href="skeleton.css" rel="stylesheet" />
```
Skeleton includes more than a grid system β it also contains CSS for typography and other page elements that you can use as a starting point. We'll leave these at the defaults for now, however β it's the grid we are really interested in here.
> **Note:** [Normalize](https://necolas.github.io/normalize.css/) is a really useful little CSS library written by Nicolas Gallagher, which automatically does some useful basic layout fixes and makes default element styling more consistent across browsers.
We will use similar HTML to our earlier example. Add the following into your HTML body:
```html
<div class="container">
<div class="row">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
<div class="col">4</div>
<div class="col">5</div>
<div class="col">6</div>
<div class="col">7</div>
<div class="col">8</div>
<div class="col">9</div>
<div class="col">10</div>
<div class="col">11</div>
<div class="col">12</div>
</div>
<div class="row">
<div class="col">13</div>
<div class="col">14</div>
<div class="col">15</div>
<div class="col">16</div>
</div>
</div>
```
To start using Skeleton we need to give the wrapper {{htmlelement("div")}} a class of `container` β this is already included in our HTML. This centers the content with a maximum width of 960 pixels. You can see how the boxes now never become wider than 960 pixels.
You can take a look in the skeleton.css file to see the CSS that is used when we apply this class. The `<div>` is centered using `auto` left and right margins, and a padding of 20 pixels is applied left and right. Skeleton also sets the {{cssxref("box-sizing")}} property to `border-box` like we did earlier, so the padding and borders of this element will be included in the total width.
```css
.container {
position: relative;
width: 100%;
max-width: 960px;
margin: 0 auto;
padding: 0 20px;
box-sizing: border-box;
}
```
Elements can only be part of the grid if they are inside a row, so as with our earlier example we need an additional `<div>` or other element with a class of `row` nested between the content `<div>` elements and the container `<div>`. We've done this already as well.
Now let's lay out the container boxes. Skeleton is based on a 12 column grid. The top line boxes all need classes of `one column` to make them span one column.
Add these now, as shown in the following snippet:
```html
<div class="container">
<div class="row">
<div class="one column">1</div>
<div class="one column">2</div>
<div class="one column">3</div>
/* and so on */
</div>
</div>
```
Next, give the containers on the second row classes explaining the number of columns they should span, like so:
```html
<div class="row">
<div class="one column">13</div>
<div class="six columns">14</div>
<div class="three columns">15</div>
<div class="two columns">16</div>
</div>
```
Try saving your HTML file and loading it in your browser to see the effect.
> **Note:** If you are having trouble getting this example to work, try widening the window you're using to view it (the grid won't be displayed as described here if the window is too narrow). If that doesn't work, try comparing it to our [html-skeleton-finished.html](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/html-skeleton-finished.html) file (see it [running live](https://mdn.github.io/learning-area/css/css-layout/grids/html-skeleton-finished.html) also).
If you look in the skeleton.css file you can see how this works. For example, Skeleton has the following defined to style elements with "three columns" classes added to them.
```css
.three.columns {
width: 22%;
}
```
All Skeleton (or any other grid framework) is doing is setting up predefined classes that you can use by adding them to your markup. It's exactly the same as if you did the work of calculating these percentages yourself.
As you can see, we need to write very little CSS when using Skeleton. It deals with all of the floating for us when we add classes to our markup. It is this ability to hand responsibility for layout over to something else that made using a framework for a grid system a compelling choice! However these days, with CSS Grid Layout, many developers are moving away from these frameworks to use the inbuilt native grid that CSS provides.
## Summary
You now understand how various grid systems are created, which will be useful in working with older sites and in understanding the difference between the native grid of CSS Grid Layout and these older systems.
{{PreviousMenuNext("Learn/CSS/CSS_layout/Media_queries", "Learn/CSS/CSS_layout/Supporting_Older_Browsers", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/grids/index.md | ---
title: Grids
slug: Learn/CSS/CSS_layout/Grids
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Flexbox", "Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout")}}
[CSS grid layout](/en-US/docs/Web/CSS/CSS_grid_layout) is a two-dimensional layout system for the web. It lets you organize content into rows and columns and offers many features to simplify the creation of complex layouts. This article will explain all you need to know to get started with grid layout.
<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">Introduction to CSS</a> and
<a href="/en-US/docs/Learn/CSS/Building_blocks">Styling boxes</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand the fundamental concepts of grid layout as well as how to
implement it with CSS Grid.
</td>
</tr>
</tbody>
</table>
## What is grid layout?
A grid is a collection of horizontal and vertical lines creating a pattern against which we can line up our design elements. They help us to create layouts in which our elements won't jump around or change width as we move from page to page, providing greater consistency on our websites.
A grid will typically have **columns**, **rows**, and then gaps between each row and column. The gaps are commonly referred to as **gutters**.

## Creating your grid in CSS
Having decided on the grid that your design needs, you can use CSS Grid Layout to create it. We'll look at the basic features of Grid Layout first and then explore how to create a simple grid system for your project.
The following video provides a nice visual explanation of using CSS Grid:
{{EmbedYouTube("KOvGeFUHAC0")}}
### Defining a grid
Let's try out grid layouts with the help of an example. Download and open [the starting point file](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/0-starting-point.html) in your text editor and browser (you can also [see it live here](https://mdn.github.io/learning-area/css/css-layout/grids/0-starting-point.html)). You will see an example with a container, which has some child items. By default, these items are displayed in a normal flow, causing them to appear one below the other. For the initial part of this lesson, we'll be using this file to see how its grid behaves.
Similar to how you define flexbox, you define a grid layout by setting the value of the {{cssxref("display")}} property to `grid`. As in the case of flexbox, the `display: grid` property transforms all the direct children of the container into grid items. Add the following CSS to your file:
```css
.container {
display: grid;
}
```
Unlike Flexbox, the items will not immediately look any different. Declaring `display: grid` gives you a one column grid, so your items will continue to display one below the other as they do in normal flow.
To see something that looks more grid-like, we'll need to add some columns to the grid. Let's add three 200-pixel columns. You can use any length unit or percentage to create these column tracks.
```css
.container {
display: grid;
grid-template-columns: 200px 200px 200px;
}
```
Add the second declaration to your CSS rule, then reload the page. You should see that the items have rearranged themselves such that there's one in each cell of the grid.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.container > div {
border-radius: 5px;
padding: 10px;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
}
```
```html hidden
<div class="container">
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
<div>Five</div>
<div>Six</div>
<div>Seven</div>
</div>
```
{{ EmbedLiveSample('Defining_a_grid', '100%', 200) }}
### Flexible grids with the fr unit
In addition to creating grids using lengths and percentages, we can use [`fr`](/en-US/docs/Web/CSS/flex_value). The `fr` unit represents one fraction of the available space in the grid container to flexibly size grid rows and columns.
Change your track listing to the following definition, creating three `1fr` tracks:
```css
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
```
You now have flexible tracks. The `fr` unit distributes space proportionally. You can specify different positive values for your tracks like so:
```css
.container {
display: grid;
grid-template-columns: 2fr 1fr 1fr;
}
```
The first track gets `2fr` of the available space and the other two tracks get `1fr`, making the first track larger. You can mix `fr` units with fixed length units. In this case, the space needed for the fixed tracks is used up first before the remaining space is distributed to the other tracks.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.container > div {
border-radius: 5px;
padding: 10px;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
}
```
```html hidden
<div class="container">
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
<div>Five</div>
<div>Six</div>
<div>Seven</div>
</div>
```
{{ EmbedLiveSample('Flexible_grids_with_the_fr_unit', '100%', 200) }}
> **Note:** The `fr` unit distributes _available_ space, not _all_ space. Therefore, if one of your tracks has something large inside it, there will be less free space to share.
### Gaps between tracks
To create gaps between tracks, we use the properties:
- {{cssxref("column-gap")}} for gaps between columns
- {{cssxref("row-gap")}} for gaps between rows
- {{cssxref("gap")}} as a shorthand for both
```css
.container {
display: grid;
grid-template-columns: 2fr 1fr 1fr;
gap: 20px;
}
```
These gaps can be any length unit or percentage, but not an `fr` unit.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.container > div {
border-radius: 5px;
padding: 10px;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
}
```
```html hidden
<div class="container">
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
<div>Five</div>
<div>Six</div>
<div>Seven</div>
</div>
```
{{ EmbedLiveSample('Gaps_between_tracks', '100%', 250) }}
> **Note:** The `gap` properties (`column-gap`, `row-gap` and `gap`) used to be prefixed by `grid-`. The spec has changed but the prefixed versions will be maintained as an alias. To be on the safe side and make your code more bulletproof, you can add both properties:
>
> ```css
> .container {
> display: grid;
> grid-template-columns: 2fr 1fr 1fr;
> grid-gap: 20px;
> gap: 20px;
> }
> ```
### Repeating track listings
You can repeat all or merely a section of your track listing using the CSS `repeat()` function.
Change your track listing to the following:
```css
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
```
You'll now get three `1fr` tracks just as before. The first value passed to the `repeat()` function specifies the number of times you want the listing to repeat, while the second value is a track listing, which may be one or more tracks that you want to repeat.
### Implicit and explicit grids
Up to this point, we've specified only column tracks, but rows are automatically created to hold the content. This concept highlights the distinction between explicit and implicit grids.
Here's a bit more about the difference between the two types of grids:
- **Explicit grid** is created using `grid-template-columns` or `grid-template-rows`.
- **Implicit grid** extends the defined explicit grid when content is placed outside of that grid, such as into the rows by drawing additional grid lines.
By default, tracks created in the implicit grid are `auto` sized, which in general means that they're large enough to contain their content. If you wish to give implicit grid tracks a size, you can use the {{cssxref("grid-auto-rows")}} and {{cssxref("grid-auto-columns")}} properties. If you add `grid-auto-rows` with a value of `100px` to your CSS, you'll see that those created rows are now 100 pixels tall.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.container > div {
border-radius: 5px;
padding: 10px;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
}
```
```html hidden
<div class="container">
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
<div>Five</div>
<div>Six</div>
<div>Seven</div>
</div>
```
```css
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 100px;
gap: 20px;
}
```
{{ EmbedLiveSample('Implicit_and_explicit_grids', '100%', 400) }}
### The minmax() function
Our 100-pixel tall tracks won't be very useful if we add content into those tracks that is taller than 100 pixels, in which case it would cause an overflow. It might be better to have tracks that are _at least_ 100 pixels tall and can still expand if more content becomes added. A fairly basic fact about the web is that you never really know how tall something is going to be β additional content or larger font sizes can cause problems with designs that attempt to be pixel perfect in every dimension.
The {{cssxref("minmax", "minmax()")}} function lets us set a minimum and maximum size for a track, for example, `minmax(100px, auto)`. The minimum size is 100 pixels, but the maximum is `auto`, which will expand to accommodate more content. Try changing `grid-auto-rows` to use a minmax value:
```css
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: minmax(100px, auto);
gap: 20px;
}
```
If you add extra content, you'll see that the track expands to allow it to fit. Note that the expansion happens right along the row.
### As many columns as will fit
We can combine some of the lessons we've learned about track listing, repeat notation, and {{cssxref("minmax", "minmax()")}} to create a useful pattern. Sometimes it's helpful to be able to ask grid to create as many columns as will fit into the container. We do this by setting the value of `grid-template-columns` using the {{cssxref("repeat", "repeat()")}} function, but instead of passing in a number, pass in the keyword `auto-fit`. For the second parameter of the function we use `minmax()` with a minimum value equal to the minimum track size that we would like to have and a maximum of `1fr`.
Try this in your file now using the CSS below:
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.container > div {
border-radius: 5px;
padding: 10px;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
}
```
```html hidden
<div class="container">
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
<div>Five</div>
<div>Six</div>
<div>Seven</div>
</div>
```
```css
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-auto-rows: minmax(100px, auto);
gap: 20px;
}
```
{{ EmbedLiveSample('As_many_columns_as_will_fit', '100%', 400) }}
This works because grid is creating as many 200-pixel columns as will fit into the container, then sharing whatever space is leftover among all the columns. The maximum is `1fr` which, as we already know, distributes space evenly between tracks.
## Line-based placement
We now move on from creating a grid to placing things on the grid. Our grid always has lines β these are numbered beginning with 1 and relate to the [writing mode](/en-US/docs/Web/CSS/CSS_writing_modes) of the document. For example, column line 1 in English (written left-to-right) would be on the left-hand side of the grid and row line 1 at the top, while in Arabic (written right-to-left), column line 1 would be on the right-hand side.
To position items along these lines, we can specify the start and end lines of the grid area where an item should be placed. There are four properties we can use to do this:
- {{cssxref("grid-column-start")}}
- {{cssxref("grid-column-end")}}
- {{cssxref("grid-row-start")}}
- {{cssxref("grid-row-end")}}
These properties accept line numbers as their values, so we can specify that an item should start on line 1 and end on line 3, for example.
Alternatively, you can also use shorthand properties that let you specify the start and end lines simultaneously, separated by a forward slash `/`:
- {{cssxref("grid-column")}} shorthand for `grid-column-start` and `grid-column-end`
- {{cssxref("grid-row")}} shorthand for `grid-row-start` and `grid-row-end`
To see this in action, download the [line-based placement starting point file](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/8-placement-starting-point.html) or [see it live here](https://mdn.github.io/learning-area/css/css-layout/grids/8-placement-starting-point.html). It has a defined grid and a simple article outlined. You can see that _auto-placement_ is placing each item into its own cell in the grid.
Let's arrange all of the elements for our site by using the grid lines. Add the following rules to the bottom of your CSS:
```css
header {
grid-column: 1 / 3;
grid-row: 1;
}
article {
grid-column: 2;
grid-row: 2;
}
aside {
grid-column: 1;
grid-row: 2;
}
footer {
grid-column: 1 / 3;
grid-row: 3;
}
```
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.container {
display: grid;
grid-template-columns: 1fr 3fr;
gap: 20px;
}
header,
footer {
border-radius: 5px;
padding: 10px;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
}
aside {
border-right: 1px solid #999;
}
```
```html hidden
<div class="container">
<header>This is my lovely blog</header>
<article>
<h1>My article</h1>
<p>
Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor
imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus
massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra
egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada
et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac
imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis
ornare egestas augue ut luctus. Proin blandit quam nec lacus varius
commodo et a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies
lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra
quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis
natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
</article>
<aside>
<h2>Other things</h2>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est.
</p>
</aside>
<footer>Contact [email protected]</footer>
</div>
```
{{ EmbedLiveSample('Line-based_placement', '100%', 550) }}
> **Note:** You can also use the value `-1` to target the end column or row line, then count inwards from the end using negative values. Note also that lines count always from the edges of the explicit grid, not the [implicit grid](/en-US/docs/Glossary/Grid).
## Positioning with grid-template-areas
An alternative way to arrange items on your grid is to use the {{cssxref("grid-template-areas")}} property and give the various elements of your design a name.
Remove the line-based positioning from the last example (or re-download the file to have a fresh starting point) and add the following CSS.
```css
.container {
display: grid;
grid-template-areas:
"header header"
"sidebar content"
"footer footer";
grid-template-columns: 1fr 3fr;
gap: 20px;
}
header {
grid-area: header;
}
article {
grid-area: content;
}
aside {
grid-area: sidebar;
}
footer {
grid-area: footer;
}
```
Reload the page and you will see that your items have been placed just as before without us needing to use any line numbers!
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
header,
footer {
border-radius: 5px;
padding: 10px;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
}
aside {
border-right: 1px solid #999;
}
```
```html hidden
<div class="container">
<header>This is my lovely blog</header>
<article>
<h1>My article</h1>
<p>
Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor
imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus
massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra
egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada
et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac
imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis
ornare egestas augue ut luctus. Proin blandit quam nec lacus varius
commodo et a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies
lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra
quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis
natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
</article>
<aside>
<h2>Other things</h2>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est.
</p>
</aside>
<footer>Contact [email protected]</footer>
</div>
```
{{ EmbedLiveSample('Positioning_with_grid-template-areas', '100%', 550) }}
The rules for `grid-template-areas` are as follows:
- You need to have every cell of the grid filled.
- To span across two cells, repeat the name.
- To leave a cell empty, use a `.` (period).
- Areas must be rectangular β for example, you can't have an L-shaped area.
- Areas can't be repeated in different locations.
You can play around with our layout, changing the footer to only sit underneath the article and the sidebar to span all the way down. This is a very nice way to describe a layout because it's clear just from looking at the CSS to know exactly what's happening.
## Nesting grids and subgrid
It's possible to nest a grid within another grid, creating a ["subgrid"](/en-US/docs/Web/CSS/CSS_grid_layout/Subgrid).
You can do this by setting the `display: grid` property on a grid item.
Let's expand on the previous example by adding a container for articles and using a nested grid to control the layout of multiple articles.
While we're using only one column in the nested grid, we can define the rows to be split in a 2:1:1 ratio by using the `grid-template-rows` property.
This approach allows us to create a layout where one article at the top of the page has a large display, while the others have a smaller, preview-like layout.
```html hidden live-sample___nesting-grids
<div class="container">
<header>This is my lovely blog</header>
<div class="articles">
<article>
<h1>Darmok and Jalad had a picnic at Tanagra</h1>
<p>
Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras
porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed
auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet
orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac
ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat.
Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros
pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam
nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum
sapien.
</p>
<button>Read more</button>
</article>
<article>
<h1>Temba held his arms wide</h1>
<p>
Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras
porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed
auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet
orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac
ornare ex malesuada et ...
</p>
<button>Read more</button>
</article>
<article>
<h1>Gilgamesh, a king, at Uruk</h1>
<p>
Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras
porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed
auctor cursus massa at porta ...
</p>
<button>Read more</button>
</article>
</div>
<aside>
<h2>Other things</h2>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est.
</p>
<button>Read more</button>
</aside>
<footer>Contact [email protected]</footer>
</div>
```
```css hidden live-sample___nesting-grids
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
header,
footer {
border-radius: 5px;
padding: 10px;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
}
header {
grid-area: header;
}
aside {
border-right: 1px solid #999;
grid-area: sidebar;
padding-right: 10px;
font-size: 0.8em;
}
footer {
grid-area: footer;
}
.container {
display: grid;
grid-template-areas:
"header header"
"sidebar content"
"footer footer";
grid-template-columns: 1fr 3fr;
gap: 20px;
}
```
```css live-sample___nesting-grids
.articles {
display: grid;
grid-template-rows: 2fr 1fr 1fr;
gap: inherit;
}
article {
padding: 10px;
border: 2px solid rgb(79 185 227);
border-radius: 5px;
}
```
{{EmbedLiveSample('nesting-grids', '100%', 1100)}}
To make it easier to work with layouts in nested grids, you can use `subgrid` on `grid-template-rows` and `grid-template-columns` properties. This allows you to leverage the tracks defined in the parent grid.
In the following example, we're using [line-based placement](#line-based_placement), enabling the nested grid to span multiple columns and rows of the parent grid.
We've added `subgrid` to inherit the parent grid's column tracks while adding a different layout for the rows within the nested grid.
```css hidden live-sample___subgrid
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.container div {
border-radius: 5px;
padding: 10px;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
}
```
```html live-sample___subgrid
<div class="container">
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
<div id="subgrid">
<div>Five</div>
<div>Six</div>
<div>Seven</div>
<div>Eight</div>
</div>
<div>Nine</div>
<div>Ten</div>
</div>
```
```css live-sample___subgrid
.container {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(1, 1fr);
gap: 10px;
}
#subgrid {
grid-column: 1 / 4;
grid-row: 2 / 4;
display: grid;
gap: inherit;
grid-template-columns: subgrid;
grid-template-rows: 2fr 1fr;
}
```
{{ EmbedLiveSample('subgrid', '100%', 300) }}
## Grid frameworks
Numerous grid frameworks are available, offering a 12 or 16-column grid, to help with laying out your content.
The good news is that you probably won't need any third-party frameworks to help you create grid-based layouts β grid functionality is already included in the specification and is supported by most modern browsers.
[Download the starting point file](https://github.com/mdn/learning-area/blob/main/css/css-layout/grids/11-grid-system-starting-point.html). This has a container with a 12-column grid defined and the same markup we used in the previous two examples. We can now use line-based placement to place our content on the 12-column grid.
```css
header {
grid-column: 1 / 13;
grid-row: 1;
}
article {
grid-column: 4 / 13;
grid-row: 2;
}
aside {
grid-column: 1 / 4;
grid-row: 2;
}
footer {
grid-column: 1 / 13;
grid-row: 3;
}
```
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.container {
display: grid;
grid-template-columns: repeat(12, minmax(0, 1fr));
gap: 20px;
}
header,
footer {
border-radius: 5px;
padding: 10px;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
}
aside {
border-right: 1px solid #999;
}
```
```html hidden
<div class="container">
<header>This is my lovely blog</header>
<article>
<h1>My article</h1>
<p>
Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor
imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus
massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra
egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada
et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac
imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis
ornare egestas augue ut luctus. Proin blandit quam nec lacus varius
commodo et a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies
lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra
quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis
natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
</article>
<aside>
<h2>Other things</h2>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est.
</p>
</aside>
<footer>Contact [email protected]</footer>
</div>
```
{{ EmbedLiveSample('Grid frameworks in CSS Grid', '100%', 600) }}
If you use the [Firefox Grid Inspector](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_grid_layouts/index.html) to overlay the grid lines on your design, you can see how our 12-column grid works.

## 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: Grid](/en-US/docs/Learn/CSS/CSS_layout/Grid_skills).
## Summary
In this overview, we've toured the main features of CSS Grid Layout. You should be able to start using it in your designs. To dig further into the specification, read our guides on Grid Layout, which can be found below.
## See also
- A [list of guides](/en-US/docs/Web/CSS/CSS_grid_layout#guides) related to the CSS grid layout
- [Subgrid](/en-US/docs/Web/CSS/CSS_grid_layout/Subgrid) guide
- [CSS grid inspector: Examine grid layouts](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_grid_layouts/index.html) on firefox-source-docs
- [A complete guide to CSS grid](https://css-tricks.com/snippets/css/complete-guide-grid/), a visual guide on CSS-Tricks (2023)
- [Grid Garden](https://cssgridgarden.com/), an educational game to learn and better understand the basics of grid on cssgridgarden.com
{{PreviousMenuNext("Learn/CSS/CSS_layout/Flexbox", "Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/multiple-column_layout/index.md | ---
title: Multiple-column layout
slug: Learn/CSS/CSS_layout/Multiple-column_Layout
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Positioning", "Learn/CSS/CSS_layout/Responsive_Design", "Learn/CSS/CSS_layout")}}
The multiple-column layout specification provides you with a method for laying content out in columns, as you might see in a newspaper. This article explains how to use this feature.
<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">Introduction to CSS</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to create multiple-column layout on webpages, such as you
might find in a newspaper.
</td>
</tr>
</tbody>
</table>
## A basic example
Let's explore how to use multiple-column layout β often referred to as _multicol_. You can follow along by [downloading the multicol starting point file](https://github.com/mdn/learning-area/blob/main/css/css-layout/multicol/0-starting-point.html) and adding the CSS into the appropriate places. At the bottom of the section you can see an example of what the final code should look like.
### A three-column layout
Our starting point file contains some very simple HTML: a wrapper with a class of `container`, inside of which is a heading and some paragraphs.
The {{htmlelement("div")}} with a class of container will become our multicol container. We enable multicol by using one of two properties: {{cssxref("column-count")}} or {{cssxref("column-width")}}. The `column-count` property takes a number as its value and creates that number of columns. If you add the following CSS to your stylesheet and reload the page, you'll get three columns:
```css
.container {
column-count: 3;
}
```
The columns that you create have flexible widths β the browser works out how much space to assign each column.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
```
```html hidden
<div class="container">
<h1>Simple multicol example</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at
ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer
ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur
vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus.
Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus
sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus.
Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis,
eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies
lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
</div>
```
{{ EmbedLiveSample('A_three-column_layout', '100%', 400) }}
### Setting column-width
Change your CSS to use `column-width` as follows:
```css
.container {
column-width: 200px;
}
```
The browser will now give you as many columns as it can of the size that you specify; any remaining space is then shared between the existing columns. This means that you won't get exactly the width that you specify unless your container is exactly divisible by that width.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
```
```html hidden
<div class="container">
<h1>Simple multicol example</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at
ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer
ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur
vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus.
Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus
sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus.
Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis,
eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies
lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
</div>
```
{{ EmbedLiveSample('Setting_column-width', '100%', 400) }}
## Styling the columns
The columns created by multicol cannot be styled individually. There's no way to make one column bigger than other columns or to change the background or text color of a single column. You have two opportunities to change the way that columns display:
- Changing the size of the gap between columns using the {{cssxref("column-gap")}}.
- Adding a rule between columns with {{cssxref("column-rule")}}.
Using your example above, change the size of the gap by adding a `column-gap` property. You can play around with different values β the property accepts any length unit.
Now add a rule between the columns with `column-rule`. In a similar way to the {{cssxref("border")}} property that you encountered in previous lessons, `column-rule` is a shorthand for {{cssxref("column-rule-color")}}, {{cssxref("column-rule-style")}}, and {{cssxref("column-rule-width")}}, and accepts the same values as `border`.
```css
.container {
column-count: 3;
column-gap: 20px;
column-rule: 4px dotted rgb(79 185 227);
}
```
Try adding rules of different styles and colors.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
```
```html hidden
<div class="container">
<h1>Simple multicol example</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at
ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer
ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur
vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus.
Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus
sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus.
Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis,
eget fermentum sapien.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies
lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
</div>
```
{{ EmbedLiveSample('Styling_the_columns', '100%', 400) }}
Something to take note of is that the rule doesn't take up any width of its own. It lies across the gap you created with `column-gap`. To make more space on either side of the rule, you'll need to increase the `column-gap` size.
## Spanning columns
You can cause an element to span across all the columns. In this case, the content breaks where the spanning element's introduced and then continues below the element, creating a new set of columns. To cause an element to span all the columns, specify the value of `all` for the {{cssxref("column-span")}} property.
> **Note:** It isn't possible to cause an element to span just _some_ columns. The property can only have the values of `none` (which is the default) or `all`.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
.container {
column-count: 3;
column-gap: 20px;
column-rule: 4px dotted rgb(79 185 227);
}
h2 {
column-span: all;
background-color: rgb(79 185 227);
color: white;
padding: 0.5em;
}
```
```html hidden
<div class="container">
<h1>Simple multicol example</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate.
Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
<h2>Spanning subhead</h2>
Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse
ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit
quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p>
<p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique
elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit
cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis
dis parturient montes, nascetur ridiculus mus.</p>
</div>
```
{{ EmbedLiveSample('Spanning_columns', '100%', 550) }}
## Columns and fragmentation
The content of a multi-column layout is fragmented. It essentially behaves the same way as content behaves in paged media, such as when you print a webpage. When you turn your content into a multicol container, it fragments into columns. In order for the content to do this, it must _break_.
### Fragmented boxes
Sometimes, this breaking will happen in places that lead to a poor reading experience. In the example below, I have used multicol to lay out a series of boxes, each of which has a heading and some text inside. The heading becomes separated from the text if the columns fragment between the two.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
```
```html
<div class="container">
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
</div>
```
```css
.container {
column-width: 250px;
column-gap: 20px;
}
.card {
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
padding: 10px;
margin: 0 0 1em 0;
}
```
{{ EmbedLiveSample('Fragmented_boxes', '100%', 1000) }}
### Setting break-inside
To control this behavior, we can use properties from the [CSS Fragmentation](/en-US/docs/Web/CSS/CSS_fragmentation) specification. This specification gives us properties to control the breaking of content in multicol and in paged media. For example, by adding the property {{cssxref("break-inside")}} with a value of `avoid` to the rules for `.card`. This is the container of the heading and text, so we don't want it fragmented.
```css
.card {
break-inside: avoid;
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
padding: 10px;
margin: 0 0 1em 0;
}
```
The addition of this property causes the boxes to stay in one pieceβthey now do not _fragment_ across the columns.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 2em auto;
font:
0.9em/1.2 Arial,
Helvetica,
sans-serif;
}
```
```html hidden
<div class="container">
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
<div class="card">
<h2>I am the heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc,
at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
</p>
</div>
</div>
```
```css hidden
.container {
column-width: 250px;
column-gap: 20px;
}
```
{{ EmbedLiveSample('Setting_break-inside', '100%', 1100) }}
## 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: Multicol](/en-US/docs/Learn/CSS/CSS_layout/Multicol_skills).
## Summary
You now know how to use the basic features of multiple-column layout, another tool at your disposal when choosing a layout method for the designs you're building.
## See also
- [CSS Fragmentation](/en-US/docs/Web/CSS/CSS_fragmentation)
- [Using multi-column layouts](/en-US/docs/Web/CSS/CSS_multicol_layout/Using_multicol_layouts)
{{PreviousMenuNext("Learn/CSS/CSS_layout/Positioning", "Learn/CSS/CSS_layout/Responsive_Design", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css/css_layout | data/mdn-content/files/en-us/learn/css/css_layout/introduction/index.md | ---
title: Introduction to CSS layout
slug: Learn/CSS/CSS_layout/Introduction
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/CSS/CSS_layout/Normal_Flow", "Learn/CSS/CSS_layout")}}
This article will recap some of the CSS layout features we've already touched upon in previous modules, such as different {{cssxref("display")}} values, as well as introduce some of the concepts we'll be covering throughout this module.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
The basics of HTML (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">Introduction to CSS</a>.)
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To give you an overview of CSS page layout techniques. Each technique
can be learned in greater detail in subsequent tutorials.
</td>
</tr>
</tbody>
</table>
CSS page layout techniques allow us to take elements contained in a web page and control where they're positioned relative to the following factors: their default position in normal layout flow, the other elements around them, their parent container, and the main viewport/window. The page layout techniques we'll be covering in more detail in this module are:
- Normal flow
- The {{cssxref("display")}} property
- Flexbox
- Grid
- Floats
- Positioning
- Table layout
- Multiple-column layout
Each technique has its uses, advantages, and disadvantages. No technique is designed to be used in isolation. By understanding what each layout method is designed for you'll be in a good position to understand which method is most appropriate for each task.
## Normal flow
Normal flow is how the browser lays out HTML pages by default when you do nothing to control page layout. Let's look at a quick HTML example:
```html
<p>I love my cat.</p>
<ul>
<li>Buy cat food</li>
<li>Exercise</li>
<li>Cheer up friend</li>
</ul>
<p>The end!</p>
```
By default, the browser will display this code as follows:
{{ EmbedLiveSample('Normal_flow', '100%', 200) }}
Note how the HTML is displayed in the exact order in which it appears in the source code, with elements stacked on top of one another β the first paragraph, followed by the unordered list, followed by the second paragraph.
The elements that appear one below the other are described as **block** elements, in contrast to **inline** elements, which appear beside one another like the individual words in a paragraph.
> **Note:** The direction in which block element contents are laid out is described as the Block Direction. The Block Direction runs vertically in a language such as English, which has a horizontal writing mode. It would run horizontally in any language with a Vertical Writing Mode, such as Japanese. The corresponding Inline Direction is the direction in which inline contents (such as a sentence) would run.
For many of the elements on your page, the normal flow will create exactly the layout you need. However, for more complex layouts you will need to alter this default behavior using some of the tools available to you in CSS. Starting with a well-structured HTML document is very important because you can then work with the way things are laid out by default rather than fighting against it.
The methods that can change how elements are laid out in CSS are:
- **The {{cssxref("display")}} property** β Standard values such as `block`, `inline` or `inline-block` can change how elements behave in normal flow, for example, by making a block-level element behave like an inline-level element (see [Types of CSS boxes](/en-US/docs/Learn/CSS/Building_blocks/The_box_model#block_and_inline_boxes) for more information). We also have entire layout methods that are enabled via specific `display` values, for example, [CSS Grid](/en-US/docs/Learn/CSS/CSS_layout/Grids) and [Flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox), which alter how child elements are laid out inside their parents.
- **Floats** β Applying a {{cssxref("float")}} value such as `left` can cause block-level elements to wrap along one side of an element, like the way images sometimes have text floating around them in magazine layouts.
- **The {{cssxref("position")}} property** β Allows you to precisely control the placement of boxes inside other boxes. `static` positioning is the default in normal flow, but you can cause elements to be laid out differently using other values, for example, as fixed to the top of the browser viewport.
- **Table layout** β Features designed for styling parts of an HTML table can be used on non-table elements using `display: table` and associated properties.
- **Multi-column layout** β The [Multi-column layout](/en-US/docs/Web/CSS/CSS_multicol_layout) properties can cause the content of a block to lay out in columns, as you might see in a newspaper.
## The display property
The main methods for achieving page layout in CSS all involve specifying values for the `display` property. This property allows us to change the default way something displays. Everything in normal flow has a default value for `display`; i.e., a default way that elements are set to behave. For example, the fact that paragraphs in English display one below the other is because they are styled with `display: block`. If you create a link around some text inside a paragraph, that link remains inline with the rest of the text, and doesn't break onto a new line. This is because the {{htmlelement("a")}} element is `display: inline` by default.
You can change this default display behavior. For example, the {{htmlelement("li")}} element is `display: block` by default, meaning that list items display one below the other in our English document. If we were to change the display value to `inline` they would display next to each other, as words would do in a sentence. The fact that you can change the value of `display` for any element means that you can pick HTML elements for their semantic meaning without being concerned about how they will look. The way they look is something that you can change.
In addition to being able to change the default presentation by turning an item from `block` to `inline` and vice versa, there are some more involved layout methods that start out as a value of `display`. However, when using these you will generally need to invoke additional properties. The two values most important for our discussion of layout are `display: flex` and `display: grid`.
## Flexbox
Flexbox is the short name for the [Flexible Box Layout](/en-US/docs/Web/CSS/CSS_flexible_box_layout) CSS module, designed to make it easy for us to lay things out in one dimension β either as a row or as a column. To use flexbox, you apply `display: flex` to the parent element of the elements you want to lay out; all its direct children then become _flex items_. We can see this in a simple example.
### Setting display: flex
The HTML markup below gives us a containing element with a class of `wrapper`, inside of which are three {{htmlelement("div")}} elements. By default these would display as block elements, that is, below one another in our English language document.
However, if we add `display: flex` to the parent, the three items now arrange themselves into columns. This is due to them becoming _flex items_ and being affected by some initial values that flexbox sets on the flex container. They are displayed in a row because the property {{cssxref("flex-direction")}} of the parent element has an initial value of `row`. They all appear to stretch in height because the property {{cssxref("align-items")}} of their parent element has an initial value of `stretch`. This means that the items stretch to the height of the flex container, which in this case is defined by the tallest item. The items all line up at the start of the container, leaving any extra space at the end of the row.
```css hidden
* {
box-sizing: border-box;
}
.wrapper > div {
border-radius: 5px;
background-color: rgb(207 232 220);
padding: 1em;
}
```
```css
.wrapper {
display: flex;
}
```
```html
<div class="wrapper">
<div class="box1">One</div>
<div class="box2">Two</div>
<div class="box3">Three</div>
</div>
```
{{ EmbedLiveSample('Setting_display_flex', '300', '200') }}
### Setting the flex property
In addition to properties that can be applied to a _flex container_, there are also properties that can be applied to _flex items_. These properties, among other things, can change the way that items _flex_, enabling them to expand or contract according to available space.
As a simple example, we can add the {{cssxref("flex")}} property to all of our child items, and give it a value of `1`. This will cause all of the items to grow and fill the container, rather than leaving space at the end. If there is more space then the items will become wider; if there is less space they will become narrower. In addition, if you add another element to the markup, the other items will all become smaller to make space for it; the items all together continue taking up all the space.
```css hidden
* {
box-sizing: border-box;
}
.wrapper > div {
border-radius: 5px;
background-color: rgb(207 232 220);
padding: 1em;
}
```
```css
.wrapper {
display: flex;
}
.wrapper > div {
flex: 1;
}
```
```html
<div class="wrapper">
<div class="box1">One</div>
<div class="box2">Two</div>
<div class="box3">Three</div>
</div>
```
{{ EmbedLiveSample('Setting_the_flex_property', '300', '200') }}
> **Note:** This has been a very short introduction to what is possible in Flexbox. To find out more, see our [Flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox) article.
## Grid Layout
While flexbox is designed for one-dimensional layout, Grid Layout is designed for two dimensions β lining things up in rows and columns.
### Setting display: grid
Similar to flexbox, we enable Grid Layout with its specific display value β `display: grid`. The below example uses similar markup to the flex example, with a container and some child elements. In addition to using `display: grid`, we also define some row and column _tracks_ for the parent using the {{cssxref("grid-template-rows")}} and {{cssxref("grid-template-columns")}} properties respectively. We've defined three columns, each of `1fr`, as well as two rows of `100px`. We don't need to put any rules on the child elements; they're automatically placed into the cells our grid's created.
```css hidden
* {
box-sizing: border-box;
}
.wrapper > div {
border-radius: 5px;
background-color: rgb(207 232 220);
padding: 1em;
}
```
```css
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 100px 100px;
gap: 10px;
}
```
```html
<div class="wrapper">
<div class="box1">One</div>
<div class="box2">Two</div>
<div class="box3">Three</div>
<div class="box4">Four</div>
<div class="box5">Five</div>
<div class="box6">Six</div>
</div>
```
{{ EmbedLiveSample('Setting_display_grid', '300', '330') }}
### Placing items on the grid
Once you have a grid, you can explicitly place your items on it, rather than relying on the auto-placement behavior seen above. In the next example below, we've defined the same grid, but this time with three child items. We've set the start and end line of each item using the {{cssxref("grid-column")}} and {{cssxref("grid-row")}} properties. This causes the items to span multiple tracks.
```css hidden
* {
box-sizing: border-box;
}
.wrapper > div {
border-radius: 5px;
background-color: rgb(207 232 220);
padding: 1em;
}
```
```css
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 100px 100px;
gap: 10px;
}
.box1 {
grid-column: 2 / 4;
grid-row: 1;
}
.box2 {
grid-column: 1;
grid-row: 1 / 3;
}
.box3 {
grid-row: 2;
grid-column: 3;
}
```
```html
<div class="wrapper">
<div class="box1">One</div>
<div class="box2">Two</div>
<div class="box3">Three</div>
</div>
```
{{ EmbedLiveSample('Placing_items_on_the_grid', '300', '330') }}
> **Note:** These two examples reveal just a small sample of the power of Grid layout. To learn more, see our [Grid Layout](/en-US/docs/Learn/CSS/CSS_layout/Grids) article.
The rest of this guide covers other layout methods that are less important for the main layout of your page, but still help to achieve specific tasks. By understanding the nature of each layout task you will soon find that when you look at a particular component of your design, the type of layout most suitable for it will often be clear.
## Floats
Floating an element changes the behavior of that element and the block level elements that follow it in normal flow. The floated element is moved to the left or right and removed from normal flow, and the surrounding content _floats_ around it.
The {{cssxref("float")}} property has four possible values:
- `left` β Floats the element to the left.
- `right` β Floats the element to the right.
- `none` β Specifies no floating at all. This is the default value.
- `inherit` β Specifies that the value of the `float` property should be inherited from the element's parent element.
In the example below, we float a `<div>` left and give it a {{cssxref("margin")}} on the right to push the surrounding text away from it. This gives us the effect of text wrapped around the boxed element, and is most of what you need to know about floats as used in modern web design.
```css hidden
body {
width: 90%;
max-width: 900px;
margin: 0 auto;
}
p {
line-height: 2;
word-spacing: 0.1rem;
}
.box {
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
padding: 10px;
border-radius: 5px;
}
```
```html
<h1>Simple float example</h1>
<div class="box">Float</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam
dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus
ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus
laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum,
tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus
neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat
volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros
pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec
lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.
</p>
```
```css
.box {
float: left;
width: 150px;
height: 150px;
margin-right: 30px;
}
```
{{ EmbedLiveSample('Floats', '100%', 600) }}
> **Note:** Floats are fully explained in our lesson on the [float and clear](/en-US/docs/Learn/CSS/CSS_layout/Floats) properties. Prior to techniques such as Flexbox and Grid Layout, floats were used as a method of creating column layouts. You may still come across these methods on the web; we will cover these in the lesson on [legacy layout methods](/en-US/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods).
## Positioning techniques
Positioning allows you to move an element from where it would otherwise be placed in normal flow over to another location. Positioning isn't a method for creating the main layouts of a page; it's more about managing and fine-tuning the position of specific items on a page.
There are, however, useful techniques for obtaining specific layout patterns that rely on the {{cssxref("position")}} property. Understanding positioning also helps in understanding normal flow, and what it means to move an item out of the normal flow.
There are five types of positioning you should know about:
- **Static positioning** is the default that every element gets. It just means "put the element into its normal position in the document layout flow β nothing special to see here".
- **Relative positioning** allows you to modify an element's position on the page, moving it relative to its position in normal flow, as well as making it overlap other elements on the page.
- **Absolute positioning** moves an element completely out of the page's normal layout flow, like it's sitting on its own separate layer. From there, you can fix it to a position relative to the edges of its closest positioned ancestor (which becomes `<html>` if no other ancestors are positioned). This is useful for creating complex layout effects, such as tabbed boxes where different content panels sit on top of one another and are shown and hidden as desired, or information panels that sit off-screen by default, but can be made to slide on screen using a control button.
- **Fixed positioning** is very similar to absolute positioning except that it fixes an element relative to the browser viewport, not another element. This is useful for creating effects such as a persistent navigation menu that always stays in the same place on the screen as the rest of the content scrolls.
- **Sticky positioning** is a newer positioning method that makes an element act like `position: relative` until it hits a defined offset from the viewport, at which point it acts like `position: fixed`.
### Simple positioning example
To provide familiarity with these page layout techniques, we'll show you a couple of quick examples. Our examples will all feature the same HTML structure (a heading followed by three paragraphs), which is as follows:
```html
<h1>Positioning</h1>
<p>I am a basic block level element.</p>
<p class="positioned">I am a basic block level element.</p>
<p>I am a basic block level element.</p>
```
This HTML will be styled by default using the following CSS:
```css
body {
width: 500px;
margin: 0 auto;
}
p {
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
padding: 10px;
margin: 10px;
border-radius: 5px;
}
.positioned {
background: rgb(255 84 104 / 30%);
border: 2px solid rgb(255 84 104);
}
```
The rendered output is as follows:
{{ EmbedLiveSample('Simple_positioning_example', '100%', 300) }}
### Relative positioning
Relative positioning allows you to offset an item from its default position in normal flow. This means you could achieve a task such as moving an icon down a bit so it lines up with a text label. To do this, we could add the following rule to add relative positioning:
```css
.positioned {
position: relative;
top: 30px;
left: 30px;
}
```
Here we give our middle paragraph a {{cssxref("position")}} value of `relative`. This doesn't do anything on its own, so we also add {{cssxref("top")}} and {{cssxref("left")}} properties. These serve to move the affected element down and to the right. This might seem like the opposite of what you were expecting, but you need to think of it as the element being pushed on its left and top sides, which results in it moving right and down.
Adding this code will give the following result:
```html hidden
<h1>Relative positioning</h1>
<p>I am a basic block level element.</p>
<p class="positioned">This is my relatively positioned element.</p>
<p>I am a basic block level element.</p>
```
```css hidden
body {
width: 500px;
margin: 0 auto;
}
p {
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
padding: 10px;
margin: 10px;
border-radius: 5px;
}
.positioned {
background: rgb(255 84 104 / 30%);
border: 2px solid rgb(255 84 104);
}
```
{{ EmbedLiveSample('Relative_positioning', '100%', 300) }}
### Absolute positioning
Absolute positioning is used to completely remove an element from the normal flow and instead position it using offsets from the edges of a containing block.
Going back to our original non-positioned example, we could add the following CSS rule to implement absolute positioning:
```css
.positioned {
position: absolute;
top: 30px;
left: 30px;
}
```
Here we give our middle paragraph a {{cssxref("position")}} value of `absolute` and the same {{cssxref("top")}} and {{cssxref("left")}} properties as before. Adding this code will produce the following result:
```html hidden
<h1>Absolute positioning</h1>
<p>I am a basic block level element.</p>
<p class="positioned">This is my absolutely positioned element.</p>
<p>I am a basic block level element.</p>
```
```css hidden
body {
width: 500px;
margin: 0 auto;
}
p {
background-color: rgb(207 232 220);
border: 2px solid rgb(79 185 227);
padding: 10px;
margin: 10px;
border-radius: 5px;
}
.positioned {
background: rgb(255 84 104 / 30%);
border: 2px solid rgb(255 84 104);
}
```
{{ EmbedLiveSample('Absolute_positioning', '100%', 300) }}
This is very different! The positioned element has now been completely separated from the rest of the page layout and sits over the top of it. The other two paragraphs now sit together as if their positioned sibling doesn't exist. The {{cssxref("top")}} and {{cssxref("left")}} properties have a different effect on absolutely positioned elements than they do on relatively positioned elements. In this case, the offsets have been calculated from the top and left of the page. It is possible to change the parent element that becomes this container and we will take a look at that in the lesson on [positioning](/en-US/docs/Learn/CSS/CSS_layout/Positioning).
### Fixed positioning
Fixed positioning removes our element from document flow in the same way as absolute positioning. However, instead of the offsets being applied from the container, they are applied from the viewport. Because the item remains fixed in relation to the viewport, we can create effects such as a menu that remains fixed as the page scrolls beneath it.
For this example, our HTML contains three paragraphs of text so that we can scroll through the page, as well as a box with the property of `position: fixed`.
```html
<h1>Fixed positioning</h1>
<div class="positioned">Fixed</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam
dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus
ut, rutrum luctus orci.
</p>
<p>
Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed
auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci
vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex
malesuada et.
</p>
<p>
In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet
turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas
augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id
ornare felis, eget fermentum sapien.
</p>
```
```css hidden
body {
width: 500px;
margin: 0 auto;
}
.positioned {
background: rgb(255 84 104 / 30%);
border: 2px solid rgb(255 84 104);
padding: 10px;
margin: 10px;
border-radius: 5px;
}
```
```css
.positioned {
position: fixed;
top: 30px;
left: 30px;
}
```
{{ EmbedLiveSample('Fixed_positioning', '100%', 200) }}
### Sticky positioning
Sticky positioning is the final positioning method that we have at our disposal. It mixes relative positioning with fixed positioning. When an item has `position: sticky`, it'll scroll in normal flow until it hits offsets from the viewport that we have defined. At that point, it becomes "stuck" as if it had `position: fixed` applied.
```html hidden
<h1>Sticky positioning</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam
dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus
ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus
laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum,
tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus
neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat
volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros
pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec
lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.
</p>
<div class="positioned">Sticky</div>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus
tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus
sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis
vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam
dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus
ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus
laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum,
tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus
neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat
volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros
pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec
lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.
</p>
```
```css hidden
body {
width: 500px;
margin: 0 auto;
}
.positioned {
background: rgb(255 84 104 / 30%);
border: 2px solid rgb(255 84 104);
padding: 10px;
margin: 10px;
border-radius: 5px;
}
```
```css
.positioned {
position: sticky;
top: 30px;
left: 30px;
}
```
{{ EmbedLiveSample('Sticky_positioning', '100%', 200) }}
> **Note:** To find out more about positioning, see our [Positioning](/en-US/docs/Learn/CSS/CSS_layout/Positioning) article.
## Table layout
HTML tables are fine for displaying tabular data, but many years ago β before even basic CSS was supported reliably across browsers β web developers used to also use tables for entire web page layouts, putting their headers, footers, columns, etc. into various table rows and columns. This worked at the time, but it has many problems: table layouts are inflexible, very heavy on markup, difficult to debug, and semantically wrong (e.g., screen reader users have problems navigating table layouts).
The way that a table looks on a webpage when you use table markup is due to a set of CSS properties that define table layout. These same properties can also be used to lay out elements that aren't tables, a use which is sometimes described as "using CSS tables".
The example below shows one such use. It must be noted, that using CSS tables for layout should be considered a legacy method at this point, and should only be used to support old browsers that lack support for Flexbox or Grid.
Let's look at an example. First, some simple markup that creates an HTML form. Each input element has a label, and we've also included a caption inside a paragraph. Each label/input pair is wrapped in a {{htmlelement("div")}} for layout purposes.
```html
<form>
<p>First of all, tell us your name and age.</p>
<div>
<label for="fname">First name:</label>
<input type="text" id="fname" />
</div>
<div>
<label for="lname">Last name:</label>
<input type="text" id="lname" />
</div>
<div>
<label for="age">Age:</label>
<input type="text" id="age" />
</div>
</form>
```
As for the CSS, most of it's fairly ordinary except for the uses of the {{cssxref("display")}} property. The {{htmlelement("form")}}, {{htmlelement("div")}}s, and {{htmlelement("label")}}s and {{htmlelement("input")}}s have been told to display like a table, table rows, and table cells respectively. Basically, they'll act like HTML table markup, causing the labels and inputs to line up nicely by default. All we then have to do is add a bit of sizing, margin, etc., to make everything look a bit nicer and we're done.
You'll notice that the caption paragraph has been given `display: table-caption;`, which makes it act like a table {{htmlelement("caption")}}, and `caption-side: bottom;` to tell the caption to sit on the bottom of the table for styling purposes, even though the markup is before the `<input>` elements in the source. This allows for a nice bit of flexibility.
```css
html {
font-family: sans-serif;
}
form {
display: table;
margin: 0 auto;
}
form div {
display: table-row;
}
form label,
form input {
display: table-cell;
margin-bottom: 10px;
}
form label {
width: 200px;
padding-right: 5%;
text-align: right;
}
form input {
width: 300px;
}
form p {
display: table-caption;
caption-side: bottom;
width: 300px;
color: #999;
font-style: italic;
}
```
This gives us the following result:
{{ EmbedLiveSample('Table_layout', '100%', '200') }}
You can also see this example live at [css-tables-example.html](https://mdn.github.io/learning-area/css/styling-boxes/box-model-recap/css-tables-example.html) (see the [source code](https://github.com/mdn/learning-area/blob/main/css/styling-boxes/box-model-recap/css-tables-example.html) too.)
> **Note:** Table layout, unlike the other topics of this page, won't be further covered in this module due to its legacy application.
## Multi-column layout
The multi-column layout CSS module provides us a way to lay out content in columns, similar to how text flows in a newspaper. While reading up and down columns is less useful in a web context due to the users having to scroll up and down, arranging content into columns can, nevertheless, be a useful technique.
To turn a block into a multi-column container, we use either the {{cssxref("column-count")}} property, which tells the browser _how many_ columns we would like to have, or the {{cssxref("column-width")}} property, which tells the browser to fill the container with as many columns as possible of a _specified width_.
In the below example, we start with a block of HTML inside a containing `<div>` element with a class of `container`.
```html
<div class="container">
<h1>Multi-column Layout</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus
aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci,
pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at
ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta.
</p>
<p>
Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada
ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed
est. Nam id risus quis ante semper consectetur eget aliquam lorem.
</p>
<p>
Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris
ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus
viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum
sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus
mus.
</p>
</div>
```
We're using a `column-width` of 200 pixels on that container, causing the browser to create as many 200 pixel columns as will fit. Whatever space is left between the columns will be shared.
```css hidden
body {
max-width: 800px;
margin: 0 auto;
}
```
```css
.container {
column-width: 200px;
}
```
{{ EmbedLiveSample('Multi-column_layout', '100%', 250) }}
## Summary
This article has provided a brief summary of all the layout technologies you should know about. Read on for more information on each individual technology!
{{NextMenu("Learn/CSS/CSS_layout/Normal_Flow", "Learn/CSS/CSS_layout")}}
| 0 |
data/mdn-content/files/en-us/learn/css | data/mdn-content/files/en-us/learn/css/howto/index.md | ---
title: Use CSS to solve common problems
slug: Learn/CSS/Howto
page-type: landing-page
---
{{LearnSidebar}}
This page rounds up questions and answers, and other material on the MDN site that can help you to solve common CSS problems.
## Styling boxes
- [How do I add a drop-shadow to an element?](/en-US/docs/Learn/CSS/Howto/Add_a_shadow)
- : Shadows can be added to boxes with the {{cssxref("box-shadow")}} property. This tutorial explains how it works and shows an example.
- [How do I fill a box with an image without distorting the image?](/en-US/docs/Learn/CSS/Howto/Fill_a_box_with_an_image)
- : The {{cssxref("object-fit")}} property provides different ways to fit an image into a box which has a different aspect ratio, and you can find out how to use them in this tutorial.
- [Which methods can be used to style boxes?](/en-US/docs/Learn/CSS/Howto/Create_fancy_boxes)
- : A rundown of the different properties that might be useful when styling boxes using CSS.
- [How can I make elements semi-transparent?](/en-US/docs/Learn/CSS/Howto/Make_box_transparent)
- : The {{cssxref("opacity")}} property and color values with an alpha channel can be used for this; find out which one to use when.
### Box styling lessons and guides
- [The Box Model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model)
- [Styling backgrounds and borders](/en-US/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders)
## CSS and text
- [How do I add a drop-shadow to text?](/en-US/docs/Learn/CSS/Howto/Add_a_text_shadow)
- : Shadows can be added to text with the {{cssxref("text-shadow")}} property. This tutorial explains how it works and shows an example.
- [How do I highlight the first line of a paragraph?](/en-US/docs/Learn/CSS/Howto/Highlight_first_line)
- : Find out how to target the first line of text in a paragraph with the {{cssxref("::first-line")}} pseudo-element.
- [How do I highlight the first paragraph in an article?](/en-US/docs/Learn/CSS/Howto/Highlight_first_para)
- : Find out how to target the first paragraph with the {{cssxref(":first-child")}} pseudo-class.
- [How do I highlight a paragraph only if it comes right after a heading?](/en-US/docs/Learn/CSS/Howto/Highlight_para_after_h1)
- : Combinators can help you to precisely target elements based on where they are in the document; this tutorial explains how to use them to apply CSS to a paragraph only if it immediately follows a heading.
### Text styling lessons and guides
- [How to style text](/en-US/docs/Learn/CSS/Styling_text/Fundamentals)
- [How to customize a list of elements](/en-US/docs/Learn/CSS/Styling_text/Styling_lists)
- [How to style links](/en-US/docs/Learn/CSS/Styling_text/Styling_links)
- [CSS Selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors)
## CSS Layout
- [How do I center an item?](/en-US/docs/Learn/CSS/Howto/Center_an_item)
- : Centering an item inside another box horizontally and vertically used to be tricky, however Flexbox now makes it simple.
### Layout guides
- [Using CSS Flexbox](/en-US/docs/Web/CSS/CSS_flexible_box_layout/Basic_concepts_of_flexbox)
- [Using CSS multi-column layouts](/en-US/docs/Web/CSS/CSS_multicol_layout/Using_multicol_layouts)
- [Using CSS Grid Layout](/en-US/docs/Web/CSS/CSS_grid_layout/Basic_concepts_of_grid_layout)
- [Using CSS generated content](/en-US/docs/Learn/CSS/Howto/Generated_content)
> **Note:** We have a cookbook dedicated to [CSS Layout solutions](/en-US/docs/Web/CSS/Layout_cookbook), with fully working examples and explanations of common layout tasks. Also check out [Practical Positioning Examples](/en-US/docs/Learn/CSS/CSS_layout/Practical_positioning_examples), which shows how you can use positioning to create a tabbed info box, and a sliding hidden panel.
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/generated_content/index.md | ---
title: Using CSS generated content
slug: Learn/CSS/Howto/Generated_content
page-type: learn-faq
---
{{LearnSidebar}}
This article describes some ways in which you can use CSS to add content when a document is displayed. You modify your stylesheet to add text content or images.
One of the important advantages of CSS is that it helps you to separate a document's style from its content. However, there are situations where it makes sense to specify certain content as part of the stylesheet, not as part of the document. You can specify text or image content within a stylesheet when that content is closely linked to the document's structure.
> **Note:** Content specified in a stylesheet does not become part of the DOM.
Specifying content in a stylesheet can cause complications. For example, you might have different language versions of your document that share a stylesheet. If you specify content in your stylesheet that requires translation, you have to put those parts of your stylesheet in different files and arrange for them to be linked with the appropriate language versions of your document.
This issue does not arise if the content you specify consists of symbols or images that apply in all languages and cultures.
## Examples
### Text content
CSS can insert text content before or after an element, or change the content of a list item marker (such as a bullet symbol or number) before a {{HTMLElement('li')}} or other element with {{ cssxref("display", "display: list-item;") }}. To specify this, make a rule and add {{ cssxref("::before") }}, {{ cssxref("::after") }}, or {{cssxref("::marker")}} to the selector. In the declaration, specify the {{ cssxref("content") }} property with the text content as its value.
#### HTML
```html
A text where I need to <span class="ref">something</span>
```
#### CSS
```css
.ref::before {
font-weight: bold;
color: navy;
content: "Reference ";
}
```
#### Output
{{ EmbedLiveSample('Text_content', 600, 30) }}
The character set of a stylesheet is UTF-8 by default, but it can also be specified in the link, in the stylesheet itself, or in other ways. For details, see [4.4 CSS style sheet representation](https://www.w3.org/TR/CSS21/syndata.html#q23) in the CSS Specification.
Individual characters can also be specified by an escape mechanism that uses backslash as the escape character. For example, "\265B" is the chess symbol for a black queen β. For details, see [Referring to characters not represented in a character encoding](https://www.w3.org/TR/CSS21/syndata.html#q24) and [Characters and case](https://www.w3.org/TR/CSS21/syndata.html#q6) in the CSS Specification.
### Image content
To add an image before or after an element, you can specify the URL of an image file in the value of the {{ cssxref("content") }} property.
This rule adds a space and an icon after every link that has the class `glossary`:
#### HTML
```html
<a href="developer.mozilla.org" class="glossary">developer.mozilla.org</a>
```
#### CSS
```css
a.glossary::after {
content: " " url("glossary-icon.gif");
}
```
{{ EmbedLiveSample('Image_content', 600, 40) }}
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/fill_a_box_with_an_image/index.md | ---
title: How to fill a box with an image without distorting it
slug: Learn/CSS/Howto/Fill_a_box_with_an_image
page-type: learn-faq
---
{{LearnSidebar}}
In this guide you can learn a technique for causing an HTML image to completely fill a box.
## Using object-fit
When you add an image to a page using the HTML {{htmlelement("img")}} element, the image will maintain the size and aspect ratio of the image file, or that of any HTML [`width`](/en-US/docs/Web/HTML/Global_attributes#width) or [`height`](/en-US/docs/Web/HTML/Global_attributes#height) attributes. Sometimes you would like the image to completely fill the box that you have placed it in. In that case you first need to decide what happens if the image is the wrong aspect ratio for the container.
1. The image should completely fill the box, retaining aspect ratio, and cropping any excess on the side that is too big to fit.
2. The image should fit inside the box, with the background showing through as bars on the too-small side.
3. The image should fill the box and stretch, which may mean it displays at the wrong aspect ratio.
The {{cssxref("object-fit")}} property makes each of these approaches possible. In the example below you can see how different values of `object-fit` work when using the same image. Select the approach that works best for your design.
{{EmbedGHLiveSample("css-examples/howto/object-fit.html", '100%', 800)}}
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/make_box_transparent/index.md | ---
title: How to make a box semi-transparent
slug: Learn/CSS/Howto/Make_box_transparent
page-type: learn-faq
---
{{LearnSidebar}}
This guide will help you to understand the ways to make a box semi-transparent using CSS.
## Change the opacity of the box and content
If you would like the box and all of the contents of the box to change opacity, then the CSS {{cssxref("opacity")}} property is the tool to reach for. Opacity is the opposite of transparency; therefore `opacity: 1` is fully opaqueβyou will not see through the box at all.
Using a value of `0` would make the box completely transparent, and values between the two will change the opacity, with higher values giving less transparency.
## Changing the opacity of the background color only
In many cases you will only want to make the background color itself partly transparent, keeping the text and other elements fully opaque. To achieve this, use a [`<color>`](/en-US/docs/Web/CSS/color_value) value that has an alpha channel, such as `rgb()`. As with `opacity`, a value of `1` for the alpha channel value makes the color fully opaque. Therefore, `background-color: rgb(0 0 0 / 50%);` will set the background color to 50% opacity.
Try changing the opacity and alpha channel values in the below examples to see more or less of the background image behind the box.
{{EmbedGHLiveSample("css-examples/howto/opacity.html", '100%', 770)}}
> **Note:** Take care that your text retains enough contrast with the background in cases where you are overlaying an image; otherwise you may make the content hard to read.
## See also
- [Applying color to HTML elements using CSS.](/en-US/docs/Web/CSS/CSS_colors/Applying_color)
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/highlight_para_after_h1/index.md | ---
title: How to highlight a paragraph that comes after a heading
slug: Learn/CSS/Howto/Highlight_para_after_h1
page-type: learn-faq
---
{{LearnSidebar}}
In this guide you can find out how to highlight a paragraph that comes directly after a heading.
## Styling the first paragraph after a heading
A common pattern is to style the first paragraph in an article differently to the ones that come after it. Usually this first paragraph will come right after a heading, and if this is the case in your design you can use that combination of elements to target the paragraph.
## The next-sibling combinator
CSS has a group of [CSS Selectors](/en-US/docs/Web/CSS/CSS_selectors) which are referred to as **combinators**, because they select things based on a combination of selectors. In our case, we will use the [next-sibling combinator](/en-US/docs/Web/CSS/Next-sibling_combinator). This combinator selects an element based on it being next to another element. In our HTML we have a {{htmlelement("Heading_Elements", "h1")}} followed by a {{htmlelement("p")}}. The `<p>` is the next sibling of the `<h1>` so we can select it with `h1 + p`.
{{EmbedGHLiveSample("css-examples/howto/highlight_h1_plus_para.html", '100%', 800)}}
## See also
- [Learn CSS: Selectors.](/en-US/docs/Learn/CSS/Building_blocks/Selectors)
- [Learn CSS: Combinators.](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Combinators)
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/create_fancy_boxes/index.md | ---
title: Create fancy boxes
slug: Learn/CSS/Howto/Create_fancy_boxes
page-type: learn-faq
---
{{LearnSidebar}}
CSS boxes are the building blocks of any web page styled with CSS. Making them nice looking is both fun and challenging. It's fun because it's all about turning a design idea into working code; it's challenging because of the constraints of CSS. Let's do some fancy boxes.
Before we start getting into the practical side of it, make sure you are familiar with [the CSS box model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model). It's also a good idea, but not a prerequisite, to be familiar with some [CSS layout basics](/en-US/docs/Learn/CSS/CSS_layout/Introduction).
On the technical side, Creating fancy boxes are all about mastering CSS border and background properties and how to apply them to a given box. But beyond the techniques it's also all about unleashing your creativity. It will not be done in one day, and some web developers spend their whole life having fun with it.
We are about to see many examples, but we will always work on the most simple piece of HTML possible, a simple element:
```html
<div class="fancy">Hi! I want to be fancy.</div>
```
Ok, that's a very small bit of HTML, what can we tweak on that element? All the following:
- Its box model properties: {{cssxref("width")}}, {{cssxref("height")}}, {{cssxref("padding")}}, {{cssxref("border")}}, etc.
- Its background properties: {{cssxref("background")}}, {{cssxref("background-color")}}, {{cssxref("background-image")}}, {{cssxref("background-position")}}, {{cssxref("background-size")}}, etc.
- Its pseudo-element: {{cssxref("::before")}} and {{cssxref("::after")}}
- and some aside properties like: {{cssxref("box-shadow")}}, {{cssxref("rotate")}}, {{cssxref("outline")}}, etc.
So we have a very large playground. Let the fun begin.
## Box model tweak
The box model alone allows us to do some basic stuff, like adding simple borders, making squares, etc. It starts to get interesting when you push the properties to the limit by having negative `padding` and/or- `margin` by having `border-radius` larger than the actual size of the box.
### Making circles
```html hidden
<div class="fancy">Hi! I want to be fancy.</div>
```
This is something that is both very simple and very fun. The {{cssxref("border-radius")}} property is made to create a rounded corner applied to boxes, but what happens if the radius size is equal or larger than the actual width of the box?
```css
.fancy {
/* Within a circle, centered text looks prettier. */
text-align: center;
/* Let's avoid our text touching the border. As
our text will still flow in a square, it looks
nicer that way, giving the feeling that it's a "real"
circle. */
padding: 1em;
/* The border will make the circle visible.
You could also use a background, as
backgrounds are clipped by border radius */
border: 0.5em solid black;
/* Let's make sure we have a square.
If it's not a square, we'll get an
ellipsis rather than a circle */
width: 4em;
height: 4em;
/* and let's turn the square into a circle */
border-radius: 100%;
}
```
Yes, we get a circle:
{{ EmbedLiveSample('Making_circles', '100%', '120') }}
## Backgrounds
When we talk about a fancy box, the core properties to handle that are [background-\* properties](/en-US/docs/Web/CSS/CSS_backgrounds_and_borders). When you start fiddling with backgrounds it's like your CSS box is turned into a blank canvas you'll fill.
Before we jump to some practical examples, let's step back a bit as there are two things you should know about backgrounds.
- It's possible to set [several backgrounds](/en-US/docs/Web/CSS/CSS_backgrounds_and_borders/Using_multiple_backgrounds) on a single box. They are stacked on top of each other like layers.
- Backgrounds can be either solid colors or images: solid color always fills the whole surface but images can be scaled and positioned.
```html hidden
<div class="fancy">Hi! I want to be fancy.</div>
```
Okay, let's have fun with backgrounds:
```css-nolint
.fancy {
padding: 1em;
width: 100%;
height: 200px;
box-sizing: border-box;
/* At the bottom of our background stack,
let's have a misty grey solid color */
background-color: #e4e4d9;
/* We stack linear gradients on top of each
other to create our color strip effect.
As you will notice, color gradients are
considered to be images and can be
manipulated as such */
background-image: linear-gradient(175deg, rgb(0 0 0 / 0%) 95%, #8da389 95%),
linear-gradient( 85deg, rgb(0 0 0 / 0%) 95%, #8da389 95%),
linear-gradient(175deg, rgb(0 0 0 / 0%) 90%, #b4b07f 90%),
linear-gradient( 85deg, rgb(0 0 0 / 0%) 92%, #b4b07f 92%),
linear-gradient(175deg, rgb(0 0 0 / 0%) 85%, #c5a68e 85%),
linear-gradient( 85deg, rgb(0 0 0 / 0%) 89%, #c5a68e 89%),
linear-gradient(175deg, rgb(0 0 0 / 0%) 80%, #ba9499 80%),
linear-gradient( 85deg, rgb(0 0 0 / 0%) 86%, #ba9499 86%),
linear-gradient(175deg, rgb(0 0 0 / 0%) 75%, #9f8fa4 75%),
linear-gradient( 85deg, rgb(0 0 0 / 0%) 83%, #9f8fa4 83%),
linear-gradient(175deg, rgb(0 0 0 / 0%) 70%, #74a6ae 70%),
linear-gradient( 85deg, rgb(0 0 0 / 0%) 80%, #74a6ae 80%);
}
```
{{ EmbedLiveSample('Backgrounds', '100%', '200') }}
> **Note:** Gradients can be used in some very creative ways. If you want to see some creative examples, take a look at [Lea Verou's CSS patterns](https://projects.verou.me/css3patterns/). If you want to learn more about gradients, feel free to get into [our dedicated article](/en-US/docs/Web/CSS/CSS_images/Using_CSS_gradients).
## Pseudo-elements
When styling a single box, you could find yourself limited and could wish to have more boxes to create even more amazing styles. Most of the time, that leads to polluting the DOM by adding extra HTML element for the unique purpose of style. Even if it is necessary, it's somewhat considered bad practice. One solution to avoid such pitfalls is to use [CSS pseudo-elements](/en-US/docs/Web/CSS/Pseudo-elements).
### A cloud
```html hidden
<div class="fancy">Hi! I want to be fancy.</div>
```
Let's have an example by turning our box into a cloud:
```css
.fancy {
text-align: center;
/* Same trick as previously used to make circles */
box-sizing: border-box;
width: 150px;
height: 150px;
padding: 80px 1em 0 1em;
/* We make room for the "ears" of our cloud */
margin: 0 100px;
position: relative;
background-color: #a4c9cf;
/* Well, actually we are not making a full circle
as we want the bottom of our cloud to be flat.
Feel free to tweak this example to make a cloud
that isn't flat at the bottom ;) */
border-radius: 100% 100% 0 0;
}
/* Those are common style that apply to both our ::before
and ::after pseudo elements. */
.fancy::before,
.fancy::after {
/* This is required to be allowed to display the
pseudo-elements, event if the value is an empty
string */
content: "";
/* We position our pseudo-elements on the left and
right sides of the box, but always at the bottom */
position: absolute;
bottom: 0;
/* This makes sure our pseudo-elements will be below
the box content whatever happens. */
z-index: -1;
background-color: #a4c9cf;
border-radius: 100%;
}
.fancy::before {
/* This is the size of the clouds left ear */
width: 125px;
height: 125px;
/* We slightly move it to the left */
left: -80px;
/* To make sure that the bottom of the cloud
remains flat, we must make the bottom right
corner of the left ear square. */
border-bottom-right-radius: 0;
}
.fancy::after {
/* This is the size of the clouds left ear */
width: 100px;
height: 100px;
/* We slightly move it to the right */
right: -60px;
/* To make sure that the bottom of the cloud
remains flat, we must make the bottom left
corner of the right ear square. */
border-bottom-left-radius: 0;
}
```
{{ EmbedLiveSample('A_cloud', '100%', '160') }}
### Blockquote
A more practical example of using pseudo-elements is to build a nice formatting for HTML {{HTMLElement('blockquote')}} elements. So let's see an example with a slightly different HTML snippet (which provide us an opportunity to see how to also handle design localization):
```html
<blockquote>
People who think they know everything are a great annoyance to those of us who
do. <i>Isaac Asimov</i>
</blockquote>
<blockquote lang="fr">
L'intelligence, c'est comme les parachutes, quand on n'en a pas, on s'Γ©crase.
<i>Pierre Desproges</i>
</blockquote>
```
So here comes our style:
```css
blockquote {
min-height: 5em;
padding: 1em 4em;
font: 1em/150% sans-serif;
position: relative;
background-color: lightgoldenrodyellow;
}
blockquote::before,
blockquote::after {
position: absolute;
height: 3rem;
font:
6rem/100% Georgia,
"Times New Roman",
Times,
serif;
}
blockquote::before {
content: "β";
top: 0.3rem;
left: 0.9rem;
}
blockquote::after {
content: "β";
bottom: 0.3rem;
right: 0.8rem;
}
blockquote:lang(fr)::before {
content: "Β«";
top: -1.5rem;
left: 0.5rem;
}
blockquote:lang(fr)::after {
content: "Β»";
bottom: 2.6rem;
right: 0.5rem;
}
blockquote i {
display: block;
font-size: 0.8em;
margin-top: 1rem;
text-align: right;
}
```
{{ EmbedLiveSample('Blockquote', '100%', '300') }}
## All together and more
So it's possible to create a wonderful effect when we mix all of this together. At some point, to accomplish such box embellishment is a matter of creativity, both in design and technical use of CSS properties. By doing such it's possible to create optical illusions that can bring your boxes alive like in this example:
```html hidden
<div class="fancy">Hi! I want to be fancy.</div>
```
Let's create some partial drop-shadow effects. The {{cssxref("box-shadow")}} property allow us to create inner light and a flat drop shadow effect, but with some little extra work it becomes possible to create a more natural geometry by using a pseudo-element and the {{cssxref("rotate")}} property, one of the three individual {{cssxref("transform")}} properties.
```css
.fancy {
position: relative;
background-color: #ffc;
padding: 2rem;
text-align: center;
max-width: 200px;
}
.fancy::before {
content: "";
position: absolute;
z-index: -1;
bottom: 15px;
right: 5px;
width: 50%;
top: 80%;
max-width: 200px;
box-shadow: 0px 13px 10px black;
rotate: 4deg;
}
```
{{ EmbedLiveSample('All_together_and_more', '100%', '120') }}
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/transition_button/index.md | ---
title: How to fade a button on hover
slug: Learn/CSS/Howto/Transition_button
page-type: learn-faq
---
{{LearnSidebar}}
In this guide you can find out how to do a gentle fade between two colors when hovering over a button.
In our button example, we can change the background of our button by defining a different background color for the `:hover` dynamic pseudo-class. However, hovering over the button will cause the background-color to snap to the new color. To create a more gentle change between the two, we can use CSS Transitions.
## Using transitions
After adding the desired color for the hover state, add the {{cssxref("transition")}} property to the rules for the button. For a simple transition, the value of `transition` is the name of the property or properties you wish this transition to apply to, and the time that the transition should take.
For the `:active` and `:focus` pseudo-classes the {{cssxref("transition")}} property is set to none, so that the button snaps to the active state when clicked.
In the example the transition takes 1 second, you can try changing this to see the difference a change in speed makes.
{{EmbedGHLiveSample("css-examples/howto/transition-button.html", '100%', 720)}}
> **Note:** The {{cssxref("transition")}} property is a shorthand for {{cssxref("transition-delay")}}, {{cssxref("transition-duration")}}, {{cssxref("transition-property")}}, and {{cssxref("transition-timing-function")}}. See the pages for these properties on MDN to find ways to tweak your transitions.
## See also
- [Using CSS transitions](/en-US/docs/Web/CSS/CSS_transitions/Using_CSS_transitions)
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/highlight_first_line/index.md | ---
title: How to highlight the first line of a paragraph
slug: Learn/CSS/Howto/Highlight_first_line
page-type: learn-faq
---
{{LearnSidebar}}
In this guide you will find out how to highlight the first line of text in a paragraph, even if you don't know how long that line will be.
## Styling the first line of text
You would like to make the first line of a paragraph larger and bold. Wrapping a `<span>` around the first line means that you can style it however, if the first line becomes shorter due to a smaller viewport size, the styled text will wrap onto the next line.
## Using a pseudo-element
A {{cssxref("pseudo-elements", "pseudo-element")}} can take the place of the `<span>`; however, it is more flexible β the exact content selected by a pseudo-element is calculated once the browser has rendered the content, so it will work even if the viewport size changes.
In this case we need to use the {{cssxref("::first-line")}} pseudo-element. It selects the first formatted line of each paragraph, meaning that you can style it as you require.
{{EmbedGHLiveSample("css-examples/howto/highlight_first_line.html", '100%', 750)}}
> **Note:** All pseudo-elements act in this way. They behave as if you had inserted an element into the document, but they do so dynamically based on the content as it displays at runtime.
## Combining pseudo-elements with other selectors
In the example above, the pseudo-element selects the first line of every paragraph. To select only the first line of the first paragraph, you can combine it with another selector. In this case, we use the {{cssxref(":first-child")}} {{cssxref("pseudo-classes", "pseudo-class")}}. This allows us to select the first line of the first child of `.wrapper` if that first child is a paragraph.
{{EmbedGHLiveSample("css-examples/howto/highlight_first_line2.html", '100%', 700)}}
> **Note:** When combining pseudo-elements with other selectors in a [complex](/en-US/docs/Web/CSS/CSS_selectors/Selector_structure#complex_selector) or [compound](/en-US/docs/Web/CSS/CSS_selectors/Selector_structure#compound_selector) selector, the pseudo-elements must appear after all the other components in the selector in which they appear.
## See also
- The {{cssxref("pseudo-elements", "pseudo-elements")}} reference page.
- [Learn CSS: Pseudo-classes and pseudo-elements.](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements)
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/css_faq/index.md | ---
title: CSS FAQ
slug: Learn/CSS/Howto/CSS_FAQ
page-type: learn-faq
---
{{LearnSidebar}}
In this article, you'll find some frequently-asked questions (FAQs) about CSS, along with answers that may help you on your quest to become a web developer.
## Why doesn't my CSS, which is valid, render correctly?
Browsers use the `DOCTYPE` declaration to choose whether to show the document using a mode that is more compatible with Web standards or with old browser bugs. Using a correct and modern `DOCTYPE` declaration at the start of your HTML will improve browser standards compliance.
Modern browsers have two main rendering modes:
- _Quirks Mode_: also called backwards-compatibility mode, allows legacy webpages to be rendered as their authors intended, following the non-standard rendering rules used by older browsers. Documents with an incomplete, incorrect, or missing `DOCTYPE` declaration or a known `DOCTYPE` declaration in common use before 2001 will be rendered in Quirks Mode.
- _Standards Mode_: the browser attempts to follow the W3C standards strictly. New HTML pages are expected to be designed for standards-compliant browsers, and as a result, pages with a modern `DOCTYPE` declaration will be rendered with Standards Mode.
Gecko-based browsers have a third [limited quirks mode](https://en.wikipedia.org/wiki/Quirks_mode#Limited_quirks_mode) that has only a few minor quirks.
The standard `DOCTYPE` declaration that will trigger standards mode is:
```html
<!doctype html>
```
When at all possible, you should just use the above doctype. There are other valid legacy doctypes that will trigger Standards or Almost Standards mode:
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
```
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
```
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
```
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
```
## Why doesn't my CSS, which is valid, render at all?
Here are some possible causes:
- You've got the path to CSS file wrong.
- To be applied, a CSS stylesheet must be served with a `text/css` MIME type. If the Web server doesn't serve it with this type, it won't be applied.
## What is the difference between `id` and `class`?
HTML elements can have an `id` and/or `class` attribute. The `id` attribute assigns a name to the element it is applied to, and for valid markup, there can be only one element with that name. The `class` attribute assigns a class name to the element, and that name can be used on many elements within the page. CSS allows you to apply styles to particular `id` and/or `class` names.
- Use a class-specific style when you want to apply the styling rules to many blocks and elements within the page, or when you currently only have element to style with that style, but you might want to add more later.
- Use an id-specific style when you need to restrict the applied styling rules to one specific block or element. This style will only be used by the element with that particular id.
It is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for styling elements that must be semantically unique):
- Using classes makes your styling extensible β even if you only have one element to style with a particular ruleset now, you might want to add more later.
- Classes allow you to style multiple elements, therefore they can lead to shorter stylesheets, rather than having to write out the same styling information in multiple rules that use id selectors. Shorter stylesheets are more performant.
- Class selectors have lower [specificity](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#specificity) than id selectors, so are easier to override if needed.
> **Note:** See [Selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors) for more information.
## How do I restore the default value of a property?
Initially CSS didn't provide a "default" keyword and the only way to restore the default value of a property is to explicitly re-declare that property. For example:
```css
/* Heading default color is black */
h1 {
color: red;
}
h1 {
color: black;
}
```
This has changed with CSS 2; the keyword [initial](/en-US/docs/Web/CSS/initial) is now a valid value for a CSS property. It resets it to its default value, which is defined in the CSS specification of the given property.
```css
/* Heading default color is black */
h1 {
color: red;
}
h1 {
color: initial;
}
```
## How do I derive one style from another?
CSS does not exactly allow one style to be defined in terms of another. However, assigning multiple classes to a single element can provide the same effect, and [CSS Variables](/en-US/docs/Web/CSS/Using_CSS_custom_properties) now provide a way to define style information in one place that can be reused in multiple places.
## How do I assign multiple classes to an element?
HTML elements can be assigned multiple classes by listing the classes in the `class` attribute, with a blank space to separate them.
```html
<style>
.news {
background: black;
color: white;
}
.today {
font-weight: bold;
}
</style>
<div class="news today">Content of today's news goes here.</div>
```
If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the `class` attribute is not relevant.
## Why don't my style rules work properly?
Style rules that are syntactically correct may not apply in certain situations. You can use [Rules view](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_and_edit_css/index.html) of _CSS Pane_ of the Inspector to debug problems of this kind, but the most frequent instances of ignored style rules are listed below.
### HTML elements hierarchy
The way CSS styles are applied to HTML elements depends also on the elements' hierarchy. It is important to remember that a rule applied to a descendant overrides the style of the parent, in spite of any specificity or priority of CSS rules.
```css
.news {
color: black;
}
.corpName {
font-weight: bold;
color: red;
}
```
```html
<!-- news item text is black, but corporate name is red and in bold -->
<div class="news">
(Reuters) <span class="corpName">General Electric</span> (GE.NYS) announced on
Thursdayβ¦
</div>
```
In case of complex HTML hierarchies, if a rule seems to be ignored, check if the element is inside another element with a different style.
### Explicitly re-defined style rule
In CSS stylesheets, order **is** important. If you define a rule and then you re-define the same rule, the last definition is used.
```css
#stockTicker {
font-weight: bold;
}
.stockSymbol {
color: red;
}
/* other rules */
/* other rules */
/* other rules */
.stockSymbol {
font-weight: normal;
}
```
```html
<!-- most text is in bold, except "GE", which is red and not bold -->
<div id="stockTicker">NYS: <span class="stockSymbol">GE</span> +1.0β¦</div>
```
To avoid this kind of error, try to define rules only once for a certain selector, and group all rules belonging to that selector.
### Use of a shorthand property
Using shorthand properties for defining style rules is good because it uses a very compact syntax. Using shorthand with only some attributes is possible and correct, but it must be remembered that undeclared attributes are automatically reset to their default values. This means that a previous rule for a single attribute could be implicitly overridden.
```css
#stockTicker {
font-size: 12px;
font-family: Verdana;
font-weight: bold;
}
.stockSymbol {
font: 14px Arial;
color: red;
}
```
```html
<div id="stockTicker">NYS: <span class="stockSymbol">GE</span> +1.0β¦</div>
```
In the previous example the problem occurred on rules belonging to different elements, but it could happen also for the same element, because rule order **is** important.
```css
#stockTicker {
font-weight: bold;
font: 12px Verdana; /* font-weight is now set to normal */
}
```
### Use of the `*` selector
The `*` wildcard selector refers to any element, and it has to be used with particular care.
```css
body * {
font-weight: normal;
}
#stockTicker {
font: 12px Verdana;
}
.corpName {
font-weight: bold;
}
.stockUp {
color: red;
}
```
```html
<div id="section">
NYS: <span class="corpName"><span class="stockUp">GE</span></span> +1.0β¦
</div>
```
In this example the `body *` selector applies the rule to all elements inside body, at any hierarchy level, including the `.stockUp` class. So `font-weight: bold;` applied to the `.corpName` class is overridden by `font-weight: normal;` applied to all elements in the body.
The use of the \* selector should be minimized as it is a slow selector, especially when not used as the first element of a selector. Its use should be avoided as much as possible.
### Specificity in CSS
When multiple rules apply to a certain element, the rule chosen depends on its style [specificity](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#specificity). Inline style (in HTML `style` attributes) has the highest specificity and will override any selectors, followed by ID selectors, then class selectors, and eventually element selectors. The text color of the below {{htmlelement("div")}} will therefore be red.
```css
div {
color: black;
}
#orange {
color: orange;
}
.green {
color: green;
}
```
```html
<div id="orange" class="green" style="color: red;">This is red</div>
```
The rules are more complicated when the selector has multiple parts. A more detailed explanation about how selector specificity is calculated can be found in the [CSS specificity documentation](/en-US/docs/Web/CSS/Specificity).
## What do the -moz-\*, -ms-\*, -webkit-\*, -o-\* and -khtml-\* properties do?
These properties, called _prefixed properties_, are extensions to the CSS standard. They were once used to allow the use of experimental and non-standard features in browsers without polluting the regular namespace, preventing future incompatibilities to arise when the standard is extended.
The use of such properties on production websites is not recommended β they have already created a huge web compatibility mess. For example, many developers only use the `-webkit-` prefixed version of a property when the non-prefixed version is fully supported across all browsers. This means a design relying on that property would not work in non-webkit-based browsers, when it could. This became a problem great enough that other browsers were pushed to implement `-webkit-` prefixed aliases to improve web compatibility, as specified in the [Compatibility Living Standard](https://compat.spec.whatwg.org/).
Browsers no longer use CSS prefixes when implementing new experimental features. Rather, they test new features behind configurable experimental flags or only on Nightly browser versions or similar.
If you are required to use prefixes in your work, write the prefixed versions first followed by the non-prefixed standard version. This way the standard version will automatically override the prefixed versions when supported. For example:
```css
-webkit-text-stroke: 4px navy;
text-stroke: 4px navy;
```
> **Note:** For more information on dealing with prefixed properties, see [Handling common HTML and CSS problems β Handling CSS prefixes](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS#handling_css_prefixes) from our [Cross-browser testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing) module.
> **Note:** See the [Mozilla CSS Extensions](/en-US/docs/Web/CSS/Mozilla_Extensions) and [WebKit CSS Extensions](/en-US/docs/Web/CSS/WebKit_Extensions) for lists of browser-prefixed CSS properties.
## How does z-index relate to positioning?
The z-index property specifies the stack order of elements.
An element with a higher z-index/stack order is always rendered in front of an element with a lower z-index/stack order on the screen. Z-index will only work on elements that have a specified position (`position:absolute`, `position:relative`, or `position:fixed`).
> **Note:** For more information, see our [Positioning](/en-US/docs/Learn/CSS/CSS_layout/Positioning) learning article, and in particular the [Introducing z-index](/en-US/docs/Learn/CSS/CSS_layout/Positioning#introducing_z-index) section.
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/center_an_item/index.md | ---
title: How to center an item
slug: Learn/CSS/Howto/Center_an_item
page-type: learn-faq
---
{{LearnSidebar}}
In this guide you can find out how to center an item inside another element, both horizontally and vertically.
## Center a box
To center one box inside another using CSS you will need to use [CSS box alignment](/en-US/docs/Web/CSS/CSS_box_alignment) properties on the parent container. As these alignment properties do not yet have browser support for block and inline layout you will need to make the parent a [flex](/en-US/docs/Web/CSS/CSS_flexible_box_layout) or [grid](/en-US/docs/Web/CSS/CSS_grid_layout) container to turn on the ability to use alignment.
In the example below we have given the parent container `display: flex`; then set {{cssxref("justify-content")}} to center to align it horizontally, and {{cssxref("align-items")}} to center to align it vertically.
{{EmbedGHLiveSample("css-examples/howto/center.html", '100%', 700)}}
> **Note:** You can use this technique to do any kind of alignment of one or more elements inside another. In the example above you can try changing the values to any valid values for {{cssxref("justify-content")}} and {{cssxref("align-items")}}.
## See also
- [Box alignment in Flexbox](/en-US/docs/Web/CSS/CSS_box_alignment/Box_alignment_in_flexbox)
- [Box alignment in Grid layout](/en-US/docs/Web/CSS/CSS_box_alignment/Box_alignment_in_grid_layout)
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/highlight_first_para/index.md | ---
title: How to highlight the first paragraph
slug: Learn/CSS/Howto/Highlight_first_para
page-type: learn-faq
---
{{LearnSidebar}}
In this guide you can find out how to highlight the first paragraph inside a container.
## Styling the first paragraph
You would like to make the first paragraph larger and bold. You could add a class to the first paragraph and select it that way, however using a pseudo-class selector is more flexible β it means that you can target the paragraph based on its location in the document, and you won't have to manually move the class if the source order changes.
## Using a pseudo-class
A {{cssxref("pseudo-classes","pseudo-class")}} acts as if you have applied a class; however, rather than using a class selector CSS selects based on the document structure. There are a number of different pseudo-classes that can select different things. In our case we are going to use {{cssxref(":first-child")}}. This will select the element that is the first-child of a parent.
{{EmbedGHLiveSample("css-examples/howto/highlight_first_para.html", '100%', 770)}}
You can try changing {{cssxref(":first-child")}} to {{cssxref(":last-child")}} in the live example above, and you will select the last paragraph.
Whenever you need to target something in your document, you can check to see if one of the available {{cssxref("pseudo-classes")}} can do it for you.
## See also
- The {{cssxref("pseudo-classes")}} reference page.
- [Learn CSS: Pseudo-classes and pseudo-elements.](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements)
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/add_a_shadow/index.md | ---
title: How to add a shadow to an element
slug: Learn/CSS/Howto/Add_a_shadow
page-type: learn-faq
---
{{LearnSidebar}}
In this guide you can find out how to add a shadow to any box on your page.
## Adding box shadows
Shadows are a common design feature that can help elements stand out on your page. In CSS, shadows on the boxes of elements are created using the {{cssxref("box-shadow")}} property (if you want to add a shadow to the text itself, you need {{cssxref("text-shadow")}}).
The `box-shadow` property takes a number of values:
- The offset on the x-axis
- The offset on the y-axis
- A blur radius
- A spread radius
- A color
- The `inset` keyword
In the example below we have set the X and Y axes to 5px, the blur to 10px and the spread to 2px. I am using a semi-transparent black as my color. Play with the different values to see how they change the shadow.
{{EmbedGHLiveSample("css-examples/howto/box-shadow-button.html", '100%', 500)}}
> **Note:** We are not using `inset` in this example, this means that the shadow is the default drop shadow with the box on top of the shadow. Inset shadows appear inside the box as if the content were pushed back into the page.
## See also
- The [Box shadow generator](/en-US/docs/Web/CSS/CSS_backgrounds_and_borders/Box-shadow_generator)
- [Learn CSS: Advanced styling effects.](/en-US/docs/Learn/CSS/Building_blocks/Advanced_styling_effects)
| 0 |
data/mdn-content/files/en-us/learn/css/howto | data/mdn-content/files/en-us/learn/css/howto/add_a_text_shadow/index.md | ---
title: How to add a shadow to text
slug: Learn/CSS/Howto/Add_a_text_shadow
page-type: learn-faq
---
{{LearnSidebar}}
In this guide you can find out how to add a shadow to any text on your page.
## Adding shadows to text
In our [guide to adding a shadow to boxes](/en-US/docs/Learn/CSS/Howto/Add_a_shadow), you can find out how to add a shadow to any element on your page. However, that technique only adds shadows to the element's surrounding box. To add a drop shadow to the text inside the box you need a different CSS property β {{cssxref("text-shadow")}}.
The `text-shadow` property takes a number of values:
- The offset on the x-axis
- The offset on the y-axis
- A blur radius
- A color
In the example below we have set the x-axis offset to 2px, the y-axis offset to 4px, the blur radius to 4px, and the color to a semi-transparent blue. Play with the different values to see how they change the shadow.
{{EmbedGHLiveSample("css-examples/howto/text-shadow.html", '100%', 500)}}
> **Note:** It can be quite easy to make text hard to read with text shadows. Make sure that the choices you make still leave your text readable and provide enough [color contrast](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) for visitors who have difficulty with low-contrast text.
| 0 |
data/mdn-content/files/en-us/learn/css | data/mdn-content/files/en-us/learn/css/first_steps/index.md | ---
title: CSS first steps overview
slug: Learn/CSS/First_steps
page-type: learn-module
---
{{LearnSidebar}}
CSS (Cascading Style Sheets) is used to style and lay out web pages β for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features. This module provides a gentle beginning to your path towards CSS mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to 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 discussed in the [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) 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 will take you through all the basic theory of CSS, and provide opportunities for you to test out some skills.
- [What is CSS?](/en-US/docs/Learn/CSS/First_steps/What_is_CSS)
- : **{{Glossary("CSS")}}** (Cascading Style Sheets) allows you to create great-looking web pages, but how does it work under the hood? This article explains what CSS is with a simple syntax example and also covers some key terms about the language.
- [Getting started with CSS](/en-US/docs/Learn/CSS/First_steps/Getting_started)
- : In this article, we will take a simple HTML document and apply CSS to it, learning some practical things about the language along the way.
- [How CSS is structured](/en-US/docs/Learn/CSS/First_steps/How_CSS_is_structured)
- : Now that you have an idea about what CSS is and the basics of using it, it is time to look a little deeper into the structure of the language itself. We have already met many of the concepts discussed here; you can return to this one to recap if you find any later concepts confusing.
- [How CSS works](/en-US/docs/Learn/CSS/First_steps/How_CSS_works)
- : We have learned the basics of CSS, what it is for, and how to write simple stylesheets. In this article, we will take a look at how a browser takes CSS and HTML and turns that into a webpage.
## Assessments
The following assessment will test your understanding of the CSS basics covered in the guides above.
- [Styling a biography page](/en-US/docs/Learn/CSS/First_steps/Styling_a_biography_page)
- : With the things you have learned in the last few articles, you should find that you can format simple text documents using CSS to add your own style to them. This assessment gives you a chance to do that.
| 0 |
data/mdn-content/files/en-us/learn/css/first_steps | data/mdn-content/files/en-us/learn/css/first_steps/getting_started/index.md | ---
title: Getting started with CSS
slug: Learn/CSS/First_steps/Getting_started
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/First_steps/What_is_CSS", "Learn/CSS/First_steps/How_CSS_is_structured", "Learn/CSS/First_steps")}}
In this article, we will take a simple HTML document and apply CSS to it, learning some practical things about the language 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 basics of linking a CSS document to an HTML file, and
be able to do simple text formatting with CSS.
</td>
</tr>
</tbody>
</table>
## Starting with some HTML
Our starting point is an HTML document. You can copy the code from below if you want to work on your own computer. Save the code below as `index.html` in a folder on your machine.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Getting started with CSS</title>
</head>
<body>
<h1>I am a level one heading</h1>
<p>
This is a paragraph of text. In the text is a
<span>span element</span> and also a
<a href="https://example.com">link</a>.
</p>
<p>
This is the second paragraph. It contains an <em>emphasized</em> element.
</p>
<ul>
<li>Item <span>one</span></li>
<li>Item two</li>
<li>Item <em>three</em></li>
</ul>
</body>
</html>
```
> **Note:** If you are reading this on a device or an environment where you can't easily create files, then don't worry β live code editors are provided below to allow you to write example code right here in the page.
## Adding CSS to our document
The very first thing we need to do is to tell the HTML document that we have some CSS rules we want it to use. There are three different ways to apply CSS to an HTML document that you'll commonly come across, however, for now, we will look at the most usual and useful way of doing so β linking CSS from the head of your document.
Create a file in the same folder as your HTML document and save it as `styles.css`. The `.css` extension shows that this is a CSS file.
To link `styles.css` to `index.html`, add the following line somewhere inside the {{htmlelement("head")}} of the HTML document:
```html
<link rel="stylesheet" href="styles.css" />
```
This {{htmlelement("link")}} element tells the browser that we have a stylesheet, using the `rel` attribute, and the location of that stylesheet as the value of the `href` attribute. You can test that the CSS works by adding a rule to `styles.css`. Using your code editor, add the following to your CSS file:
```css
h1 {
color: red;
}
```
Save your HTML and CSS files and reload the page in a web browser. The level one heading at the top of the document should now be red. If that happens, congratulations β you have successfully applied some CSS to an HTML document. If that doesn't happen, carefully check that you've typed everything correctly.
You can continue to work in `styles.css` locally, or you can use our interactive editor below to continue with this tutorial. The interactive editor acts as if the CSS in the first panel is linked to the HTML document, just as we have with our document above.
## Styling HTML elements
By making our heading red, we have already demonstrated that we can target and style an HTML element. We do this by targeting an _element selector_ β this is a selector that directly matches an HTML element name. To target all paragraphs in the document, you would use the selector `p`. To turn all paragraphs green, you would use:
```css
p {
color: green;
}
```
You can target multiple selectors at the same time by separating the selectors with a comma. If you want all paragraphs and all list items to be green, your rule would look like this:
```css
p,
li {
color: green;
}
```
Try this out in the interactive editor below (edit the code boxes) or in your local CSS document.
{{EmbedGHLiveSample("css-examples/learn/getting-started/started1.html", '100%', 900)}}
## Changing the default behavior of elements
When we look at a well-marked up HTML document, even something as simple as our example, we can see how the browser is making the HTML readable by adding some default styling. Headings are large and bold and our list has bullets. This happens because browsers have internal stylesheets containing default styles, which they apply to all pages by default; without them all of the text would run together in a clump and we would have to style everything from scratch. All modern browsers display HTML content by default in pretty much the same way.
However, you will often want something other than the choice the browser has made. This can be done by choosing the HTML element that you want to change and using a CSS rule to change the way it looks. A good example is `<ul>`, an unordered list. It has list bullets. If you don't want those bullets, you can remove them like so:
```css
li {
list-style-type: none;
}
```
Try adding this to your CSS now.
The `list-style-type` property is a good property to look at on MDN to see which values are supported. Take a look at the page for [`list-style-type`](/en-US/docs/Web/CSS/list-style-type) and you will find an interactive example at the top of the page to try some different values in, then all allowable values are detailed further down the page.
Looking at that page you will discover that in addition to removing the list bullets, you can change them β try changing them to square bullets by using a value of `square`.
## Adding a class
So far, we have styled elements based on their HTML element names. This works as long as you want all of the elements of that type in your document to look the same. To select a subset of the elements without changing the others, you can add a class to your HTML element and target that class in your CSS.
1. In your HTML document, add a [class attribute](/en-US/docs/Web/HTML/Global_attributes/class) to the second list item. Your list will now look like this:
```html
<ul>
<li>Item one</li>
<li class="special">Item two</li>
<li>Item <em>three</em></li>
</ul>
```
2. In your CSS, you can target the class of `special` by creating a selector that starts with a full stop character. Add the following to your CSS file:
```css
.special {
color: orange;
font-weight: bold;
}
```
3. Save and refresh to see what the result is.
You can apply the class of `special` to any element on your page that you want to have the same look as this list item. For example, you might want the `<span>` in the paragraph to also be orange and bold. Try adding a `class` of `special` to it, then reload your page and see what happens.
Sometimes you will see rules with a selector that lists the HTML element selector along with the class:
```css
li.special {
color: orange;
font-weight: bold;
}
```
This syntax means "target any `li` element that has a class of special". If you were to do this, then you would no longer be able to apply the class to a `<span>` or another element by adding the class to it; you would have to add that element to the list of selectors:
```css
li.special,
span.special {
color: orange;
font-weight: bold;
}
```
As you can imagine, some classes might be applied to many elements and you don't want to have to keep editing your CSS every time something new needs to take on that style. Therefore, it is sometimes best to bypass the element and refer to the class, unless you know that you want to create some special rules for one element alone, and perhaps want to make sure they are not applied to other things.
## Styling things based on their location in a document
There are times when you will want something to look different based on where it is in the document. There are a number of selectors that can help you here, but for now we will look at just a couple. In our document, there are two `<em>` elements β one inside a paragraph and the other inside a list item. To select only an `<em>` that is nested inside an `<li>` element, you can use a selector called the **descendant combinator**, which takes the form of a space between two other selectors.
Add the following rule to your stylesheet:
```css
li em {
color: rebeccapurple;
}
```
This selector will select any `<em>` element that is inside (a descendant of) an `<li>`. So in your example document, you should find that the `<em>` in the third list item is now purple, but the one inside the paragraph is unchanged.
Something else you might like to try is styling a paragraph when it comes directly after a heading at the same hierarchy level in the HTML. To do so, place a `+` (an **next-sibling combinator**) between the selectors.
Try adding this rule to your stylesheet as well:
```css
h1 + p {
font-size: 200%;
}
```
The live example below includes the two rules above. Try adding a rule to make a span red if it is inside a paragraph. You will know if you have it right because the span in the first paragraph will be red, but the one in the first list item will not change color.
{{EmbedGHLiveSample("css-examples/learn/getting-started/started2.html", '100%', 1100)}}
> **Note:** As you can see, CSS gives us several ways to target elements, and we've only scratched the surface so far! We will be taking a proper look at all of these selectors and many more in our [Selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors) articles later on in the course.
## Styling things based on state
The final type of styling we shall take a look at in this tutorial is the ability to style things based on their state. A straightforward example of this is when styling links. When we style a link, we need to target the [`<a>`](/en-US/docs/Web/HTML/Element/a) (anchor) element. This has different states depending on whether it is unvisited, visited, being hovered over, focused via the keyboard, or in the process of being clicked (activated). You can use CSS to target these different states β the CSS below styles unvisited links pink and visited links green.
```css
a:link {
color: pink;
}
a:visited {
color: green;
}
```
You can change the way the link looks when the user hovers over it, for example by removing the underline, which is achieved by the next rule:
```css
a:hover {
text-decoration: none;
}
```
In the live example below, you can play with different values for the various states of a link. We have added the rules above to it, and now realize that the pink color is quite light and hard to read β why not change that to a better color? Can you make the links bold?
{{EmbedGHLiveSample("css-examples/learn/getting-started/started3.html", '100%', 1000)}}
We have removed the underline on our link on hover. You could remove the underline from all states of a link. It is worth remembering however that in a real site, you want to ensure that visitors know that a link is a link. Leaving the underline in place can be an important clue for people to realize that some text inside a paragraph can be clicked on β this is the behavior they are used to. As with everything in CSS, there is the potential to make the document less accessible with your changes β we will aim to highlight potential pitfalls in appropriate places.
> **Note:** you will often see mention of [accessibility](/en-US/docs/Learn/Accessibility) in these lessons and across MDN. When we talk about accessibility we are referring to the requirement for our webpages to be understandable and usable by everyone.
>
> Your visitor may well be on a computer with a mouse or trackpad, or a phone with a touchscreen. Or they might be using a screen reader, which reads out the content of the document, or they may need to use much larger text, or be navigating the site using the keyboard only.
>
> A plain HTML document is generally accessible to everyone β as you start to style that document it is important that you don't make it less accessible.
## Combining selectors and combinators
It is worth noting that you can combine multiple selectors and combinators together. For example:
```css
/* selects any <span> that is inside a <p>, which is inside an <article> */
article p span {
}
/* selects any <p> that comes directly after a <ul>, which comes directly after an <h1> */
h1 + ul + p {
}
```
You can combine multiple types together, too. Try adding the following into your code:
```css
body h1 + p .special {
color: yellow;
background-color: black;
padding: 5px;
}
```
This will style any element with a class of `special`, which is inside a `<p>`, which comes just after an `<h1>`, which is inside a `<body>`. Phew!
In the original HTML we provided, the only element styled is `<span class="special">`.
Don't worry if this seems complicated at the moment β you'll soon start to get the hang of it as you write more CSS.
## Summary
In this article, we have taken a look at a number of ways in which you can style a document using CSS. We will be developing this knowledge as we move through the rest of the lessons. However, you now already know enough to style text, apply CSS based on different ways of targeting elements in the document, and look up properties and values in the MDN documentation.
In the next lesson, we'll be taking a look at [how CSS is structured](/en-US/docs/Learn/CSS/First_steps/How_CSS_is_structured).
{{PreviousMenuNext("Learn/CSS/First_steps/What_is_CSS", "Learn/CSS/First_steps/How_CSS_is_structured", "Learn/CSS/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/css/first_steps | data/mdn-content/files/en-us/learn/css/first_steps/what_is_css/index.md | ---
title: What is CSS?
slug: Learn/CSS/First_steps/What_is_CSS
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/CSS/First_steps/Getting_started", "Learn/CSS/First_steps")}}
**{{Glossary("CSS")}}** (Cascading Style Sheets) allows you to create great-looking web pages, but how does it work under the hood? This article explains what CSS is with a simple syntax example and also covers some key terms about the language.
<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 learn what CSS is.</td>
</tr>
</tbody>
</table>
In the [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) module, we covered what HTML is and how it is used to mark up documents. These documents will be readable in a web browser. Headings will look larger than regular text, paragraphs break onto a new line and have space between them. Links are colored and underlined to distinguish them from the rest of the text. What you are seeing are the browser's default styles β very basic styles β that the browser applies to HTML to make sure that the page will be basically readable even if no explicit styling is specified by the author of the page.

However, the web would be a boring place if all websites looked like that. Using CSS, you can control exactly how HTML elements look in the browser, presenting your markup using whatever design you like.
For more on browser/default styles, check out the following video:
{{EmbedYouTube("spK_S0HfzFw")}}
## What is CSS for?
As we have mentioned before, CSS is a language for specifying how documents are presented to users β how they are styled, laid out, etc.
A **document** is usually a text file structured using a markup language β {{Glossary("HTML")}} is the most common markup language, but you may also come across other markup languages such as {{Glossary("SVG")}} or {{Glossary("XML")}}.
**Presenting** a document to a user means converting it into a form usable by your audience. {{Glossary("browser","Browsers")}}, like {{Glossary("Mozilla Firefox","Firefox")}}, {{Glossary("Google Chrome","Chrome")}}, or {{Glossary("Microsoft Edge","Edge")}}, are designed to present documents visually, for example, on a computer screen, projector, or printer.
> **Note:** A browser is sometimes called a {{Glossary("User agent","user agent")}}, which basically means a computer program that represents a person inside a computer system. Browsers are the main type of user agents we think of when talking about CSS, however, they are not the only ones. There are other user agents available, such as those that convert HTML and CSS documents into PDFs to be printed.
CSS can be used for very basic document text styling β for example, for changing the [color](/en-US/docs/Web/CSS/color_value) and [size](/en-US/docs/Web/CSS/font-size) of headings and links. It can be used to create a layout β for example, [turning a single column of text into a layout](/en-US/docs/Web/CSS/Layout_cookbook/Column_layouts) with a main content area and a sidebar for related information. It can even be used for effects such as [animation](/en-US/docs/Web/CSS/CSS_animations). Have a look at the links in this paragraph for specific examples.
## CSS syntax
CSS is a rule-based language β you define the rules by specifying groups of styles that should be applied to particular elements or groups of elements on your web page.
For example, you can decide to have the main heading on your page to be shown as large red text. The following code shows a very simple CSS rule that would achieve the styling described above:
```css
h1 {
color: red;
font-size: 5em;
}
```
- In the above example, the CSS rule opens with a {{Glossary("CSS Selector", "selector")}}. This _selects_ the HTML element that we are going to style. In this case, we are styling level one headings ({{htmlelement("Heading_Elements", "h1")}}).
- We then have a set of curly braces `{ }`.
- Inside the braces will be one or more **declarations**, which take the form of **property** and **value** pairs. We specify the property (`color` in the above example) before the colon, and we specify the value of the property after the colon (`red` in this example).
- This example contains two declarations, one for `color` and the other for `font-size`. Each pair specifies a property of the element(s) we are selecting ({{htmlelement("Heading_Elements", "h1")}} in this case), then a value that we'd like to give the property.
CSS {{Glossary("property/CSS","properties")}} have different allowable values, depending on which property is being specified. In our example, we have the `color` property, which can take various [color values](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#color). We also have the `font-size` property. This property can take various [size units](/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#numbers_lengths_and_percentages) as a value.
A CSS stylesheet will contain many such rules, written one after the other.
```css
h1 {
color: red;
font-size: 5em;
}
p {
color: black;
}
```
You will find that you quickly learn some values, whereas others you will need to look up. The individual property pages on MDN give you a quick way to look up properties and their values when you forget or when you want to know what else you can use as a value.
> **Note:** You can find links to all the CSS property pages (along with other CSS features) listed on the MDN [CSS reference](/en-US/docs/Web/CSS/Reference). Alternatively, you should get used to searching for "mdn _css-feature-name_" in your favorite search engine whenever you need to find out more information about a CSS feature. For example, try searching for "mdn color" and "mdn font-size"!
## CSS modules
As there are so many things that you could style using CSS, the language is broken down into _modules_. You'll see reference to these modules as you explore MDN. Many of the documentation pages are organized around a particular module. For example, you could take a look at the MDN reference to the [Backgrounds and Borders](/en-US/docs/Web/CSS/CSS_backgrounds_and_borders) module to find out what its purpose is and the properties and features it contains. In that module, you will also find a link to _Specifications_ that defines the technology (also see the section below).
At this stage, you don't need to worry too much about how CSS is structured; however, it can make it easier to find information if, for example, you are aware that a certain property is likely to be found among other similar things, and is therefore, probably in the same specification.
For a specific example, let's go back to the Backgrounds and Borders module β you might think that it makes logical sense for the [`background-color`](/en-US/docs/Web/CSS/background-color) and [`border-color`](/en-US/docs/Web/CSS/border-color) properties to be defined in this module. And you'd be right.
## CSS specifications
All web standards technologies (HTML, CSS, JavaScript, etc.) are defined in giant documents called specifications (or "specs"), which are published by standards organizations (such as the {{glossary("W3C")}}, {{glossary("WHATWG")}}, {{glossary("ECMA")}}, or {{glossary("Khronos")}}) and define precisely how those technologies are supposed to behave.
CSS is no different β it is developed by a group within the W3C called the [CSS Working Group](https://www.w3.org/Style/CSS/). This group is made of representatives of browser vendors and other companies who have an interest in CSS. There are also other people, known as _invited experts_, who act as independent voices; they are not linked to a member organization.
New CSS features are developed or specified by the CSS Working Group β sometimes because a particular browser is interested in having some capability, other times because web designers and developers are asking for a feature, and sometimes because the Working Group itself has identified a requirement. CSS is constantly developing, with new features becoming available. However, a key thing about CSS is that everyone works very hard to never change things in a way that would break old websites. A website built in 2000, using the limited CSS available then, should still be usable in a browser today!
As a newcomer to CSS, it is likely that you will find the CSS specs overwhelming β they are intended for engineers to use to implement support for the features in user agents, not for web developers to read to understand CSS. Many experienced developers would much rather refer to MDN documentation or other tutorials. Nevertheless, it is worth knowing that these specs exist and understanding the relationship between the CSS you are using, the browser support (see below), and the specs.
## Browser support information
After a CSS feature has been specified, then it is only useful for us in developing web pages if one or more browsers have implemented the feature. This means that the code has been written to turn the instruction in our CSS file into something that can be output to the screen. We'll look at this process more in the lesson [How CSS works](/en-US/docs/Learn/CSS/First_steps/How_CSS_works). It is unusual for all browsers to implement a feature at the same time, and so there is usually a gap where you can use some part of CSS in some browsers and not in others. For this reason, being able to check implementation status is useful.
The browser support status is shown on every MDN CSS property page in a table named "Browser compatibility". Consult the information in that table to check if the property can be used on your website. For an example, see the [browser compatibility table for the CSS `font-family` property](/en-US/docs/Web/CSS/font-family#browser_compatibility).
Based on your requirements, you can use the browser compatibility table to check how this property is supported across various browsers, or check if your specific browser and the version you have support the property, or if there are any caveats you should be aware of for the browser and version you are using.
## Summary
You made it to the end of the article! Now that you have some understanding of what CSS is, let's move on to [Getting started with CSS](/en-US/docs/Learn/CSS/First_steps/Getting_started), where you can start to write some CSS yourself.
{{NextMenu("Learn/CSS/First_steps/Getting_started", "Learn/CSS/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/css/first_steps | data/mdn-content/files/en-us/learn/css/first_steps/how_css_is_structured/index.md | ---
title: How CSS is structured
slug: Learn/CSS/First_steps/How_CSS_is_structured
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/First_steps/Getting_started", "Learn/CSS/First_steps/How_CSS_works", "Learn/CSS/First_steps")}}
Now that you are beginning to understand the purpose and use of CSS, let's examine the structure of 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
> 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 learn CSS's fundamental syntax structures in detail.</td>
</tr>
</tbody>
</table>
## Applying CSS to HTML
First, let's examine three methods of applying CSS to a document: with an external stylesheet, with an internal stylesheet, and with inline styles.
### External stylesheet
An external stylesheet contains CSS in a separate file with a `.css` extension. This is the most common and useful method of bringing CSS to a document. You can link a single CSS file to multiple web pages, styling all of them with the same CSS stylesheet. In the [Getting started with CSS](/en-US/docs/Learn/CSS/First_steps/Getting_started), we linked an external stylesheet to our web page.
You reference an external CSS stylesheet from an HTML `<link>` element:
```html
<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8" />
<title>My CSS experiment</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
</body>
</html>
```
The CSS stylesheet file might look like this:
```css
h1 {
color: blue;
background-color: yellow;
border: 1px solid black;
}
p {
color: red;
}
```
The `href` attribute of the {{htmlelement("link")}} element needs to reference a file on your file system. In the example above, the CSS file is in the same folder as the HTML document, but you could place it somewhere else and adjust the path. Here are three examples:
```html
<!-- Inside a subdirectory called styles inside the current directory -->
<link rel="stylesheet" href="styles/style.css" />
<!-- Inside a subdirectory called general, which is in a subdirectory called styles, inside the current directory -->
<link rel="stylesheet" href="styles/general/style.css" />
<!-- Go up one directory level, then inside a subdirectory called styles -->
<link rel="stylesheet" href="../styles/style.css" />
```
### Internal stylesheet
An internal stylesheet resides within an HTML document. To create an internal stylesheet, you place CSS inside a {{htmlelement("style")}} element contained inside the HTML {{htmlelement("head")}}.
The HTML for an internal stylesheet might look like this:
```html
<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8" />
<title>My CSS experiment</title>
<style>
h1 {
color: blue;
background-color: yellow;
border: 1px solid black;
}
p {
color: red;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
</body>
</html>
```
In some circumstances, internal stylesheets can be useful. For example, perhaps you're working with a content management system where you are blocked from modifying external CSS files.
But for sites with more than one page, an internal stylesheet becomes a less efficient way of working. To apply uniform CSS styling to multiple pages using internal stylesheets, you must have an internal stylesheet in every web page that will use the styling. The efficiency penalty carries over to site maintenance too. With CSS in internal stylesheets, there is the risk that even one simple styling change may require edits to multiple web pages.
### Inline styles
Inline styles are CSS declarations that affect a single HTML element, contained within a `style` attribute. The implementation of an inline style in an HTML document might look like this:
```html
<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8" />
<title>My CSS experiment</title>
</head>
<body>
<h1 style="color: blue;background-color: yellow;border: 1px solid black;">
Hello World!
</h1>
<p style="color:red;">This is my first CSS example</p>
</body>
</html>
```
**Avoid using CSS in this way, when possible.** It is the opposite of a best practice. First, it is the least efficient implementation of CSS for maintenance. One styling change might require multiple edits within a single web page. Second, inline CSS also mixes (CSS) presentational code with HTML and content, making everything more difficult to read and understand. Separating code and content makes maintenance easier for all who work on the website.
There are a few circumstances where inline styles are more common. You might have to resort to using inline styles if your working environment is very restrictive. For example, perhaps your CMS only allows you to edit the HTML body. You may also see a lot of inline styles in HTML email to achieve compatibility with as many email clients as possible.
## Playing with the CSS in this article
For the exercise that follows, create a folder on your computer. You can name the folder whatever you want. Inside the folder, copy the text below to create two files:
**index.html:**
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>My CSS experiments</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<p>Create your test HTML here</p>
</body>
</html>
```
**styles.css:**
```css
/* Create your test CSS here */
p {
color: red;
}
```
When you find CSS that you want to experiment with, replace the HTML `<body>` contents with some HTML to style, and then add your test CSS code to your CSS file.
As an alternative, you can also use the interactive editor below.
{{EmbedGHLiveSample("css-examples/learn/getting-started/experiment-sandbox.html", '100%', 800)}}
Read on and have fun!
## Selectors
A selector targets HTML to apply styles to content. We have already discovered a variety of selectors in the [Getting started with CSS](/en-US/docs/Learn/CSS/First_steps/Getting_started) tutorial. If CSS is not applying to content as expected, your selector may not match the way you think it should match.
Each CSS rule starts with a selector β or a list of selectors β in order to tell the browser which element or elements the rules should apply to. All the examples below are valid selectors or lists of selectors.
```css
h1
a:link
.manythings
#onething
*
.box p
.box p:first-child
h1, h2, .intro
```
Try creating some CSS rules that use the selectors above. Add HTML to be styled by the selectors. If any of the syntax above is not familiar, try searching MDN.
> **Note:** You will learn more about selectors in the next module: [CSS selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors).
### Specificity
You may encounter scenarios where two selectors select the same HTML element. Consider the stylesheet below, with a `p` selector that sets paragraph text to blue. However, there is also a class that sets the text of selected elements to red.
```css
.special {
color: red;
}
p {
color: blue;
}
```
Suppose that in our HTML document, we have a paragraph with a class of `special`. Both rules apply. Which selector prevails? Do you expect to see blue or red paragraph text?
```html
<p class="special">What color am I?</p>
```
The CSS language has rules to control which selector is stronger in the event of a conflict. These rules are called **cascade** and **specificity**. In the code block below, we define two rules for the `p` selector, but the paragraph text will be blue. This is because the declaration that sets the paragraph text to blue appears later in the stylesheet. Later styles replace conflicting styles that appear earlier in the stylesheet. This is the **cascade** rule.
```css
p {
color: red;
}
p {
color: blue;
}
```
However, in the case of our earlier example with the conflict between the class selector and the element selector, the class prevails, rendering the paragraph text red. How can this happen even though a conflicting style appears later in the stylesheet? A class is rated as being more specific, as in having more **specificity** than the element selector, so it cancels the other conflicting style declaration.
Try this experiment for yourself! Add HTML, then add the two `p { }` rules to your stylesheet. Next, change the first `p` selector to `.special` to see how it changes the styling.
The rules of specificity and the cascade can seem complicated at first. These rules are easier to understand as you become more familiar with CSS. The [Cascade and inheritance](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance) section in the next module explains this in detail, including how to calculate specificity.
For now, remember that specificity exists. Sometimes, CSS might not apply as you expected because something else in the stylesheet has more specificity. Recognizing that more than one rule could apply to an element is the first step in fixing these kinds of issues.
## Properties and values
At its most basic level, CSS consists of two components:
- **Properties**: These are human-readable identifiers that indicate which stylistic features you want to modify. For example, {{cssxref("font-size")}}, {{cssxref("width")}}, {{cssxref("background-color")}}.
- **Values**: Each property is assigned a value. This value indicates how to style the property.
The example below highlights a single property and value. The property name is `color` and the value is `blue`.

When a property is paired with a value, this pairing is called a _CSS declaration_. CSS declarations are found within _CSS Declaration Blocks_. In the example below, highlighting identifies the CSS declaration block.

Finally, CSS declaration blocks are paired with _selectors_ to produce _CSS rulesets_ (or _CSS rules_). The example below contains two rules: one for the `h1` selector and one for the `p` selector. The colored highlighting identifies the `h1` rule.

Setting CSS properties to specific values is the primary way of defining layout and styling for a document. The CSS engine calculates which declarations apply to every single element of a page.
CSS properties and values are case-insensitive. The property and value in a property-value pair are separated by a colon (`:`).
**Look up different values of properties listed below. Write CSS rules that apply styling to different HTML elements:**
- **{{cssxref("font-size")}}**
- **{{cssxref("width")}}**
- **{{cssxref("background-color")}}**
- **{{cssxref("color")}}**
- **{{cssxref("border")}}**
> **Warning:** If a property is unknown, or if a value is not valid for a given property, the declaration is processed as _invalid_. It is completely ignored by the browser's CSS engine.
> **Warning:** In CSS (and other web standards), it has been agreed that US spelling is the standard where there is language variation or uncertainty. For example, `colour` should be spelled `color`, as `colour` will not work.
### Functions
While most values are relatively simple keywords or numeric values, there are some values that take the form of a function.
#### The calc() function
An example would be the `calc()` function, which can do simple math within CSS:
```html
<div class="outer"><div class="box">The inner box is 90% - 30px.</div></div>
```
```css
.outer {
border: 5px solid black;
}
.box {
padding: 10px;
width: calc(90% - 30px);
background-color: rebeccapurple;
color: white;
}
```
This renders as:
{{EmbedLiveSample('The_calc_function', '100%', 200)}}
A function consists of the function name, and parentheses to enclose the values for the function. In the case of the `calc()` example above, the values define the width of this box to be 90% of the containing block width, minus 30 pixels. The result of the calculation isn't something that can be computed in advance and entered as a static value.
#### Transform functions
Another example would be the various values for {{cssxref("transform")}}, such as `rotate()`.
```html
<div class="box"></div>
```
```css
.box {
margin: 30px;
width: 100px;
height: 100px;
background-color: rebeccapurple;
transform: rotate(0.8turn);
}
```
The output from the above code looks like this:
{{EmbedLiveSample('Transform_functions', '100%', 200)}}
**Look up different values of properties listed below. Write CSS rules that apply styling to different HTML elements:**
- **{{cssxref("transform")}}**
- **{{cssxref("background-image")}}, in particular gradient values**
- **{{cssxref("color")}}, in particular rgb and hsl values**
## @rules
CSS [@rules](/en-US/docs/Web/CSS/At-rule) (pronounced "at-rules") provide instruction for what CSS should perform or how it should behave. Some @rules are simple with just a keyword and a value. For example, `@import` imports a stylesheet into another CSS stylesheet:
```css
@import "styles2.css";
```
One common @rule that you are likely to encounter is `@media`, which is used to create [media queries](/en-US/docs/Web/CSS/CSS_media_queries). Media queries use conditional logic for applying CSS styling.
In the example below, the stylesheet defines a default pink background for the `<body>` element. However, a media query follows that defines a blue background if the browser viewport is wider than 30em.
```css
body {
background-color: pink;
}
@media (min-width: 30em) {
body {
background-color: blue;
}
}
```
You will encounter other @rules throughout these tutorials.
**See if you can add a media query that changes styles based on the viewport width. Change the width of your browser window to see the result.**
## Shorthands
Some properties like {{cssxref("font")}}, {{cssxref("background")}}, {{cssxref("padding")}}, {{cssxref("border")}}, and {{cssxref("margin")}} are called **shorthand properties.** This is because shorthand properties set several values in a single line.
For example, this one line of code:
```css
/* In 4-value shorthands like padding and margin, the values are applied
in the order top, right, bottom, left (clockwise from the top). There are also other
shorthand types, for example 2-value shorthands, which set padding/margin
for top/bottom, then left/right */
padding: 10px 15px 15px 5px;
```
is equivalent to these four lines of code:
```css
padding-top: 10px;
padding-right: 15px;
padding-bottom: 15px;
padding-left: 5px;
```
This one line:
```css
background: red url(bg-graphic.png) 10px 10px repeat-x fixed;
```
is equivalent to these five lines:
```css
background-color: red;
background-image: url(bg-graphic.png);
background-position: 10px 10px;
background-repeat: repeat-x;
background-attachment: fixed;
```
Later in the course, you will encounter many other examples of shorthand properties. MDN's [CSS reference](/en-US/docs/Web/CSS/Reference) is a good resource for more information about any shorthand property.
**Try using the declarations (above) in your own CSS exercise to become more familiar with how it works. You can also experiment with different values.**
> **Warning:** One less obvious aspect of using CSS shorthand is how omitted values reset. A value not specified in CSS shorthand reverts to its initial value. This means an omission in CSS shorthand can **override previously set values**.
## Comments
As with any coding work, it is best practice to write comments along with CSS. This helps you to remember how the code works as you come back later for fixes or enhancement. It also helps others understand the code.
CSS comments begin with `/*` and end with `*/`. In the example below, comments mark the start of distinct sections of code. This helps to navigate the codebase as it gets larger. With this kind of commenting in place, searching for comments in your code editor becomes a way to efficiently find a section of code.
```css
/* Handle basic element styling */
/* -------------------------------------------------------------------------------------------- */
body {
font:
1em/150% Helvetica,
Arial,
sans-serif;
padding: 1em;
margin: 0 auto;
max-width: 33em;
}
@media (min-width: 70em) {
/* Increase the global font size on larger screens or windows
for better readability */
body {
font-size: 130%;
}
}
h1 {
font-size: 1.5em;
}
/* Handle specific elements nested in the DOM */
div p,
#id:first-line {
background-color: red;
border-radius: 3px;
}
div p {
margin: 0;
padding: 1em;
}
div p + p {
padding-top: 0;
}
```
"Commenting out" code is also useful for temporarily disabling sections of code for testing. In the example below, the rules for `.special` are disabled by "commenting out" the code.
```css
/*.special {
color: red;
}*/
p {
color: blue;
}
```
**Add comments to your CSS.**
## White space
White space means actual spaces, tabs and new lines. Just as browsers ignore white space in HTML, browsers ignore white space inside CSS. The value of white space is how it can improve readability.
In the example below, each declaration (and rule start/end) has its own line. This is arguably a good way to write CSS. It makes it easier to maintain and understand CSS.
```css
body {
font:
1em/150% Helvetica,
Arial,
sans-serif;
padding: 1em;
margin: 0 auto;
max-width: 33em;
}
@media (min-width: 70em) {
body {
font-size: 130%;
}
}
h1 {
font-size: 1.5em;
}
div p,
#id:first-line {
background-color: red;
border-radius: 3px;
}
div p {
margin: 0;
padding: 1em;
}
div p + p {
padding-top: 0;
}
```
The next example shows the equivalent CSS in a more compressed format. Although the two examples work the same, the one below is more difficult to read.
```css-nolint
body {font: 1em/150% Helvetica, Arial, sans-serif; padding: 1em; margin: 0 auto; max-width: 33em;}
@media (min-width: 70em) { body { font-size: 130%;}}
h1 {font-size: 1.5em;}
div p, #id:first-line {background-color: red; border-radius: 3px;}
div p {margin: 0; padding: 1em;}
div p + p {padding-top: 0;}
```
For your own projects, you will format your code according to personal preference. For team projects, you may find that a team or project has its own style guide.
> **Warning:** Though white space separates values in CSS declarations, **property names never have white space**.
For example, these declarations are valid CSS:
```css
margin: 0 auto;
padding-left: 10px;
```
But these declarations are invalid:
```css example-bad
margin: 0auto;
padding- left: 10px;
```
Do you see the spacing errors? First, `0auto` is not recognized as a valid value for the `margin` property. The entry `0auto` is meant to be two separate values: `0` and `auto`. Second, the browser does not recognize `padding-` as a valid property. The correct property name (`padding-left`) is separated by an errant space.
You should always make sure to separate distinct values from one another by at least one space. Keep property names and property values together as single unbroken strings.
**To find out how spacing can break CSS, try playing with spacing inside your test CSS.**
## Summary
At this point, you should have a better idea about how CSS is structured. It's also useful to understand how the browser uses HTML and CSS to display a webpage. The next article, [How CSS works](/en-US/docs/Learn/CSS/First_steps/How_CSS_works), explains the process.
{{PreviousMenuNext("Learn/CSS/First_steps/Getting_started", "Learn/CSS/First_steps/How_CSS_works", "Learn/CSS/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/css/first_steps | data/mdn-content/files/en-us/learn/css/first_steps/styling_a_biography_page/index.md | ---
title: Styling a biography page
slug: Learn/CSS/First_steps/Styling_a_biography_page
page-type: learn-module-assessment
---
{{LearnSidebar}}{{PreviousMenu("Learn/CSS/First_steps/How_CSS_works", "Learn/CSS/First_steps")}}
With the things you have learned in the last few lessons you should find that you can format simple text documents using CSS to add your own style to them. This assessment gives you a chance to do that.
<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 CSS and test your new-found knowledge.</td>
</tr>
</tbody>
</table>
## Starting point
You can work in the live editor below, or you can [download the starting point file](https://github.com/mdn/css-examples/blob/main/learn/getting-started/biog-download.html) to work with in your own editor. This is a single page containing both the HTML and the starting point CSS (in the head of the document). If you prefer you could move this CSS to a separate file and link to it when you create the example on your local computer.
> **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).
## Project brief
The following live example shows a biography, which has been styled using CSS. The CSS properties that are used are as follows β each one links to its property page on MDN, which will give you more examples of its use.
- {{cssxref("font-family")}}
- {{cssxref("color")}}
- {{cssxref("border-bottom")}}
- {{cssxref("font-weight")}}
- {{cssxref("font-size")}}
- {{cssxref("font-style")}}
- {{cssxref("text-decoration")}}
In the interactive editor you will find some CSS already in place. This selects parts of the document using element selectors, classes, and pseudo-classes. Make the following changes to this CSS:
1. Make the level one heading pink, using the CSS color keyword `hotpink`.
2. Give the heading a 10px dotted {{cssxref("border-bottom")}} which uses the CSS color keyword `purple`.
3. Make the level 2 heading italic.
4. Give the `ul` used for the contact details a {{cssxref("background-color")}} of `#eeeeee`, and a 5px solid purple {{cssxref("border")}}. Use some {{cssxref("padding")}} to push the content away from the border.
5. Make the links `green` on hover.
## Hints and tips
- Use the [W3C CSS Validator](https://jigsaw.w3.org/css-validator/) to catch unintended mistakes in your CSS β mistakes you might have otherwise missed β so that you can fix them.
- Afterwards try looking up some properties not mentioned on this page in the [MDN CSS reference](/en-US/docs/Web/CSS/Reference) and get adventurous!
- Remember that there is no wrong answer here β at this stage in your learning you can afford to have a bit of fun.
## Example
You should end up with something like this image.

{{EmbedGHLiveSample("css-examples/learn/getting-started/biog.html", '100%', 1600)}}
{{PreviousMenu("Learn/CSS/First_steps/How_CSS_works", "Learn/CSS/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/css/first_steps | data/mdn-content/files/en-us/learn/css/first_steps/how_css_works/index.md | ---
title: How CSS works
slug: Learn/CSS/First_steps/How_CSS_works
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/CSS/First_steps/How_CSS_is_structured", "Learn/CSS/First_steps/Styling_a_biography_page", "Learn/CSS/First_steps")}}
We have learned the basics of CSS, what it is for and how to write simple stylesheets. In this lesson we will take a look at how a browser takes CSS and HTML and turns that into a webpage.
<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 basics of how CSS and HTML are parsed by the browser,
and what happens when a browser encounters CSS it does not understand.
</td>
</tr>
</tbody>
</table>
## How does CSS actually work?
When a browser displays a document, it must combine the document's content with its style information. It processes the document in a number of stages, which we've listed below. Bear in mind that this is a very simplified version of what happens when a browser loads a webpage, and that different browsers will handle the process in different ways. But this is roughly what happens.
1. The browser loads the HTML (e.g. receives it from the network).
2. It converts the {{Glossary("HTML")}} into a {{Glossary("DOM")}} (_Document Object Model_). The DOM represents the document in the computer's memory. The DOM is explained in a bit more detail in the next section.
3. The browser then fetches most of the resources that are linked to by the HTML document, such as embedded images, videos, and even linked CSS! JavaScript is handled a bit later on in the process, and we won't talk about it here to keep things simpler.
4. The browser parses the fetched CSS, and sorts the different rules by their selector types into different "buckets", e.g. element, class, ID, and so on. Based on the selectors it finds, it works out which rules should be applied to which nodes in the DOM, and attaches style to them as required (this intermediate step is called a render tree).
5. The render tree is laid out in the structure it should appear in after the rules have been applied to it.
6. The visual display of the page is shown on the screen (this stage is called painting).
The following diagram also offers a simple view of the process.

## About the DOM
A DOM has a tree-like structure. Each element, attribute, and piece of text in the markup language becomes a {{Glossary("Node/DOM","DOM node")}} in the tree structure. The nodes are defined by their relationship to other DOM nodes. Some elements are parents of child nodes, and child nodes have siblings.
Understanding the DOM helps you design, debug and maintain your CSS because the DOM is where your CSS and the document's content meet up. When you start working with browser DevTools you will be navigating the DOM as you select items in order to see which rules apply.
## A real DOM representation
Rather than a long, boring explanation, let's look at an example to see how a real HTML snippet is converted into a DOM.
Take the following HTML code:
```html
<p>
Let's use:
<span>Cascading</span>
<span>Style</span>
<span>Sheets</span>
</p>
```
In the DOM, the node corresponding to our `<p>` element is a parent. Its children are a text node and the three nodes corresponding to our `<span>` elements. The `SPAN` nodes are also parents, with text nodes as their children:
```plain
P
ββ "Let's use:"
ββ SPAN
| ββ "Cascading"
ββ SPAN
| ββ "Style"
ββ SPAN
ββ "Sheets"
```
This is how a browser interprets the previous HTML snippet β it renders the above DOM tree and then outputs it in the browser like so:
{{EmbedLiveSample('A_real_DOM_representation', '100%', 55)}}
```css hidden
p {
margin: 0;
}
```
## Applying CSS to the DOM
Let's say we add some CSS to our document, to style it. Again, the HTML is as follows:
```html
<p>
Let's use:
<span>Cascading</span>
<span>Style</span>
<span>Sheets</span>
</p>
```
Let's suppose we apply the following CSS to it:
```css
span {
border: 1px solid black;
background-color: lime;
}
```
The browser parses the HTML and creates a DOM from it. Next, it parses the CSS. Since the only rule available in the CSS has a `span` selector, the browser sorts the CSS very quickly! It applies that rule to each one of the three `<span>`s, then paints the final visual representation to the screen.
The updated output is as follows:
{{EmbedLiveSample('Applying_CSS_to_the_DOM', '100%', 90)}}
In our [Debugging CSS](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS) article in the next module we will be using browser DevTools to debug CSS problems, and will learn more about how the browser interprets CSS.
## What happens if a browser encounters CSS it doesn't understand?
The ["Browser support information" section in the "What is CSS" article](/en-US/docs/Learn/CSS/First_steps/What_is_CSS#browser_support_information) mentioned that browsers do not necessarily implement new CSS features at the same time. In addition, many people are not using the latest version of a browser. Given that CSS is being developed all the time, and is therefore ahead of what browsers can recognize, you might wonder what happens if a browser encounters a CSS selector or declaration it doesn't recognize.
The answer is that it does nothing, and just moves on to the next bit of CSS!
If a browser is parsing your rules, and encounters a property or value that it doesn't understand, it ignores it and moves on to the next declaration. It will do this if you have made an error and misspelled a property or value, or if the property or value is just too new and the browser doesn't yet support it.
Similarly, if a browser encounters a selector that it doesn't understand, it will just ignore the whole rule and move on to the next one.
In the example below I have used the British English spelling for color, which makes that property invalid as it is not recognized. So my paragraph has not been colored blue. All of the other CSS have been applied however; only the invalid line is ignored.
```html
<p>I want this text to be large, bold and blue.</p>
```
```css
p {
font-weight: bold;
colour: blue; /* incorrect spelling of the color property */
font-size: 200%;
}
```
{{EmbedLiveSample('What_happens_if_a_browser_encounters_CSS_it_doesnt_understand', '100%', 200)}}
This behavior is very useful. It means that you can use new CSS as an enhancement, knowing that no error will occur if it is not understood β the browser will either get the new feature or not. This enables basic fallback styling.
This works particularly well when you want to use a value that is quite new and not supported everywhere. For example, some older browsers do not support `calc()` as a value. I might give a fallback width for a box in pixels, then go on to give a width with a `calc()` value of `100% - 50px`. Old browsers will use the pixel version, ignoring the line about `calc()` as they don't understand it. New browsers will interpret the line using pixels, but then override it with the line using `calc()` as that line appears later in the cascade.
```css
.box {
width: 500px;
width: calc(100% - 50px);
}
```
We will look at many more ways to support various browsers in later lessons.
## Summary
You've nearly finished this module β we only have one more thing to do. In the [Styling a biography page assessment](/en-US/docs/Learn/CSS/First_steps/Styling_a_biography_page) you'll use your new knowledge to restyle an example, testing out some CSS in the process.
{{PreviousMenuNext("Learn/CSS/First_steps/How_CSS_is_structured", "Learn/CSS/First_steps/Styling_a_biography_page", "Learn/CSS/First_steps")}}
| 0 |
data/mdn-content/files/en-us/learn/css/first_steps | data/mdn-content/files/en-us/learn/css/first_steps/how_css_works/rendering.svg | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 635 245"><style>@font-face{font-family:'open_sanssemibold';src:url(data:application/x-font-opentype;charset=utf-8;base64,AAEAAAATAQAABAAwRkZUTWfOXwkAAAE8AAAAHEdERUYAZgAEAAABWAAAACBHUE9TECH6YwAAAXgAAALSR1NVQpM8gksAAARMAAAAUE9TLzKhy73TAAAEnAAAAGBjbWFwpkuXDgAABPwAAAFiY3Z0IBPbDf4AAAZgAAAAOmZwZ21TtC+nAAAGnAAAAmVnYXNwAAAAEAAACQQAAAAIZ2x5ZgLNdmwAAAkMAAAgVGhlYWQKowZEAAApYAAAADZoaGVhD04FGwAAKZgAAAAkaG10eAUXFaoAACm8AAAA5GxvY2HTnN0QAAAqoAAAAHRtYXhwAVQBRAAAKxQAAAAgbmFtZWTusSEAACs0AAAE+nBvc3TOYv/WAAAwMAAAAKtwcmVwjm2IcAAAMNwAAADzd2ViZiE+Vh4AADHQAAAABgAAAAEAAAAAzD2izwAAAADJTOp9AAAAANJD0bwAAQAAAA4AAAAYAAAAAAACAAEAAQA4AAEABAAAAAIAAAABAAAACgBUAGIABERGTFQAGmN5cmwAJmdyZWsAMmxhdG4APgAEAAAAAP//AAEAAAAEAAAAAP//AAEAAAAEAAAAAP//AAEAAAAEAAAAAP//AAEAAAABa2VybgAIAAAAAQAAAAEABAACAAAAAQAIAAECLgAEAAAAGQA8AGIAgABiAJIAmACAAJ4AYgDEAGIA0gE0AToBOgCAAYQB0gHkAeQB+gHkAeQCEAH6AAkABv/XAAr/1wANAQoAEv/XABT/1wAX/3EAGf+uABr/rgAc/4UABwAE/9cAF//DABn/7AAa/+wAG//XABz/7AAd/+wABAAG/9cACv/XABL/1wAU/9cAAQANAHsAAQAE/9cACQAG/9cACv/XABL/1wAU/9cAF//XABj/7AAZ/9cAGv/XABz/wwADAAT/mgAb/9cAHf/sABgABP9xAAb/1wAK/9cAEv/XABT/1wAXACkAHv9cACD/cQAh/3EAIv9xACT/cQAq/5oAK/+aACz/cQAt/5oALv9xAC//mgAw/4UAMv+aADP/1wA0/9cANf/XADb/1wA3/64AAQAE/+wAEgAE/64ABv/sAAr/7AAS/+wAFP/sAB7/1wAg/9cAIf/XACL/1wAk/+wAKv/sACv/7AAs/9cALf/sAC7/1wAv/+wAMP/sADL/7AATAAT/hQAG/9cACv/XABL/1wAU/9cAHv+aACD/mgAh/5oAIv+aACT/1wAq/8MAK//DACz/mgAt/8MALv+aAC//wwAw/64AMv/DADf/1wAEAAb/7AAK/+wAEv/sABT/7AAFADP/1wA0/9cANf/XADb/1wA3/+wABQAg/9cAIf/XACL/1wAs/9cALv/XAAcAHv/XACD/1wAh/9cAIv/XACT/7AAs/9cALv/XAAEAGQAEAAUABgAHAAgACQAOAA8AEgATABQAFwAYABkAGgAbABwAHQAfACIAKAAsAC0ALwA1AAAAAQAAAAoATABOAARERkxUABpjeXJsACRncmVrAC5sYXRuADgABAAAAAD//wAAAAQAAAAA//8AAAAEAAAAAP//AAAABAAAAAD//wAAAAAAAAADBLECWAAFAAQFmgUzAAABHwWaBTMAAAPRAGYB9gAAAgsHBgMIBAICBOAAAu9AACBbAAAAKAAAAAAxQVNDACAADSX8Bmb+ZgAACGQCaiAAAZ8AAAAABFIFtgAAACAAAgAAAAMAAAADAAAAHAABAAAAAABcAAMAAQAAABwABABAAAAADAAIAAIABAANACAAWgB6Jfz//wAAAA0AIABBAGEl/P////X/4//D/73aPAABAAAAAAAAAAAAAAAAAAABBgAAAQAAAAAAAAABAgAAAAIAAAAAAAAAAAAAAAAAAAABAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHQAAAAAAAB4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEUgW2AM0AgwCXAKIAqgC0ALoAwADEAMgA2QEEAOsA6wDvAKwA4QDVANAA6ADkAKQAlAC3AEQFEQAAsAAssAATS7BMUFiwSnZZsAAjPxiwBitYPVlLsExQWH1ZINSwARMuGC2wASwg2rAMKy2wAixLUlhFI1khLbADLGkYILBAUFghsEBZLbAELLAGK1ghIyF6WN0bzVkbS1JYWP0b7VkbIyGwBStYsEZ2WVjdG81ZWVkYLbAFLA1cWi2wBiyxIgGIUFiwIIhcXBuwAFktsAcssSQBiFBYsECIXFwbsABZLbAILBIRIDkvLbAJLCB9sAYrWMQbzVkgsAMlSSMgsAQmSrAAUFiKZYphILAAUFg4GyEhWRuKimEgsABSWDgbISFZWRgtsAossAYrWCEQGxAhWS2wCywg0rAMKy2wDCwgL7AHK1xYICBHI0ZhaiBYIGRiOBshIVkbIVktsA0sEhEgIDkvIIogR4pGYSOKIIojSrAAUFgjsABSWLBAOBshWRsjsABQWLBAZTgbIVlZLbAOLLAGK1g91hghIRsg1opLUlggiiNJILAAVVg4GyEhWRshIVlZLbAPLCMg1iAvsAcrXFgjIFhLUxshsAFZWIqwBCZJI4ojIIpJiiNhOBshISEhWRshISEhIVktsBAsINqwEistsBEsINKwEistsBIsIC+wBytcWCAgRyNGYWqKIEcjRiNhamAgWCBkYjgbISFZGyEhWS2wEywgiiCKhyCwAyVKZCOKB7AgUFg8G8BZLbAULLMAQAFAQkIBS7gQAGMAS7gQAGMgiiCKVVggiiCKUlgjYiCwACNCG2IgsAEjQlkgsEBSWLIAIABDY0KyASABQ2NCsCBjsBllHCFZGyEhWS2wFSywAUNjI7AAQ2MjLQAAAAABAAH//wAPAAIARAAAAmQFVQADAAcALrEBAC88sgcEG+0ysQYF3DyyAwIb7TIAsQMALzyyBQQb7TKyBwYc/DyyAQIb7TIzESERJSERIUQCIP4kAZj+aAVV+qtEBM0AAAACAAAAAAVKBbwABwAPACwAsgAAACuwAzOyAQIAK7QGCAABDSuxBgPpAbAQL7ERASsAsQEIERKwDTkwMTEBIQEjAyEDEyEDLgEnBgcCIwEEAiP+kv3Rj9UBqokPNQobNAW8+kQBlv5qAmQBjiisKHuSAAAAAAMAwQAABNkFtgAPABgAIQBnALIAAAArsRAM6bICAgArsSEM6bQZGAACDSuxGQrpAbAiL7AA1rEQEemwGTKwEBCxFAErsQwR6bAdINYRsQUR6bEjASuxHRARErEJCDk5ALEYEBESsAw5sBkRsQgJOTmwIRKwBTkwMTMRISAEFRQGBxUeARUUBCMlMzI2NTQmKwE1MzI2NTQmKwHBAbIBLgENhHyakf7t9f7f/paZnJ/y5paKlaLPBbawvoCqFgodq5LF38lzfHJuwl9yZ1wAAAABAHn/7ATPBcsAGAA9ALIWAAArsRAD6bIEAgArsQoD6QGwGS+wANaxDRHpsRoBKwCxEBYRErAUObAKEbIABxM5OTmwBBKwBjkwMRM0EiQzMhcHLgEjIgIREBIzMjY3FQYjIAB5pwE81eC+VkqlW87s49ddrl6s2v6//qgC2+QBVrZexyM1/tz+//7z/uwlHc1BAYUAAgDBAAAFZgW2AAgADwA4ALIIAAArsQkM6bICAgArsQ8M6QGwEC+wANaxCRHpsAkQsQwBK7EFEemxEQErALEPCRESsAU5MDEzESEgABEQACEnMyARECEjwQHEAV0BhP5u/oaqqgIQ/hXPBbb+iP6r/pb+gckCGAINAAAAAAEAwQAAA/wFtgALAEcAsgAAACuxCQPpsgECACuxBAzptAUIAAENK7EFDOkBsAwvsADWsQkR6bAEMrIJAAors0AJCwkrsAIys0AJBwkrsQ0BKwAwMTMRIRUhESEVIREhFcEDO/20Aif92QJMBbbK/nLI/jXLAAAAAAEAwQAAA/oFtgAJAEAAsgAAACuyAQIAK7EEDOm0CAUAAQ0rsQgD6QGwCi+wANaxCQ/psAQysgkACiuzQAkDCSuzQAkHCSuxCwErADAxMxEhFSERIRUhEcEDOf20Aif92QW2yv43y/2oAAAAAAEAef/sBTEFywAaAHgAshgAACuxDgzpsgMCACuxCAPptBITGAMNK7ESA+kBsBsvsADWsQsR6bALELEQASuxFQ/pshAVCiuzQBASCSuxHAErsRALERKyAwgYOTk5sBURsQYFOTkAsQ4YERKwFTmxExIRErEACzk5sAgRsAY5sAMSsAU5MDETEAAhMhcHJiMiABUQEjMyNxEhNSERDgEjIAB5AZYBZOXNVLKy6v7w9eZ0hP7RAhqE843+tP6YAtsBYQGPWMdS/tr//vT+6R0Bec39IiskAYkAAAEAwQAABUIFtgALAD8AsgAAACuwBzOyAQIAK7AFM7QDCgABDSuxAwPpAbAML7AA1rELEemwAjKwCxCxCAErsAQysQcR6bENASsAMDEzETMRIREzESMRIRHB7wKi8PD9XgW2/aoCVvpKApP9bQAAAAABAMEAAAGwBbYAAwAhALIAAAArsgECACsBsAQvsADWsQMR6bEDEemxBQErADAxMxEzEcHvBbb6SgAAAAAB/2T+aAGqBbYADAAtALIFAgArsAovsQID6QGwDS+wBNaxBxHpsQ4BKwCxAgoRErAMObAFEbAAOTAxBxYzMjURMxEUBiMiJ5xUPsTw1c1iQrYV+AWJ+n/g7RkAAAEAwQAABR0FtgAOADAAsgAAACuwCjOyAQIAK7AGMwGwDy+wANaxDhHpsAIysRABKwCxAQARErEDDDk5MDEzETMRNjcBIQAHASEBBxHB72JhAYsBEP6BpgI0/uv+NY0Ftv1GeG8B0/4+v/zLApZz/d0AAAAAAQDBAAAEGwW2AAUALACyAAAAK7EDA+myAQIAKwGwBi+wANaxAxHpsgMACiuzQAMFCSuxBwErADAxMxEzESEVwe8CawW2+xfNAAAAAAEAwQAABqIFtgAUAF4AsgAAACuxBw4zM7IBAgArsAUzAbAVL7AA1rEUD+m0EQ8AKAQrsBQQsQgBK7EHD+mxFgErsRQRERKwEDmwCBGzAgUODyQXObAHErEMDTk5ALEBABESsgMMEDk5OTAxMxEhATMBIREjETQSNyMBIwEjEhURwQFRAZYGAaIBUuYLBAj+SdP+WAgRBbb7dQSL+koC020BXiX7PQTF/vDu/TkAAAAAAQDBAAAFgwW2ABEAUgCyAAAAK7AKM7IBAgArsAgzAbASL7AA1rERD+mwERCxBwErsQoP6bETASuxEQARErEMDTk5sAcRsQILOTmwChKxAwQ5OQCxAQARErEDDDk5MDEzESEBMyYCNREzESEBIxcWFRHBASICzQYCDNv+2/0xCAUOBbb7eRcBIVEC/vpKBI1Bupr9CAAAAAACAHn/7AXTBc0ACwAXAEQAsgkAACuxDwPpsgMCACuxFQPpAbAYL7AA1rEMEemwDBCxEgErsQYR6bEZASuxEgwRErEDCTk5ALEVDxESsQAGOTkwMRMQACEgABEQACEgABMQEjMyEhEQAiMiAnkBZQFLAUYBZP6b/rn+tf6d/trW1dnX1dfbAt8BagGE/nb+mv6b/nQBiQFo/vL+6QEUAREBDQEW/uoAAAACAMEAAASJBbYACgATAEIAsgAAACuyAgIAK7ETDOm0CQsAAg0rsQkM6QGwFC+wANaxChHpsAsysAoQsQ8BK7EFEemxFQErALETCxESsAU5MDEzESEgBBUUBCEjGQEzMjY1NCYrAcEBpQESARH+1P7rmH+4rJqjpgW24Nrl9P3dAuyAiH58AAAAAgB5/qQF0wXNAA8AGwBTALINAAArsRMD6bIDAgArsRkD6QGwHC+wANaxEBHpsBAQsRYBK7EGEemxHQErsRYQERKzAwsMCSQXObAGEbAKOQCxEw0RErAJObAZEbEABjk5MDETEAAhIAAREAIHASEBIyAAExASMzISERACIyICeQFlAUsBRgFky8IBXv6+/uwn/rX+nf7a1tXZ19XX2wLfAWoBhP52/pr+9v6USv6HAUgBiQFo/vL+6QEUAREBDQEW/uoAAAIAwQAABQoFtgAMABUAWwCyAAAAK7AIM7ICAgArsRUM6bQLDQACDSuxCwvpAbAWL7AA1rEMEemwDTKwDBCxEQErsQUR6bEXASuxEQwRErEKBzk5sAURsAk5ALENCxESsAc5sBURsAU5MDEzESEgBBUQBQEhASMZATMyNjU0JisBwQGdARsBEP7kAZ3+8P6i7KanlqKjngW21Nb+73T9eQJI/bgDDnx6fGwAAAABAGT/7AQMBcsAJABoALIjAAArsQQM6bIQAgArsRUD6QGwJS+wDdaxGA/psBgQsQcBK7EgD+mxJgErsRgNERKwCzmwBxG1BAoQFRwjJBc5sCASshITHTk5OQCxBCMRErAAObAVEbMBDRMgJBc5sBASsBI5MDE3NR4BMzI2NTQmJy4BNTQkMzIXByYjIgYVFB4BFx4CFRQEIyJkZOFhjod8wsikAQTb0tBMw5l0eDBuj6GWRv7m+Pg54i82bFtSck5R0JK30lzDUmVTOVFIO0N0kmPD3gAAAAABAB0AAARoBbYABwA6ALIGAAArsgECACuxAAPpsAMyAbAIL7AG1rEFEemyBQYKK7NABQMJK7IGBQors0AGAAkrsQkBKwAwMRM1IRUhESMRHQRL/lLvBOnNzfsXBOkAAAABALT/7AU7BbYAEQA3ALIPAAArsQYD6bIBAgArsAkzAbASL7AA1rEDEemwAxCxCAErsQsR6bETASuxCAMRErAPOQAwMRMRMxEUFjMgGQEzERQGBCMgALTwqK4BUu+L/vm3/vD+0gIIA678Y7WsAWMDm/xOovODASAAAAAAAQAAAAAE+gW2AAwAIQCyDAAAK7IAAgArsAkzAbANL7EOASsAsQAMERKwBTkwMREzAR4BFz4BNwEzASP2ATEYNggNNhEBMfj+APwFtvxzQc0yTMgwA4n6SgAAAAABAAwAAAeDBbYAHAD8ALIbAAArsBEzsgACACuzAQgJDyQXMwGwHS+wANaxARHpsAEQsQ8BK7EQEemxHgErsDYausHY8MEAFSsKDrAAELAcwLABELACwLo+APAfABUrCgWwCC4OsAfAsRcU+bAZwLrCce5+ABUrCgWwCS4OsArAsRUV+bATwLMUFRMTK7o+SfFJABUrC7AZELMYGRcTK7IYGRcgiiCKIwYOERI5shQVEyCKIIojBg4REjkAQAoCBwoTGRwUFRcYLi4uLi4uLi4uLgFADAIHCAkKExkcFBUXGC4uLi4uLi4uLi4uLrBAGgGxDwERErERGzk5ALEAGxESsgQMFjk5OTAxEzMTFhc+ATcTMxMWFzY3EzMBIQMuAScOAQcDIQMM9NExFQssEu7t9CMnDznQ8v6D/vz4EDAFCi0P8v78vQW2/KzNnVXSQQNW/KZ37Y/dA1L6SgNoOdcqQMwy/JwC3AABAAQAAAT2BbYACwAmALIAAAArsAgzsgICACuwBTMBsAwvsQ0BKwCxAgARErEECjk5MDEzCQEhCQEhCQEhCQEEAeX+OgEKAVIBUgEC/jcB7P7t/pL+jwL2AsD91wIp/Tz9DgJW/aoAAAEAAAAABLwFtgAIADAAsgcAACuyAAIAK7ADMwGwCS+wB9axBhHpsQoBK7EGBxESsAI5ALEABxESsAI5MDERIQkBIQERIxEBBAFaAVoBBP4Z8AW2/WUCm/yB/ckCLwAAAAEAQgAABFgFtgAJAC4AsgAAACuxBwPpsgQCACuxAwPpAbAKL7ELASsAsQcAERKwATmxBAMRErAGOTAxMzUBITUhFQEhFUIC4f0zA+79HAL4pgRDzaj7v80AAAAAAgBa/+wEBARmABsAJgB/ALIUAAArshkAACuxHwjpsg8BACuxCAjptAMkGQ8NK7EDBekBsCcvsADWsRwR6bAcELEiASuwBDKxEg/psSgBK7EcABESsQsMOTmwIhGyDxkIOTk5sBISsBY5ALEfFBESsRUWOTmwJBGwADmwAxKwAjmwCBGwCzmwDxKwDDkwMRM0NiU3NTQmIyIGByc+ATMyFhURIycjDgEjIiY3FBYzMjY9AQcOAVr+AQS/Y2hVnEhMWtZf09eoLwhQon+jt/RYWICbjqaXAT2rrggGO2ppMiKoLzG4xf0XmmVJsJ9KUY+BYAYGYwAAAAACAKj/7ASTBhQAEwAfAGMAsgAAACuyDwAAK7EXCumyCQEAK7EcCumwAS8BsCAvsADWsRQP6bACMrAUELEaASuxDBHpsSEBK7EUABESsgYHETk5ObAaEbEJDzk5ALEXABESsBE5sBwRsAw5sAkSsAY5MDEzETMRFAYHMzYzMhIREAIjIicjBxMUFjMyNjUQISIGB6jrCAIKcNrP5+rQ0nQQKzuAkX2B/v6OfQIGFP6OKaIWpf7U/vH+8P7Rl4MCK8q1xrsBeafEAAEAZv/sA7QEZgAVAD0AshMAACuxDQvpsgMBACuxCAvpAbAWL7AA1rEKEemxFwErALENExESsBA5sAgRsgAGDzk5ObADErAFOTAxExAAITIXByYjIBEUFjMyNxUOASMiAGYBEQECr4xHlWH+4Y+KnYw/j2b7/vsCIwEXASxBvTr+g7q7Ts0lIAElAAAAAgBm/+wEVAYUABIAHwBrALIMAAArshAAACuxFgrpsgMBACuxHQrpsAkvAbAgL7AA1rETEemwExCxCAErsBkysQoP6bEhASuxCBMRErQDDhAWHSQXObAKEbIFBhg5OTkAsRYMERKxDQ45ObAdEbAAObADErEFBjk5MDETEBIzMhczJjURMxEjJyMGIyICExQWMzI2NzU0JiMiBmbr0NpyDBHsuCkLcdrP6PKCgpGEAoiRfIYCJwEQAS+hd0UBk/nskaUBLAELuMGjtyHRsMkAAAIAZv/sBDkEZgAUABsAZgCyEgAAK7ELCemyAwEAK7EZCOm0FQgSAw0rsRUH6QGwHC+wANaxCBHpsBUysAgQsRYBK7EGD+mxHQErsRYIERKyAwsSOTk5sAYRsQ4POTkAsQsSERKwDzmwCBGwDjmwFRKwADkwMRMQADMyEh0BIR4BMzI2NxUOASMgABMhLgEjIgZmAQ7s2/79HwWklWKpYVawcf7+/t32AfYCgHBwhwIhAQ8BNv726X+hrSUrvykiAS0BhYmNjgAAAQAjAAADQgYfABUAYACyFAAAK7IPAQArsRII6bAAMrICAQArsAsvsQYK6QGwFi+wFNawAjKxEw/psA4yshMUCiuzQBMRCSuyFBMKK7NAFAAJK7EXASsAsQ8SERKwATmwCxGwCTmwBhKwCDkwMRM1NzU0NjMyFwcmIyIGHQEhFSERIxEjtri9fHg+V09QSQEO/vLsA6BuSEjEvSmyHGNjSLL8YAOgAAAAAwAX/hQETgRmACsAOABDAMQAshIBACuxQQTpsBQysg8BACuxQQXpsCkvsS8G6bA2L7EiDOmwGy+xPAXpAbBEL7AM1rE5D+mwACDWEbQsDwAwBCuwORCwHyDWEbQGDwAfBCuwBi+0Hw8AHwQrsDkQsT4BK7EYD+mzMhg+CCuxJg/psUUBK7E5LBESsQkDOTmxPh8RErcSGw8jKS88QSQXObEYMhESsBU5ALE2LxESsSYAOTmwIhGwAzmwGxKxBh85ObA8EbEJHTk5sEESshUYDDk5OTAxFzQ2Ny4BNTQ2Ny4BNTQ2MzIWFyEVBx4BFRQGIyInBhUUFjsBMhYVFAQhIiY3FBYzMjY1NCYrASIGExQWMzI1NCYjIgYXgXQvPUZFVmvj0i9nGgF/vRoi7M81K0xHX8G3vv7K/tvi7tKJfMC8Z4yyZXdla2TMZWdmabhmixsUWTE+Violp3C0xg0HgSMjZjmrxAgvPyYmnJO8zKCgTFJuW0g9XwNHaHDabHV0AAAAAAEAqAAABHUGFAAVAE0AsgAAACuwDDOyCQEAK7ERCumwAS8BsBYvsADWsRUP6bACMrAVELENASuxDA/psRcBK7EVABESsAU5sA0RsQYJOTkAsQkRERKwBTkwMTMRMxEUBzM+ATMgGQEjETQmIyIGFRGo6wwPMKtyAZLsZ3CUiwYU/nVfbFBY/mv9LwKogH6x0P3bAAACAJoAAAGiBfoACwAPADkAsgwAACuyDQEAK7AJL7EDDukBsBAvsADWsAwysQYR6bEPD+mxBhHpsREBK7EPABESsQMJOTkAMDETNDYzMhYVFAYjIiYTETMRmkVAPkVFPkBFDusFdz9ERD88RUX6xQRS+64AAAL/h/4UAaIF+gAMABgARQCyBQEAK7AKL7ECCumwFi+xEA7pAbAZL7AE1rANMrEHD+mxExHpsRoBK7EHBBESsRAWOTkAsQIKERKwDDmwBRGwADkwMQMWMzI1ETMRFAYjIicBNDYzMhYVFAYjIiZ5REeW67OpakYBE0VAPkVFPkBF/ucSqgTT+x2rsBkHSj9ERD88RUUAAAAAAQCoAAAEiQYUAA4AOgCyAAAAK7AKM7IHAQArsAEvAbAPL7AA1rEOD+mwAjKxEAErsQ4AERKxBAU5OQCxBwARErEEDDk5MDEzETMRBzM3ASEJASEBBxGo6QwGhQFOAQ/+QwHZ/uz+nYEGFP0J1aYBZP4l/YkB5Wr+hQAAAAEAqAAAAZMGFAADAB8AsgAAACuwAS8BsAQvsADWsQMP6bEDD+mxBQErADAxMxEzEajrBhT57AAAAQCoAAAHBgRmACMAcACyAAAAK7ERGjMzsgEBACuyBwEAK7ANM7EfCumwFjIBsCQvsADWsSMP6bAjELEbASuxGg/psBoQsRIBK7ERD+mxJQErsSMAERKwBDmwGxGwBzmwGhKxCgk5ObASEbANOQCxAR8RErMDBAkKJBc5MDEzETMXMz4BMyAXMz4BMzIWFREjETQmIyIGFREjETQmIyIGFRGouCEMLq9pAP9TEDGyc8a162FmiX/sYGaIfwRSkU9WrlJcyM39LwKqf32rsf22Aqp/fbHO/dkAAQCoAAAEdQRmABMATACyAAAAK7AKM7IBAQArsgcBACuxDwrpAbAUL7AA1rETD+mwExCxCwErsQoP6bEVASuxEwARErAEObALEbAHOQCxAQ8RErEDBDk5MDEzETMXMz4BMyAZASMRNCYjIgYVEai4IQwyuHABjuxncJWKBFKRT1b+a/0vAqiAfrDP/dkAAAAAAgBm/+wEfQRmAAwAFQBEALIJAAArsQ8K6bIDAQArsRMK6QGwFi+wANaxDRHpsA0QsREBK7EGEemxFwErsRENERKxAwk5OQCxEw8RErEGADk5MDETEAAzMgAREAAjIiYCNxAhIBEQISIGZgEU+/ABGP7q+JvugPIBGwEY/uaUhQIrAQ0BLv7L/vr+8f7QjAEGrf6BAX8Be8QAAAAAAgCo/hQEkwRmABMAIABuALINAAArsRcK6bIBAQArsgcBACuxHQrpsAAvAbAhL7AA1rETD+mwFDK0Ag8AHwQrsBMQsRoBK7EKEemxIgErsRMCERKyBQ8QOTk5sBoRsQcNOTkAsRcNERKxDxA5ObAdEbAKObABErEEBTk5MDETETMWFzM2MzISERACIyInIxYVGQEUFjMyNjU0JiMiBhWovggZDG7cz+frz9J0Dg6AkXqEg3+Mgf4UBj4fdaj+1P7x/vH+0JeMHv47BBfKtci5ur+ktAACAGb+FARUBGYAFAAgAHIAshIAACuxFwnpsggBACuyAwEAK7EeCumwCy8BsCEvsADWsRUR6bAVELELASuwGjKxCg/psAoQtAgPAB8EK7AIL7EiASuxCxURErQDEBIXHiQXObAIEbEGDzk5ALEXEhESsA85sB4RsAA5sAgSsAY5MDETEBIzMhYXMzczESMRNDY3IwYjIgITECEyNj0BNCYjIgZm7M9opUEIGsPsCAMNaOPN6PIBBpSBhZR+hAInAQ4BMU1YkfnCAdUsYhqlAS0BCv6Fq60lzbTIAAAAAQCoAAADTgRmABAAPwCyAAAAK7IBAQArsgcBACuxDA3pAbARL7AA1rEQD+m0Ag8AFgQrsRIBK7EQAhESsAQ5ALEBDBESsQMEOTkwMTMRMxczPgEzMhcHJiMiBhURqLgfDDexZkcuFzI2ja8EUsNjdArbDLiT/b4AAQBi/+wDjwRmACEAawCyFAAAK7EZCOmyAwEAK7EICOkBsCIvsADWsBYysQoP6bAKELEbASuxEQ/psSMBK7EKABESsCA5sBsRtQMIDRQZHyQXObARErIGDgU5OTkAsRkUERKwFjmwCBGzAAYRFyQXObADErAFOTAxEzQ2MzIXByYjIhUUFhceAhUUBiMiJzUWMzI1NC4BJy4BYuXFw65Ms3q6YaOJfDzs3N2Gw6jZMG5iv4cDO46dT7FKajRIPzVYc1CirUPLWoMqODwmSpQAAAEAJ//sAvAFSAAVAHAAshIAACuxDArpsgUBACuxCAjpsAAysgUICiuzQAUDCSuyAgEAKwGwFi+wFNaxCQ/psAQysgkUCiuzQAkHCSuwDjKyFAkKK7NAFAAJK7EXASuxCRQRErACOQCxDBIRErAPObAIEbAOObAFErABOTAxEzU/ATMVIRUhERQWMzI3FQ4BIyAZASeiUJEBO/7FVUVWVid7Qv6yA6BoVur2sv2wVVEbsREXAWACVAABAJ7/7ARtBFIAFABMALINAAArshIAACuxBgrpsgEBACuwCjMBsBUvsADWsQMP6bADELEJASuxCw/psRYBK7EJAxESsBI5sAsRsA85ALEGDRESsQ4POTkwMRMRMxEUFjMyNjURMxEjJyMOASMiJp7taG+Ui+y5IQwxtXTJxgF/AtP9Vn9/sdACJ/uukU1YyAABAAAAAARIBFIACwAhALILAAArsgABACuwCDMBsAwvsQ0BKwCxAAsRErAEOTAxETMTFhczNjcTMwEj+OE6DAgJPeH6/lr+BFL9faJkSL4Cg/uuAAABABQAAAZzBFIAHQC5ALIdAAArsBQzsgABACuyAQoSMzMzAbAeL7AA1rEBEemwARCxEgErsRMP6bEfASuwNhq6wgrv+AAVKwqwABCwHcAOsAEQsALAusJf7r0AFSsKBbAKLg6wDcCxGAr5sBbAsAoQswsKDRMrswwKDRMrsgsKDSCKIIojBg4REjmwDDkAtQILFhgMDS4uLi4uLgG3AgoLFhgdDA0uLi4uLi4uLrBAGgGxEgERErAUOQCxAB0RErEEDjk5MDETMxMWFzM+ATcTIRMeARczNjcTMwEhAyYDIwIHAyEU8I0wFAYKKQ+oAQKjDy0ECA83j+z+yP74jxpECToik/78BFL938qQSb0vAkb9ujHKOHvdAiH7rgIEUgEr/vJx/f4AAAEAGQAABE4EUgALACYAsgAAACuwCDOyAgEAK7AFMwGwDC+xDQErALECABESsQQKOTkwMTMJASEbASEJASEJARkBhf6NAQz8/gEK/owBh/72/u/+8AI1Ah3+fQGD/eP9ywGe/mIAAAAAAQAA/hQESgRSABQAKwCyAAEAK7AIM7AML7ERCukBsBUvsRYBKwCxEQwRErAOObAAEbEEDzk5MDERIRMWFzM+ARMzAQIhIic1FjMyPwEBAOEzEQgJMOb+/ieB/tNOSjVEqkUpBFL9jYZ2N50Cm/sb/qcRugzFaAAAAQBEAAADiwRSAAkALgCyAAAAK7EHCOmyBAEAK7EDCOkBsAovsQsBKwCxBwARErABObEEAxESsAY5MDEzNQEhNSEVASEVRAIv/fMDFf3dAjORAw20pP0GtAAAAAABAAAAAARRBFEAAwAnALIAAAArsgEBACsBsAQvsADWtAMRAAcEK7QDEQAHBCuxBQErADAxMREhEQRRBFH7rwAAAQAAAAEZmkZDfmNfDzz1AB8IAAAAAADSQ9G9AAAAANJD0b3/ZP4UB4MGHwABAAgAAgAAAAAAAAABAAAIZP2WAAAHpv9k/6UHgwABAAAAAAAAAAAAAAAAAAAAOQLsAEQAAAAABBQAAAIUAAAFSgAABUgAwQUSAHkF3wDBBHcAwQRCAMEFzwB5BgIAwQJxAMECZP9kBR0AwQRWAMEHYgDBBkQAwQZMAHkE7ADBBkwAeQUdAMEEZgBkBIcAHQXwALQE+gAAB5EADAT6AAQEvAAABJoAQgSkAFoE/ACoA/YAZgT8AGYEnABmAucAIwRzABcFFACoAjsAmgI7/4cEkwCoAjsAqAemAKgFFACoBOMAZgT8AKgE/ABmA3MAqAPlAGIDJQAnBRQAngRIAAAGiQAUBGgAGQRKAAAD0wBEBFEAAAAAACwALAAsACwAZgDOARgBVgGSAcgCNAJsAooCuALyAxgDcAO8BBAEVAS2BQwFeAWoBeYGFAbIBvwHLAdaB9YIOgiACOgJTAmgCmIKrArmCzILcAuMC/gMQAyODPgNZg2iDgoOZg6uDtgPbA+gD9wQChAqAAEAAAA5AEQAAwAAAAAAAgABAAIAFgAAAQAA/AAAAAAAAAAUAPYAAwABBAkAAABoAAAAAwABBAkAAQAkAGgAAwABBAkAAgAOAIwAAwABBAkAAwBOAJoAAwABBAkABAA0AOgAAwABBAkABQAYARwAAwABBAkABgAiATQAAwABBAkABwCkAVYAAwABBAkACAAoAfoAAwABBAkACwA4AiIAAwABBAkADABcAloAAwABBAkADQBcArYAAwABBAkADgBUAxIAAwABBAkAEAASA2YAAwABBAkAEQAQA3gAAwABBAkAyAAWA4gAAwABBAkAyQAwA54AAwABBAkAygAOA84AAwABBAkAywAOA9wAAwABBAnZAwAaA+oARABpAGcAaQB0AGkAegBlAGQAIABkAGEAdABhACAAYwBvAHAAeQByAGkAZwBoAHQAIACpACAAMgAwADEAMQAsACAARwBvAG8AZwBsAGUAIABDAG8AcgBwAG8AcgBhAHQAaQBvAG4ALgBPAHAAZQBuACAAUwBhAG4AcwAgAFMAZQBtAGkAYgBvAGwAZABSAGUAZwB1AGwAYQByAEEAcwBjAGUAbgBkAGUAcgAgAC0AIABPAHAAZQBuACAAUwBhAG4AcwAgAFMAZQBtAGkAYgBvAGwAZAAgAEIAdQBpAGwAZAAgADEAMAAwAE8AcABlAG4AIABTAGEAbgBzACAAUwBlAG0AaQBiAG8AbABkACAAUgBlAGcAdQBsAGEAcgBWAGUAcgBzAGkAbwBuACAAMQAuADEAMABPAHAAZQBuAFMAYQBuAHMALQBTAGUAbQBpAGIAbwBsAGQATwBwAGUAbgAgAFMAYQBuAHMAIABpAHMAIABhACAAdAByAGEAZABlAG0AYQByAGsAIABvAGYAIABHAG8AbwBnAGwAZQAgAGEAbgBkACAAbQBhAHkAIABiAGUAIAByAGUAZwBpAHMAdABlAHIAZQBkACAAaQBuACAAYwBlAHIAdABhAGkAbgAgAGoAdQByAGkAcwBkAGkAYwB0AGkAbwBuAHMALgBBAHMAYwBlAG4AZABlAHIAIABDAG8AcgBwAG8AcgBhAHQAaQBvAG4AaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGEAcwBjAGUAbgBkAGUAcgBjAG8AcgBwAC4AYwBvAG0ALwBoAHQAdABwADoALwAvAHcAdwB3AC4AYQBzAGMAZQBuAGQAZQByAGMAbwByAHAALgBjAG8AbQAvAHQAeQBwAGUAZABlAHMAaQBnAG4AZQByAHMALgBoAHQAbQBsAEwAaQBjAGUAbgBzAGUAZAAgAHUAbgBkAGUAcgAgAHQAaABlACAAQQBwAGEAYwBoAGUAIABMAGkAYwBlAG4AcwBlACwAIABWAGUAcgBzAGkAbwBuACAAMgAuADAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGEAcABhAGMAaABlAC4AbwByAGcALwBsAGkAYwBlAG4AcwBlAHMALwBMAEkAQwBFAE4AUwBFAC0AMgAuADAATwBwAGUAbgAgAFMAYQBuAHMAUwBlAG0AaQBiAG8AbABkAFcAZQBiAGYAbwBuAHQAIAAxAC4AMABXAGUAZAAgAE8AYwB0ACAAMQA0ACAAMAA1ADoAMwAyADoANAA1ACAAMgAwADEANQBkAGUAZgBhAHUAbAB0AHAAZQByAHMAZQB1AHMARgBvAG4AdAAgAFMAcQB1AGkAcgByAGUAbAAAAAIAAAAAAAD/ZgBmAAAAAAAAAAAAAAAAAAAAAAAAAAAAOQAAAQIBAwADACQAJQAmACcAKAApACoAKwAsAC0ALgAvADAAMQAyADMANAA1ADYANwA4ADkAOgA7ADwAPQBEAEUARgBHAEgASQBKAEsATABNAE4ATwBQAFEAUgBTAFQAVQBWAFcAWABZAFoAWwBcAF0BBAZnbHlwaDEHdW5pMDAwRAd1bmkyNUZDALgB/4WwAY0AS7AIUFixAQGOWbFGBitYIbAQWUuwFFJYIbCAWR2wBitcWACwAyBFsAMrRLAMIEWyA9cCK7ADK0SwCyBFsgxzAiuwAytEsAogRbILVQIrsAMrRLAJIEWyCjcCK7ADK0SwCCBFsgktAiuwAytEsAcgRbIIIwIrsAMrRLAGIEWyBxkCK7ADK0SwBSBFsgZfAiuwAytEsAQgRbIFDwIrsAMrRLANIEWyA2gCK7ADK0SwDiBFsg0YAiuwAytEAbAPIEWwAytEsBAgRboAD3//AAIrsQNGditEsBEgRboAEAEbAAIrsQNGditEWbAUKwAAAVYeIT0AAA==) format('truetype');font-weight:400;font-style:normal}@font-face{font-family:'open_sansbold';src:url(data:application/x-font-opentype;charset=utf-8;base64,AAEAAAATAQAABAAwRkZUTWfDjC0AAAE8AAAAHEdERUYAZgAEAAABWAAAACBHUE9TECH6YwAAAXgAAALSR1NVQpM8gksAAARMAAAAUE9TLzKiSMcwAAAEnAAAAGBjbWFwpkuXDgAABPwAAAFiY3Z0IA7uE6oAAAZgAAAAMGZwZ21TtC+nAAAGkAAAAmVnYXNwAAAAEAAACPgAAAAIZ2x5Zgv3uGQAAAkAAAAg/GhlYWQK4AZGAAAp/AAAADZoaGVhD7QFOQAAKjQAAAAkaG10eA1SFGkAACpYAAAA5GxvY2HYvuKCAAArPAAAAHRtYXhwAVQBWwAAK7AAAAAgbmFtZVLIniEAACvQAAAEinBvc3TOYv/WAAAwXAAAAKtwcmVw5S0OXwAAMQgAAACId2ViZiE/Vh4AADGQAAAABgAAAAEAAAAAzD2izwAAAADJQhegAAAAANJD0b0AAQAAAA4AAAAYAAAAAAACAAEAAQA4AAEABAAAAAIAAAABAAAACgBUAGIABERGTFQAGmN5cmwAJmdyZWsAMmxhdG4APgAEAAAAAP//AAEAAAAEAAAAAP//AAEAAAAEAAAAAP//AAEAAAAEAAAAAP//AAEAAAABa2VybgAIAAAAAQAAAAEABAACAAAAAQAIAAECLgAEAAAAGQA8AGIAgABiAJIAmACAAJ4AYgDEAGIA0gE0AToBOgCAAYQB0gHkAeQB+gHkAeQCEAH6AAkABv/XAAr/1wANAQoAEv/XABT/1wAX/3EAGf+uABr/rgAc/4UABwAE/9cAF//DABn/7AAa/+wAG//XABz/7AAd/+wABAAG/9cACv/XABL/1wAU/9cAAQANAHsAAQAE/9cACQAG/9cACv/XABL/1wAU/9cAF//XABj/7AAZ/9cAGv/XABz/wwADAAT/mgAb/9cAHf/sABgABP9xAAb/1wAK/9cAEv/XABT/1wAXACkAHv9cACD/cQAh/3EAIv9xACT/cQAq/5oAK/+aACz/cQAt/5oALv9xAC//mgAw/4UAMv+aADP/1wA0/9cANf/XADb/1wA3/64AAQAE/+wAEgAE/64ABv/sAAr/7AAS/+wAFP/sAB7/1wAg/9cAIf/XACL/1wAk/+wAKv/sACv/7AAs/9cALf/sAC7/1wAv/+wAMP/sADL/7AATAAT/hQAG/9cACv/XABL/1wAU/9cAHv+aACD/mgAh/5oAIv+aACT/1wAq/8MAK//DACz/mgAt/8MALv+aAC//wwAw/64AMv/DADf/1wAEAAb/7AAK/+wAEv/sABT/7AAFADP/1wA0/9cANf/XADb/1wA3/+wABQAg/9cAIf/XACL/1wAs/9cALv/XAAcAHv/XACD/1wAh/9cAIv/XACT/7AAs/9cALv/XAAEAGQAEAAUABgAHAAgACQAOAA8AEgATABQAFwAYABkAGgAbABwAHQAfACIAKAAsAC0ALwA1AAAAAQAAAAoATABOAARERkxUABpjeXJsACRncmVrAC5sYXRuADgABAAAAAD//wAAAAQAAAAA//8AAAAEAAAAAP//AAAABAAAAAD//wAAAAAAAAADBNcCvAAFAAQFmgUzAAABHwWaBTMAAAPRAGYB/AgCAgsIBgMFBAICBOAAAu9AACBbAAAAKAAAAAAxQVNDACAADSX8Bmb+ZgAACI0CgCAAAZ8AAAAABF4FtgAAACAAAgAAAAMAAAADAAAAHAABAAAAAABcAAMAAQAAABwABABAAAAADAAIAAIABAANACAAWgB6Jfz//wAAAA0AIABBAGEl/P////X/4//D/73aPAABAAAAAAAAAAAAAAAAAAABBgAAAQAAAAAAAAABAgAAAAIAAAAAAAAAAAAAAAAAAAABAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHQAAAAAAAB4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEXgW2AQIA4gD2AP4BMQExATYA1AD0APwBLAEmAQ0AyQERARwBFwEIAIcARAURsAAssAATS7BMUFiwSnZZsAAjPxiwBitYPVlLsExQWH1ZINSwARMuGC2wASwg2rAMKy2wAixLUlhFI1khLbADLGkYILBAUFghsEBZLbAELLAGK1ghIyF6WN0bzVkbS1JYWP0b7VkbIyGwBStYsEZ2WVjdG81ZWVkYLbAFLA1cWi2wBiyxIgGIUFiwIIhcXBuwAFktsAcssSQBiFBYsECIXFwbsABZLbAILBIRIDkvLbAJLCB9sAYrWMQbzVkgsAMlSSMgsAQmSrAAUFiKZYphILAAUFg4GyEhWRuKimEgsABSWDgbISFZWRgtsAossAYrWCEQGxAhWS2wCywg0rAMKy2wDCwgL7AHK1xYICBHI0ZhaiBYIGRiOBshIVkbIVktsA0sEhEgIDkvIIogR4pGYSOKIIojSrAAUFgjsABSWLBAOBshWRsjsABQWLBAZTgbIVlZLbAOLLAGK1g91hghIRsg1opLUlggiiNJILAAVVg4GyEhWRshIVlZLbAPLCMg1iAvsAcrXFgjIFhLUxshsAFZWIqwBCZJI4ojIIpJiiNhOBshISEhWRshISEhIVktsBAsINqwEistsBEsINKwEistsBIsIC+wBytcWCAgRyNGYWqKIEcjRiNhamAgWCBkYjgbISFZGyEhWS2wEywgiiCKhyCwAyVKZCOKB7AgUFg8G8BZLbAULLMAQAFAQkIBS7gQAGMAS7gQAGMgiiCKVVggiiCKUlgjYiCwACNCG2IgsAEjQlkgsEBSWLIAIABDY0KyASABQ2NCsCBjsBllHCFZGyEhWS2wFSywAUNjI7AAQ2MjLQAAAAABAAH//wAPAAIARAAAAmQFVQADAAcALrEBAC88sgcEFu0ysQYF3DyyAwIW7TIAsQMALzyyBQQW7TKyBwYX/DyyAQIW7TIzESERJSERIUQCIP4kAZj+aAVV+qtEBM0AAAACAAAAAAWFBbwABwANAEsAsgAAACuwAzOyAQIAK7QGCAABDSuxBgPpAbAOL7AA1rEHCemwBxCxBAErsQMJ6bEPASuxBAcRErMBAggJJBc5ALEBCBESsAw5MDExASEBIQMhAxMhAiYnBgIEAXsCBv6yav3rargBfZMlCCEFvPpEAVz+pAJgAdl8JIAAAAMAuAAABPQFtgAPABcAIABnALIPAAArsRAD6bICAgArsSAG6bQYFw8CDSuxGAXpAbAhL7AA1rEQCemwGDKwEBCxFAErsQwJ6bAcINYRsQUJ6bEiASuxBRQRErEICTk5ALEXEBESsAw5sBgRsQgJOTmwIBKwBTkwMTMRISAEFRQGBxUeARUUBCMDMzI2NTQhIzUzMjY1NCYrAbgBxwE3ARl7Zot7/t/47cqAev78wLR+cXuFowW2scGDqBEKH6qNyOABAGJltvZOWlRJAAEAd//sBNEFywAWAEUAshQAACuxDwPpsgQCACuxCgPpswcUBAgrAbAXL7AA1rENCemxGAErALEPFBESsBI5sAcRsgANETk5ObEEChESsAY5MDETNBIkMzIXBy4BIyICFRAhMjcRBiMgAHemATfR1ddkUqZQr8ABb5rbtN7+wf6uAtnkAVe3Z/wnOv756/4XTf78SwGDAAAAAgC4AAAFdQW2AAgADwA4ALIIAAArsQkD6bICAgArsQ8G6QGwEC+wANaxCQnpsAkQsQwBK7EFCemxEQErALEPCRESsAU5MDEzESEgABEQACEDMyARECEjuAHLAWYBjP5l/nxohQHA/mClBbb+hv6t/pf+gAEAAeEB1wAAAAEAuAAABAIFtgALAEcAsgAAACuxCQPpsgECACuxBAbptAUIAAENK7EFBukBsAwvsADWsQkJ6bAEMrIJAAors0AJCwkrsAIys0AJBwkrsQ0BKwAwMTMRIRUhESEVIREhEbgDSv3sAe/+EQIUBbb+/r/+/of/AAAAAAEAuAAAA/4FtgAJAEAAsgAAACuyAQIAK7EEBum0CAUAAQ0rsQgG6QGwCi+wANaxCQfpsAQysgkACiuzQAkDCSuzQAkHCSuxCwErADAxMxEhFSERIRUhEbgDRv3rAfD+EAW2/v6H/f2+AAAAAAEAd//sBScFywAaAHkAshgAACuxDgPpsgMCACuxCAPptBITGAMNK7ESA+kBsBsvsADWsQsJ6bALELEQASuxFQfpsAUyshAVCiuzQBASCSuxHAErsRALERKyAwgYOTk5sBURsAY5ALEOGBESsBU5sRMSERKxAAs5ObAIEbAGObADErAFOTAxExAAITIXByYjIgIVFBYzMjcRIREhEQ4BIyAAdwGVAWfh0Wegrcnyw7phZP7rAkSN+YL+tf6jAt0BYgGMWvhQ/vLk7vsUATEBAv0KLiUBhQAAAAEAuAAABWYFtgALAD8AsgAAACuwBzOyAQIAK7AFM7QDCgABDSuxAwPpAbAML7AA1rELCemwAjKwCxCxCAErsAQysQcJ6bENASsAMDEzESERIREhESERIRG4ATYCQwE1/sv9vQW2/cMCPfpKAnf9iQABALgAAAHuBbYAAwAhALIAAAArsgECACsBsAQvsADWsQMJ6bEDCemxBQErADAxMxEhEbgBNgW2+koAAAAB/2j+UgHuBbYADQAtALIGAgArsAsvsQID6QGwDi+wBdaxCAnpsQ8BKwCxAgsRErANObAGEbAAOTAxBxYzMjY1ESEREAIjIieYUEJmWAE26uVpTpYUf4cFWvqo/wD+9BYAAAAAAQC4AAAFUAW2AAwAMACyAAAAK7AIM7IBAgArsAUzAbANL7AA1rEMCemwAjKxDgErALEBABESsQMKOTkwMTMRIRE3ASEJASEBBxG4ATZ6AYwBWP4CAgL+oP6BgwW2/WOsAfH9efzRAmhe/fYAAQC4AAAEPwW2AAUALACyAAAAK7EDA+myAQIAKwGwBi+wANaxAwnpsgMACiuzQAMFCSuxBwErADAxMxEhESERuAE2AlEFtvtK/wAAAAEAuAAABtQFtgAUAIoAsgAAACuxBw8zM7IBAgArsQIFMzMBsBUvsADWsRQH6bQRBwAfBCuwFBCxCwErsQYH6bAGELEMB+mwDC+xFgErsDYausLc7RQAFSsKsA8uDrAQwLEDC/kFsALAAwCxAxAuLgGzAgMPEC4uLi6wQBqxCxQRErEFDjk5sAwRsA05ALEBABESsAw5MDEzESEBMwEhESERNDYTIwEhASMSFRG4AaYBWgYBbwGn/t4DDAn+h/7k/qAJEwW2+6IEXvpKArQxgAEU+4cEe/6idf1YAAABALgAAAXJBbYADwBdALIAAAArsAkzsgECACuwBzMBsBAvsADWsQ8H6bAPELEGASuxCAfpsAgQtAQHAB8EK7AEL7ERASuxDwARErELDDk5sAYRsQIKOTmwBBKwAzkAsQEAERKxAws5OTAxMxEhATMCNREhESEBIxIVEbgBhwJ7Bw8BF/52/YQJEwW2+7kBHXYCtPpKBFL+2339UAACAHf/7AXnBc0ACwAVAEQAsgkAACuxDwPpsgMCACuxEwPpAbAWL7AA1rEMCemwDBCxEQErsQYJ6bEXASuxEQwRErEDCTk5ALETDxESsQAGOTkwMRMQACEgABEQACEgAAEUFjMgERAhIgZ3AWkBUQFRAWX+mP6w/rD+mAFFurkBc/6PubwC3wFtAYH+fP6U/pX+egGGAWv1+AHtAe75AAAAAgC4AAAEqgW2AAoAEwBCALIAAAArsgICACuxEwbptAkLAAINK7EJBukBsBQvsADWsQoJ6bALMrAKELEPASuxBQnpsRUBKwCxEwsRErAFOTAxMxEhIAQVFAQhIxkBMzI2NTQmKwG4AdMBCgEV/tn+8IVmj453f40FtuXj7Pr9+AMGcWxtaAAAAAIAd/6kBecFzQAPABkAXgCyDQAAK7ETA+myDRMKK7NADQsJK7IDAgArsRcD6QGwGi+wANaxEAnpsBAQsRUBK7EGCemxGwErsRUQERKzAwsMCSQXObAGEbAKOQCxEw0RErAJObAXEbEABjk5MDETEAAhIAAREAIHASEBIyAAARQWMyARECEiBncBaQFRAVEBZbexAWD+c/70F/6w/pgBRbq5AXP+j7m8At8BbQGB/nz+lP7+/qNR/ncBSAGGAWv1+AHtAe75AAAAAgC4AAAFSAW2AA4AFwBbALIAAAArsAozsgICACuxFwbptA0PAAINK7ENBukBsBgvsADWsQ4J6bAPMrAOELETASuxBQnpsRkBK7ETDhESsAw5sAURsQgLOTkAsQ8NERKwCDmwFxGwBTkwMTMRISAEFRQGBwAXIQEjGQEzMjY1NCYrAbgBqgEqAR6OggFKZP6o/qOlZJOMj5ZeBbbZ3YHJOf4TkAIx/c8DLWJpaFgAAAABAF7/7AQXBcsAJwBxALImAAArsQQD6bISAgArsRkD6bMWJhIIKwGwKC+wD9axHAfpsBwQsQcBK7EjB+mwFTKxKQErsRwPERKwDDmwBxG1BAsSGSAmJBc5sCMSsRYhOTkAsQQmERKwADmwFhGzAQ8cIyQXObESGRESsBU5MDE3ER4BMzI2NTQuAScuAjU0JDMyFhcHLgEjIgYVFB4BFx4BFRQEIyJelM1VZm0wXY+GhlABB+hyz3FkdZlKWF4mU5vNmP7j/upEASBCNk5NK0M+RD90mmfC3jYx8TAmUkIpPTlKYsWPxuQAAQApAAAEeQW2AAcAOgCyBgAAK7IBAgArsQAD6bADMgGwCC+wBtaxBQnpsgUGCiuzQAUDCSuyBgUKK7NABgAJK7EJASsAMDETESERIREhESkEUP5z/soEtAEC/v77TAS0AAAAAAEArv/sBV4FtgASADcAshAAACuxBgPpsgECACuwCjMBsBMvsADWsQMJ6bADELEJASuxDAnpsRQBK7EJAxESsBA5ADAxExEhERQWMzI2NREhERQGBCMgAK4BNYidmIkBNZH+7rv+5v7IAggDrvyBqZ6fqgN9/E6i9IIBIQABAAAAAAUzBbYACwA9ALILAAArsgACACuwCDMBsAwvsADWsQEJ6bABELEIASuxCQnpsQ0BK7EIARESsQoLOTkAsQALERKwBTkwMREhAR4BFzY3ASEBIQE5ARMXMQYLQAEVATn+D/6uBbb8mk3NKFzmA2b6SgAAAAABAAAAAAe8BbYAHQEWALIdAAArsBMzsgACACuxCBEzMwGwHi+wANaxAQfpsAEQsREBK7ESB+mxHwErsDYauj4Q8F8AFSsKDrAFELAHwLEbDPmwGcC6wLX2hgAVKwoOsBgQsBbAsQsN+bANwLo+uPNAABUrC7AFELMGBQcTK7rA7/UdABUrC7ALELMMCw0TK7AYELMXGBYTK7o+ofLUABUrC7AbELMaGxkTK7IGBQcgiiCKIwYOERI5shobGRESObIMCw0giiCKIwYOERI5shcYFhESOQBADAcNGBsFBgsMFhcZGi4uLi4uLi4uLi4uLgFADAcNGBsFBgsMFhcZGi4uLi4uLi4uLi4uLrBAGgGxEQERErETHTk5ALEAHRESsAQ5MDERIRMWFz4BNxMhEx4BFz4BNxMhASEDJgInDgEHAyEBMbsxFgYrE9UBJdUOKgsKLBK6ATH+jP6fxgs1BAYwDcX+oAW2/OLdojnvQgMz/M034lFO6UgDHvpKAwApAQEsNu8z/QIAAAEAAAAABVYFtgALACYAsgAAACuwCDOyAgIAK7AFMwGwDC+xDQErALECABESsQQKOTkwMTEJASEJASEJASEJAQHl/joBVgE7ATUBTv41Ae7+nv6s/qwC8gLE/fICDv0r/R8CKf3XAAAAAQAAAAAE/gW2AAgAMACyBwAAK7IAAgArsAMzAbAJL7AH1rEGCemxCgErsQYHERKwAjkAsQAHERKwAjkwMREhCQEhAREhEQFQAS8BMQFO/hv+zAW2/aYCWvyD/ccCLwAAAQAxAAAEcQW2AAkALgCyAAAAK7EHA+myBAIAK7EDA+kBsAovsQsBKwCxBwARErABObEEAxESsAY5MDEzNQEhESEVASERMQK9/VYEGv1EAs/JA+0BAMj8Ev8AAAACAFb/7AQ7BHUAGAAiAIIAshEAACuyFgAAK7EbBOmyDAEAK7EHBOm0AyAWDA0rtAMEABQEKwGwIy+wANaxGQnpsBkQsR4BK7AEMrEPB+mxJAErsRkAERKxCQo5ObAeEbIHDBY5OTmwDxKwEzkAsRsRERKxEhM5ObAgEbAAObADErACObAHEbAJObAMErAKOTAxEzQ2PwE1NCMiByc2MzIWFREjJyMOASMiJiUUMzI2PQEHDgFW+fvCroa1ZcHr4fDVOwhNo4OhuQE5lGp/doWCAU6yqQkGMapRzmXEyP0XmGFLuKiBemVcBARYAAIAoP/sBLQGFAASAB8AYwCyAAAAK7IOAAArsRYF6bIIAQArsRwF6bABLwGwIC+wANaxEwfpsAIysBMQsRkBK7ELCemxIQErsRMAERKyBQYQOTk5sBkRsQgOOTkAsRYAERKwEDmwHBGwCzmwCBKwBTkwMTMRIREUBzM2MzISERACIyInIwcTFBYzMjY1NCYjIgYHoAExDAxr0sbg58fFcBUzSGt0Xm9wYXFoAgYU/pZFmKb+y/7z/uv+0I97AjO0nK2lpaWLoAAAAQBc/+wD3QRzABUAPQCyFAAAK7ENBemyAwEAK7EJBekBsBYvsADWsQsJ6bEXASsAsQ0UERKwETmwCRGyAAYQOTk5sAMSsAU5MDETEAAhMhcHLgEjIhEQMzI2NxEOASMgXAEcAQnCmlpIfD7u7liWS0qXc/32AikBHQEtTOwdJf6u/rgvMv77LyQAAAACAFz/7ARxBhQAEgAfAGIAsgwAACuyDwAAK7AJLwGwIC+wANaxEwnpsBMQsQgBK7EKB+mwChCxGQfpsBkvsAYzsSEBK7EIExEStAMOEBYdJBc5sBkRsQUNOTmwChKwDDkAsQkMERK0AA0OFh0kFzkwMRMQEjMyFzMmNREhESMnIwYjIgIBFBYzMjY3NTQmIyIGXOXJ028KFwEy6jsNaNXF4QE1cmp1bQVvfWZxAi0BEwEzpH1iAWb57JGlATIBC6WliKMhtJytAAIAXP/sBGIEcwAUABsAaQCyEgAAK7ELBOmyAwEAK7EZBOm0FQgSAw0rtBUEABQEKwGwHC+wANaxCAnpsBUysAgQsRYBK7EGB+mxHQErsRYIERKyAwsSOTk5sAYRsQ4POTkAsQsSERKwDzmwCBGwDjmwFRKwADkwMRMQADMyAB0BIR4BMzI2NxUOASMgAAEhLgEjIgZcARn47QEI/S8FkIJltGJQtoP+8v7QATwBrAJyYWFuAicBGQEz/vLulIKSKi7sKCcBKgGYcXt7AAEAKQAAA3UGHwAVAFoAshQAACuyDwEAK7ESBOmwADKyAgEAK7ALL7EGBekBsBYvsBTWsAIysRMH6bAOMrITFAors0ATEQkrshQTCiuzQBQACSuxFwErALELDxESsAk5sAYRsAg5MDETNTc1NDYzMhcHJiMiBh0BIRUhESERKai8z557TlxOQToBCP74/s8DeZNSUr+wL+AdTTxG5fyHA3kAAAAAAwAG/hQEbQRzACkANgBAAN8AsjQAACuxIAXpshIBACu0PwQADAQrsBQysg8BACu0PwQAFAQrsCcvtC0EABQEK7QaOjQPDSu0GgQAFAQrAbBBL7AM1rE3B+mwHjKwACDWEbQqBwAfBCuwNxC0BgcAGAQrsAYvsDcQsT0BK7EXB+mwFxCwJCDWEbQwBwAlBCuwMC+0JAcAJQQrsUIBK7EqBhESsAM5sDcRsAk5sD0StBwPICctJBc5sDARsCE5sBcSsBU5ALE0LRESsSQAOTmwIBGwAzmwGhKxBh45ObA6EbEJHDk5sD8SshUXDDk5OTAxFzQ2Ny4BNTQ2Ny4BNTQ2MzIWFyEVBxYVFAYjLwEGFRQ7ATIWFRQEISImJRQWMzI2NTQmKwEiBhMUFjMyNjU0IyIGfnovRkpGWGfu3S+BEgGGrzD73zctL6i+uMH+uf7O6vcBCHltpLpuc55UcW9TVVZQpqi2ZYgdFFszQFUpJqhyt8gRBJstS120yQMFJCxCnpnE2KOrP0haTj8wTwNNW2pqW8oAAAAAAQCgAAAEqAYUABUARACyAAAAK7ANM7ABLwGwFi+wANaxFQfpsAIysBUQsQ4BK7ENB+mxFwErsRUAERKwBjmwDhGxBwk5OQCxAQARErAROTAxMxEhERQPATM2MzIWFREhETQjIgYVEaABMQcHEGbexcz+z7SAcgYU/sMliVqk1Mb9JwKN8q7D/fIAAAACAJMAAAHfBhQACAAMADcAsgkAACuyCgEAK7AHL7QCAwAjBCsBsA0vsAnWsAAysQwH6bAEMrEOASuxDAkRErEHAjk5ADAxEzQzMhUUBiMiExEhEZOmplNTpg0BMQV/lZVHT/sXBF77ogAAAAAC/33+FAHfBhQADQAWAEcAsgYBACuwCy+xAgXpsBUvtBADACMEKwGwFy+wBdawDjKxCAfpsBIysRgBK7EIBRESsRAVOTkAsQILERKwDTmwBhGwADkwMQcWMzI2NREhERQGIyInATQzMhUUBiMig0ZJTUcBMc69dVQBFqamU1Om4xNWVASq+ymywRkHUpWVR08AAAAAAQCgAAAE9gYUAA4AOgCyAAAAK7AKM7IHAQArsAEvAbAPL7AA1rEOB+mwAjKxEAErsQ4AERKxBAU5OQCxBwARErEEDDk5MDEzESERBzM3ASEJASEBBxGgATEQBIUBOQFY/kQB1/6g/r6DBhT9Sv6qAVT+G/2HAcVp/qQAAAEAoAAAAdEGFAADAB8AsgAAACuwAS8BsAQvsADWsQMH6bEDB+mxBQErADAxMxEhEaABMQYU+ewAAQCgAAAHQgRzACMAcACyAAAAK7ERGjMzsgEBACuyBwEAK7ANM7EfBemwFjIBsCQvsADWsSMH6bAjELEbASuxGgfpsBoQsRIBK7ERB+mxJQErsSMAERKwBDmwGxGwBzmwGhKxCgk5ObASEbANOQCxAR8RErMDBAkKJBc5MDEzETMXMz4BMzIXMz4BMzIWFREhETQmIyIGFREhETQmIyIGFRGg6SkRLapu+1kbLa9uvsP+zlFXcG/+z1FXdWoEXo9NV6ROVsPX/ScCjXl5oK79zwKNeXmsxf3yAAAAAAEAoAAABKgEcwAUAEwAsgAAACuwCzOyAQEAK7IHAQArsRAF6QGwFS+wANaxFAfpsBQQsQwBK7ELB+mxFgErsRQAERKwBDmwDBGwBzkAsQEQERKxAwQ5OTAxMxEzFzM+ATMyFhURIRE0JiMiBhURoOkpETOzcsPK/s9WXoByBF6PUVPTx/0nAo15eavG/fIAAAIAXP/sBJgEcwANABkARACyCgAAK7ERBemyAwEAK7EXBekBsBovsADWsQ4J6bAOELEUASuxBwnpsRsBK7EUDhESsQMKOTkAsRcRERKxBwA5OTAxExAAITIWEhUQACEiJgIlFBYzMjY1NCYjIgZcAR4BA6H2hP7g/v+h9oQBN217emtse3psAjEBEgEwjP76sP7v/syNAQiwpqqpp6ampQACAKD+FAS0BHMAEwAfAGcAsg0AACuxFwXpsgEBACuyBgEAK7EcBemwAC8BsCAvsADWsRMH6bAUMrATELEZASuxCQnpsSEBK7ETABESsgQPEDk5ObAZEbEGDTk5ALEXDRESsQ8QOTmwHBGwCTmwARKxAwQ5OTAxExEzFzM2MzISERQCBiMiJyMWFRkBFBYzMhE0JiMiBgeg+CsOa9LG4GnCg8VwEBBrdM1lbHFoAv4UBkqRpv7O/vCz/viKj4wW/jsEH7ScAVKlpYugAAACAFz+FARxBHMAFAAgAFoAsggBACuyAgEAK7ALLwGwIS+wANaxFQnpsBUQsRsBK7EJB+mwCRCxCwfpsAsvsSIBK7ELFREStAMPEhgfJBc5sBsRsgcGDjk5OQCxCAsRErMABhgfJBc5MDETEBIzMhYXMzchESERNDcjDgEjIgIBFBYzMjY3NTQmIyJc5cdqnjwIGwEC/s4NDTGiasbgATdrcXRsBW971wItARIBNFBUj/m2AdU9a1FUATEBDKimhaYltJwAAQCgAAADdwRzABAAOACyAAAAK7IBAQArsgcBACuxDAPpAbARL7AA1rEQB+mxEgErsRAAERKwBDkAsQEMERKxAwQ5OTAxMxEzFzM+ATMyFwMmIyIGFRGg5y0PNLFoPikXJTWSowRevF5zCf7iCpaH/ccAAAABAFz/7AOsBHMAJQBrALIVAAArsRwE6bIDAQArsQkE6QGwJi+wANawGDKxCwfpsAsQsR4BK7ESB+mxJwErsQsAERKwIzmwHhG1AwkOFRwiJBc5sBISsgYPBTk5OQCxHBURErAYObAJEbMABhIZJBc5sAMSsAU5MDETNDYzMhcHLgEjIhUUFhceAhUUBiMiJic1HgEzMjU0LgEnLgJc59TKv1xUkkyHV5ODejrv7nqsS1XVUaYsbFqBeTcDO5WjWNwkLkkpPDs1XHhTrLQhIPwoNmAkLTkmNlx3AAAAAQAv/+wDNwVMABUAcACyEQAAK7EMBemyBQEAK7EIBOmwADKyBQgKK7NABQQJK7ICAQArAbAWL7AU1rEJB+mwBDKyCRQKK7NACQcJK7AOMrIUCQors0AUAAkrsRcBK7EJFBESsAI5ALEMERESsA85sAgRsA45sAUSsAE5MDETNT8BMxUhFSERFBYzMjcVBiMiJjURL6hYwwE5/sdJPFBwcqa3pwN5gWbs7uX95UE+I+MzubkCGwAAAAEAmv/sBKIEXgAUAEwAsg0AACuyEgAAK7EGBemyAQEAK7AKMwGwFS+wANaxAwfpsAMQsQkBK7ELB+mxFgErsQkDERKwEjmwCxGwDzkAsQYNERKxDg85OTAxExEhERQWMzI2NREhESMnIw4BIyImmgExVl6AcgEx6ikQMbRzxcgBhQLZ/XN5eavGAg77oo9OVdMAAAABAAAAAASNBF4ACwAhALILAAArsgABACuwCDMBsAwvsQ0BKwCxAAsRErAEOTAxESETFhczNjcTIQEhAT/YJAkGBSjXAT/+Vv7HBF79g3lsYIUCffuiAAAAAQAUAAAGxQReAB0A5gCyHQAAK7AXM7IAAQArswEKFRYkFzMBsB4vsADWsQEH6bABELEVASuxFgfpsR8BK7A2GrrCEu/cABUrCrAAELAdwA6wARCwAsC6wdTwzgAVKwoFsAouDrAOwLEaBPmwGcC6PcfvRwAVKwoOsBUQsBTABbAWELAXwLrBlvHZABUrC7AKELMLCg4TK7MMCg4TK7MNCg4TK7ILCg4giiCKIwYOERI5sAw5sA05ALcCCxQZGgwNDi4uLi4uLi4uAUALAgoLFBcZGh0MDQ4uLi4uLi4uLi4uLrBAGgEAsQAdERKxBBA5OTAxEyETFhczNj8BEyETHgMXMz4BNxMhASELASMDIRQBMIEfIAYEHxCKAVCDBBEQDQEGCS4KhgEr/r7+tFZ0B8z+uARe/hGF6kylVQIY/egWVmFdHEj7LAHv+6IBhwHu/IsAAAEACgAABJYEXgALACYAsgAAACuwCDOyAgEAK7AFMwGwDC+xDQErALECABESsQQKOTkwMTMJASEbASEJASELAQoBe/6YAVrZ2wFa/pQBff6l6+wCOwIj/pwBZP3d/cUBf/6BAAABAAD+FASNBF4AFgArALIAAQArsAgzsA0vsRIF6QGwFy+xGAErALESDRESsA85sAARsQQQOTkwMREhExYXMzY3EyEBDgEjIic1FjMyNj8BAU7TGwoGCyDPAUf+J0HxoU9MN0FReSISBF79i1JwZ1sCdfsTr64R8g1jZDcAAQA3AAADqgReAAkALgCyAAAAK7EHBOmyBAEAK7EDBOkBsAovsQsBKwCxBwARErABObEEAxESsAY5MDEzNQEhNSEVASEVNwIG/hkDQv4IAgq0AsHpxv1R6QAAAAABAAAAAARgBGAAAwAnALIAAAArsgEBACsBsAQvsADWtAMJAAcEK7QDCQAHBCuxBQErADAxMREhEQRgBGD7oAAAAQAAAAEZmpevkAxfDzz1AB8IAAAAAADSQ9G+AAAAANJD0b7/aP4UB7wGHwABAAgAAgAAAAAAAAABAAAIjf2AAAAH2/9o/6QHvAABAAAAAAAAAAAAAAAAAAAAOQLsAEQAAAAABBQAAAIUAAAFhQAABWAAuAUZAHcF7AC4BHsAuARkALgFywB3Bh8AuAKmALgCpv9oBVAAuASFALgHiwC4BoEAuAZeAHcFBgC4Bl4AdwVIALgEaABeBKIAKQYMAK4FMwAAB7wAAAVWAAAE/gAABKIAMQTVAFYFEACgBB0AXAUQAFwEugBcAxkAKQSFAAYFQgCgAnEAkwJx/30E9gCgAnEAoAfbAKAFQgCgBPQAXAUQAKAFEABcA6IAoAP6AFwDeQAvBUIAmgSNAAAG2QAUBKAACgSNAAAD5wA3BGAAAAAAACwALAAsACwAcgDYASQBYgGeAdQCQAJ4ApYCyAL+AyQDkgPgBDAEdATYBTAFpAXWBhQGUAcUB0gHeAemCBwIgAjGCSoJkAniCq4K9AsqC3QLsgvODDwMhAzUDToNnA3WDkQOoA7qDxYPwA/yEDAQXhB+AAEAAAA5AEEAAwAAAAAAAgABAAIAFgAAAQABFgAAAAAAAAASAN4AAwABBAkAAAByAAAAAwABBAkAAQASAHIAAwABBAkAAgAIAIQAAwABBAkAAwBGAIwAAwABBAkABAAcANIAAwABBAkABQAYAO4AAwABBAkABgAaAQYAAwABBAkABwCkASAAAwABBAkACAAoAcQAAwABBAkACwA4AewAAwABBAkADABcAiQAAwABBAkADQBcAoAAAwABBAkADgBUAtwAAwABBAkAyAAWAzAAAwABBAkAyQAwA0YAAwABBAkAygAOA3YAAwABBAkAywAOA4QAAwABBAnZAwAaA5IARABpAGcAaQB0AGkAegBlAGQAIABkAGEAdABhACAAYwBvAHAAeQByAGkAZwBoAHQAIACpACAAMgAwADEAMAAtADIAMAAxADEALAAgAEcAbwBvAGcAbABlACAAQwBvAHIAcABvAHIAYQB0AGkAbwBuAC4ATwBwAGUAbgAgAFMAYQBuAHMAQgBvAGwAZABBAHMAYwBlAG4AZABlAHIAIAAtACAATwBwAGUAbgAgAFMAYQBuAHMAIABCAG8AbABkACAAQgB1AGkAbABkACAAMQAwADAATwBwAGUAbgAgAFMAYQBuAHMAIABCAG8AbABkAFYAZQByAHMAaQBvAG4AIAAxAC4AMQAwAE8AcABlAG4AUwBhAG4AcwAtAEIAbwBsAGQATwBwAGUAbgAgAFMAYQBuAHMAIABpAHMAIABhACAAdAByAGEAZABlAG0AYQByAGsAIABvAGYAIABHAG8AbwBnAGwAZQAgAGEAbgBkACAAbQBhAHkAIABiAGUAIAByAGUAZwBpAHMAdABlAHIAZQBkACAAaQBuACAAYwBlAHIAdABhAGkAbgAgAGoAdQByAGkAcwBkAGkAYwB0AGkAbwBuAHMALgBBAHMAYwBlAG4AZABlAHIAIABDAG8AcgBwAG8AcgBhAHQAaQBvAG4AaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGEAcwBjAGUAbgBkAGUAcgBjAG8AcgBwAC4AYwBvAG0ALwBoAHQAdABwADoALwAvAHcAdwB3AC4AYQBzAGMAZQBuAGQAZQByAGMAbwByAHAALgBjAG8AbQAvAHQAeQBwAGUAZABlAHMAaQBnAG4AZQByAHMALgBoAHQAbQBsAEwAaQBjAGUAbgBzAGUAZAAgAHUAbgBkAGUAcgAgAHQAaABlACAAQQBwAGEAYwBoAGUAIABMAGkAYwBlAG4AcwBlACwAIABWAGUAcgBzAGkAbwBuACAAMgAuADAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGEAcABhAGMAaABlAC4AbwByAGcALwBsAGkAYwBlAG4AcwBlAHMALwBMAEkAQwBFAE4AUwBFAC0AMgAuADAAVwBlAGIAZgBvAG4AdAAgADEALgAwAFcAZQBkACAATwBjAHQAIAAxADQAIAAwADUAOgAzADIAOgA0ADYAIAAyADAAMQA1AGQAZQBmAGEAdQBsAHQAcABlAHIAcwBlAHUAcwBGAG8AbgB0ACAAUwBxAHUAaQByAHIAZQBsAAAAAgAAAAAAAP9mAGYAAAAAAAAAAAAAAAAAAAAAAAAAAAA5AAABAgEDAAMAJAAlACYAJwAoACkAKgArACwALQAuAC8AMAAxADIAMwA0ADUANgA3ADgAOQA6ADsAPAA9AEQARQBGAEcASABJAEoASwBMAE0ATgBPAFAAUQBSAFMAVABVAFYAVwBYAFkAWgBbAFwAXQEEBmdseXBoMQd1bmkwMDBEB3VuaTI1RkMAuAH/hbABjQBLsAhQWLEBAY5ZsUYGK1ghsBBZS7AUUlghsIBZHbAGK1xYALADIEWwAytEsAYgRbID+gIrsAMrRLAFIEWyBmwCK7ADK0SwBCBFsgUkAiuwAytEAbAHIEWwAytEsAggRboAB3//AAIrsQNGditEsAkgRbII2gIrsQNGditEWbAUKwABVh4hPgAA) format('truetype');font-weight:400;font-style:normal}@font-face{font-family:'open_sansitalic';src:url(data:application/x-font-opentype;charset=utf-8;base64,AAEAAAATAQAABAAwRkZUTWfkvbYAAAE8AAAAHEdERUYAZgAEAAABWAAAACBHUE9TECH6YwAAAXgAAALSR1NVQpM8gksAAARMAAAAUE9TLzKg7bwzAAAEnAAAAGBjbWFwpkuXDgAABPwAAAFiY3Z0IA9XE2wAAAZgAAAATGZwZ21TtC+nAAAGrAAAAmVnYXNwAAAAEAAACRQAAAAIZ2x5ZhZeU88AAAkcAAAnVGhlYWQJ/wcYAAAwcAAAADZoaGVhDrwESAAAMKgAAAAkaG10eOvmCl0AADDMAAAA5GxvY2EIDRLaAAAxsAAAAHRtYXhwAVQBPgAAMiQAAAAgbmFtZVUun4gAADJEAAAEmHBvc3TOVv/WAAA23AAAAKtwcmVw6lkVVgAAN4gAAAFSd2ViZiGoVh4AADjcAAAABgAAAAEAAAAAzD2izwAAAADJY0jAAAAAANJD0iYAAQAAAA4AAAAYAAAAAAACAAEAAQA4AAEABAAAAAIAAAABAAAACgBUAGIABERGTFQAGmN5cmwAJmdyZWsAMmxhdG4APgAEAAAAAP//AAEAAAAEAAAAAP//AAEAAAAEAAAAAP//AAEAAAAEAAAAAP//AAEAAAABa2VybgAIAAAAAQAAAAEABAACAAAAAQAIAAECLgAEAAAAGQA8AGIAgABiAJIAmACAAJ4AYgDEAGIA0gE0AToBOgCAAYQB0gHkAeQB+gHkAeQCEAH6AAkABv/XAAr/1wANAQoAEv/XABT/1wAX/3EAGf+uABr/rgAc/4UABwAE/9cAF//DABn/7AAa/+wAG//XABz/7AAd/+wABAAG/9cACv/XABL/1wAU/9cAAQANAHsAAQAE/9cACQAG/9cACv/XABL/1wAU/9cAF//XABj/7AAZ/9cAGv/XABz/wwADAAT/mgAb/9cAHf/sABgABP9xAAb/1wAK/9cAEv/XABT/1wAXACkAHv9cACD/cQAh/3EAIv9xACT/cQAq/5oAK/+aACz/cQAt/5oALv9xAC//mgAw/4UAMv+aADP/1wA0/9cANf/XADb/1wA3/64AAQAE/+wAEgAE/64ABv/sAAr/7AAS/+wAFP/sAB7/1wAg/9cAIf/XACL/1wAk/+wAKv/sACv/7AAs/9cALf/sAC7/1wAv/+wAMP/sADL/7AATAAT/hQAG/9cACv/XABL/1wAU/9cAHv+aACD/mgAh/5oAIv+aACT/1wAq/8MAK//DACz/mgAt/8MALv+aAC//wwAw/64AMv/DADf/1wAEAAb/7AAK/+wAEv/sABT/7AAFADP/1wA0/9cANf/XADb/1wA3/+wABQAg/9cAIf/XACL/1wAs/9cALv/XAAcAHv/XACD/1wAh/9cAIv/XACT/7AAs/9cALv/XAAEAGQAEAAUABgAHAAgACQAOAA8AEgATABQAFwAYABkAGgAbABwAHQAfACIAKAAsAC0ALwA1AAAAAQAAAAoATABOAARERkxUABpjeXJsACRncmVrAC5sYXRuADgABAAAAAD//wAAAAQAAAAA//8AAAAEAAAAAP//AAAABAAAAAD//wAAAAAAAAADBDwBkAAFAAQFmgUzAAABHwWaBTMAAAPRAGYCAAAAAgsGBgMFBAICBOAAAu9AACBbAAAAKAAAAAAxQVNDAAEADSX8Bmb+ZgAACGICTSAAAZ8AAAAABEgFtgAAACAAAgAAAAMAAAADAAAAHAABAAAAAABcAAMAAQAAABwABABAAAAADAAIAAIABAANACAAWgB6Jfz//wAAAA0AIABBAGEl/P////X/4//D/73aPAABAAAAAAAAAAAAAAAAAAABBgAAAQAAAAAAAAABAgAAAAIAAAAAAAAAAAAAAAAAAAABAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHQAAAAAAAB4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAESAW2AJgAQwBpAHUAfQCCAIsAjwCTAJwA3QCqAIMAiwCaAKIApgCqALAAtgDLAH8AqACfAJEApAB4AJYAjQCsAK4AewBwAIYFEbAALLAAE0uwTFBYsEp2WbAAIz8YsAYrWD1ZS7BMUFh9WSDUsAETLhgtsAEsINqwDCstsAIsS1JYRSNZIS2wAyxpGCCwQFBYIbBAWS2wBCywBitYISMheljdG81ZG0tSWFj9G+1ZGyMhsAUrWLBGdllY3RvNWVlZGC2wBSwNXFotsAYssSIBiFBYsCCIXFwbsABZLbAHLLEkAYhQWLBAiFxcG7AAWS2wCCwSESA5Ly2wCSwgfbAGK1jEG81ZILADJUkjILAEJkqwAFBYimWKYSCwAFBYOBshIVkbiophILAAUlg4GyEhWVkYLbAKLLAGK1ghEBsQIVktsAssINKwDCstsAwsIC+wBytcWCAgRyNGYWogWCBkYjgbISFZGyFZLbANLBIRICA5LyCKIEeKRmEjiiCKI0qwAFBYI7AAUliwQDgbIVkbI7AAUFiwQGU4GyFZWS2wDiywBitYPdYYISEbINaKS1JYIIojSSCwAFVYOBshIVkbISFZWS2wDywjINYgL7AHK1xYIyBYS1MbIbABWViKsAQmSSOKIyCKSYojYTgbISEhIVkbISEhISFZLbAQLCDasBIrLbARLCDSsBIrLbASLCAvsAcrXFggIEcjRmFqiiBHI0YjYWpgIFggZGI4GyEhWRshIVktsBMsIIogiocgsAMlSmQjigewIFBYPBvAWS2wFCyzAEABQEJCAUu4EABjAEu4EABjIIogilVYIIogilJYI2IgsAAjQhtiILABI0JZILBAUliyACAAQ2NCsgEgAUNjQrAgY7AZZRwhWRshIVktsBUssAFDYyOwAENjIy0AAAAAAQAB//8ADwACAEQAAAJkBVUAAwAHAC6xAQAvPLIHBATtMrEGBdw8sgMCBO0yALEDAC88sgUEBO0ysgcGJfw8sgECBO0yMxEhESUhESFEAiD+JAGY/mgFVfqrRATNAAAAAv+LAAAEEAW2AAcADgB5ALIAAAArsQMEMzOyAQIAK7ACM7QGCAABDSuwCTOxBgzpsAUyAbAPL7AE1rEDDumxEAErsDYausB6+DcAFSsKDrAEELAKwAWwAxCwAsCwChCzBQoEEyuzCQoEEysDALAKLgGzAgUJCi4uLi6wQBoAsQEIERKwDDkwMSMBMxMjAyEDASEDJicOAXUDH664qjn+EPUBSQGKIxgFJVcFtvpKAdH+LwJtASuzq1iuAAADAFYAAASyBbYADgAXACAAkACyAAAAK7EPCumyAQIAK7EgC+m0GBcAAQ0rsRgK6QGwIS+wE9axCxbpsxwLEwgrsQQV6bEiASuwNhq6PpzyuQAVKwqwAC6wIC6wABCxDxP5sCAQsQET+bAPELMXDyATK7MYDyATKwO1AAEPFxggLi4uLi4usEAaALEXDxESsAs5sBgRsQgHOTmwIBKwBDkwMTMBISARFAYHFR4BFRQEIyUhMjY1NCYrATczMjY1NCYrAVYBNQF3AbCunnN7/tD//voBCrXClYzsH/icuoWP0wW2/rCNwh0KIJ1u1PGRoZN0e5CSfmhnAAEAlv/sBQoFywAYAD0AshYAACuxEAPpsgQCACuxCQPpAbAZL7AA1rENFumxGgErALEQFhESsBM5sAkRsgAHEjk5ObAEErAGOTAxExASJDMyFwcmIyIEAhUUFjMyNxUOASMiAJbTAWThxZdFio2u/u2hw6uLt1acbvL+7AIZAQUBwexQjUXC/ondu985lR8cASsAAAACAFYAAAUUBbYACQATAF0AsgkAACuwADOxCgvpsgECACuxEwvpAbAUL7AP1rEFFumxFQErsDYauj6V8psAFSsKsAAusBMusAAQsQoT+bATELEBE/kDswABChMuLi4usEAaALETChESsAU5MDEzASEgABEQAgQhJzMyJBI1NCYrAVYBNQFWARQBH9L+ev76l6LKATKjzseyBbb+1f7i/vv+cNiTtwFO19fdAAAAAQBWAAAEagW2AAsAaQCyAAAAK7EJA+myAQIAK7EEA+m0BQgAAQ0rsQUD6QGwDC+xDQErsDYauj6m8ukAFSsKsAAusAQusAAQsQkT+bAEELEBE/mwCRCzBQkEEyuzCAkEEysDtQABBAUICS4uLi4uLrBAGgAwMTMBIQchAyEHIQMhB1YBNQLfIP3KYgIPHf3vcgI1IQW2mf4rmP3omAAAAAEAVgAABGoFtgAJAGAAsgAAACuwCTOyAQIAK7EEA+m0CAUAAQ0rsQgD6QGwCi+wANaxCQ7psQsBK7A2Gro+ofLVABUrCrAAELABwLAJELAEwLMFCQQTK7MICQQTKwOzAQQFCC4uLi6wQBoAMDEzASEHIQMhByEDVgE1At8e/chuAhAg/e+DBbaZ/euZ/ZEAAAEAlv/sBU4FywAdAH4AshsAACuxEgPpsgQCACuxCwPptBYXGwQNK7AYM7EWA+mwFTIBsB4vsADWsQ8W6bEfASuwNhq6Po7yegAVKwqwFS4OsBTABbEYE/kOsBnAALEUGS4uAbMUFRgZLi4uLrBAGgEAsRYSERKxDwA5ObELFxESsAg5sAQRsAc5MDETEBIkMzIWFwcuASMiBAIVFBYzMjcTITchAwYjIACWywFo23XNaEJNsWqp/uuazbiaamD+3yEBy5rYy/74/tsCEAENAbn1KCyYIjLL/pThvtonAbyY/TlLASEAAAABAFYAAAVzBbYACwCgALIAAAArsgcICzMzM7IBAgArsgIFBjMzM7QDCgABDSuwCTOxAwPpsAQyAbAML7AA1rELDumwCxCxAQErsQIO6bACELEIASuxBxPpsAcQsQUBK7EGDumxDQErsDYauj6g8s0AFSsKuj6W8p4AFSsKsAsQswMLAhMrsAgQswQIBRMrswkIBRMrsAsQswoLAhMrA7MDBAkKLi4uLrBAGgAwMTMBMwMhEzMBIxMhA1YBNaqDApSFqP7Kp4/9bJEFtv2SAm76SgKw/VAAAAABAFYAAAI1BbYAAwA/ALIAAAArsAMzsgECACuwAjMBsAQvsADWsQMO6bADELEBASuxAg7psQUBK7A2Gro+mfKvABUrCgMBsEAaADAxMwEzAVYBN6j+yQW2+koAAAH+wf5/AjUFtgAMAFkAsgcCACuwCDOwCy+xAwPpAbANL7AH1rEIDumxDgErsDYauj6d8r4AFSsKDrAHELAGwLAIELAJwACxBgkuLgGxBgkuLrBAGgEAsQMLERKwADmwBxGwATkwMQE3FjMyNjcBMwECISL+wQZFTGSDGQEzqv7LT/6paf6YkxR9eAWq+kT+hQAAAAABAFYAAAUrBbYADQCHALIAAAArsQcNMzOyAQIAK7ECBDMzAbAOL7AA1rENDumwDRCxAQErsQIO6bEPASuwNhq6Pp7yxAAVKwq6Pp7yxAAVKwuwDRCzAw0CEyuzDA0CEyuyDA0CIIogiiMGDhESObADOQCxAwwuLgGxAwwuLrBAGgGxAgERErALOQCxAQARErALOTAxMwEzAwEzCQEjJgInBwNWATWqlwK80f2BAV66SJVIrn0Ftv06Asb9g/zHtQFlt4P9sgAAAAEAVgAAA1YFtgAFAEUAsgAAACuxAwPpsgECACuwAjMBsAYvsAHWsQIO6bEHASuwNhq6Pp/yyQAVKwqwARCwAMCwAhCwA8ADsQADLi6wQBoAMDEzATMBIQdWATWq/uwCNSEFtvrkmgAAAQBUAAAGuAW2ABQA9gCyAAAAK7MHCA4UJBczsgECACuxAgYzMwGwFS+wANaxFBLpsBQQsQgBK7EHFemxFgErsDYauj6e8sQAFSsKsAAQsAHADrAUELARwLrAfPgkABUrCgWwDi4OsA/AsQMJ+QWwAsC6PqvzAwAVKwoOsAgQsArABbAHELAGwLo+mfKsABUrC7AIELMJCAoTK7AUELMSFBETK7MTFBETK7ITFBEgiiCKIwYOERI5sBI5sgkIChESOQC2Aw8TCQoREi4uLi4uLi4BQAsBAgMGDg8TCQoREi4uLi4uLi4uLi4usEAaAbEIFBESsQQNOTkAsQEAERKwCzkwMTMBMxMzASEBIxoBNyMBIwMjDgEHA1QBNfSVCQKTAQr+0a5+hhsG/TODpggHKxC+Bbb7TAS0+koCTgJ3TfruBRBI+0r8fQAAAAABAFQAAAWoBbYADwB/ALIAAAArsQkPMzOyAQIAK7EHCDMzAbAQL7AA1rEPEumwDxCxBwErsQgS6bERASuwNhq6Pp7yxAAVKwqwABCwAcAOsA8QsA7Auj6s8wcAFSsKsAcQsAbABbAIELAJwAMAsQYOLi4BswEGCQ4uLi4usEAaALEBABESsQMLOTkwMTMBMwEzNjcTMwEjASMGBwNUATW0AcsGHiqupP7Ltf40BiAqrAW2+zzgtQMv+koEx93F/NsAAAAAAgCW/+wFgwXNAA0AGwBEALILAAArsRED6bIEAgArsRgD6QGwHC+wANaxDhbpsA4QsRUBK7EHFumxHQErsRUOERKxBAs5OQCxGBERErEABzk5MDETEBIkMzIAERACBCMgABMUFjMyNhI1NCYjIgYClsABT9L0ARiw/rjX/wD+4rbEqJjxjLynnfiJAiUBCAG07P7M/vL+8/5X6QErARLH38MBbN3H38r+mAAAAAIAVgAABIcFtgAKABMAcwCyAAAAK7AKM7IBAgArsRML6bQJCwABDSuxCQvpAbAUL7AA1rEKDumwChCxDwErsQUV6bEVASuwNhq6Pp7yxAAVKwqwABCwAcCwChCwE8CzCQoTEyuzCwoTEysDswEJCxMuLi4usEAaALETCxESsAU5MDEzASEyFhUUACEjAxMzMjY1NCYrAVYBNQFK1tz+uP7Dh3uahdjgi5CjBba9vPj++v3BAtG2sH1vAAAAAgCW/qQFgwXNABEAHwBNALIPAAArsRUD6bIEAgArsRwD6QGwIC+wANaxEhbpsBIQsRkBK7EHFumxIQErsRkSERKzBAsOCiQXOQCxFQ8RErAKObAcEbEABzk5MDETEBIkMzIAERAABwEjAwcjIAATFBYzMjYSNTQmIyIGApbAAU/S9AEY/ursARLb4xEQ/wD+4rbEqJ7yhbynnfiJAiUBCAG07P7M/vL+s/4aTv6aAUoCASsBEsffyAFp28ffyv6YAAAAAAIAVgAABIkFtgALABUAiwCyAAAAK7EHCzMzsgECACuxFAvptAoMAAENK7EKC+kBsBYvsADWsQsO6bALELEQASuxBBXpsRcBK7A2Gro+nvLEABUrCrAAELABwLALELAUwLMKCxQTK7MMCxQTKwOzAQoMFC4uLi6wQBqxEAsRErEGCDk5sAQRsAc5ALEMChESsAY5sBQRsAQ5MDEzASEgERAFEyMDIwMTMzI2NTQmKwECVgE1AUABvv6Q77rR/IGgqMHQh5imZgW2/pL+pGX9eQJg/aAC8qqfeW3+EgABACf/7AQjBcsAJgBmALIkAAArsQML6bIPAgArsRYD6QGwJy+wDNaxGRbpsBkQsQYBK7EhFumxKAErsRkMERKyCgMkOTk5sAYRswkPFh0kFzmwIRKwHjkAsQMkERKwADmwFhGzAQwTISQXObAPErASOTAxNzUWMzI2NTQmJy4BNTQkMzIWFwcuASMiBhUUHgEXHgIVFAQjIiYnorKivmmPl3UBCNdjq19CQqRFhqMiSmmTZzX+5/9qoSuqVJeETndRVap0u+smLpYmLIt3Nk1EPVhkeVDT6R0AAAAAAQC6AAAEtAW2AAcASgCyBgAAK7AFM7IBAgArsQAD6bEEBzIyAbAIL7AG1rEFDumxCQErsDYauj6Z8q4AFSsKsAYQsAfAsAUQsATAA7EEBy4usEAaADAxEzchByEBIwG6IQPZHv5o/umsARUFH5eX+uEFHwABAKT/7AV/BbYAFQB3ALITAAArsQoD6bIDAgArsQ4PMzMBsBYvsADWsQcO6bAHELEDASuxBA7psAQQsQ4BK7EPDumxFwErsDYauj6J8mEAFSsKDrAOELANwLAPELAQwACxDRAuLgGxDRAuLrBAGgGxDgQRErEKEzk5ALEDChESsAA5MDETNDcTMwMGFRQWMzI2NxMzAwIEIyImpBi9qr8WkpGsvyzNqs03/uP25t4Bf1F4A278hWpSdYevygO6/Dr++f3QAAAAAAEAvAAABR8FtgALAFEAsgsAACuyAAIAK7EBCDMzAbAML7AA1rEBDumxDQErsDYausBY+VwAFSsKsAAQsAvADrABELACwACwAi4BsQILLi6wQBoBALEACxESsAQ5MDETMxMWFTM2NwEzASO8qmEUBD1lAd+//PO0Bbb8XsSLkMIDn/pKAAEA3wAAB4EFtgAdAGcAsh0AACuwFDOyAAIAK7EJEjMzAbAeL7AA1rEBDumwARCwAyDWEbEdEOmwHS+xAxDpsAEQsRgBK7EKD+mxHwErsQMBERKxBQY5ObAYEbEJHDk5sAoSsBU5ALEAHRESsgUOGDk5OTAxEzMTFxQHMzY3ATMTFhUHMzY3ATMBIwMmNSMOAQEj36ofAgoGWUMBlbIrCQEJSzgBg7b9aKoxCAYZSP4srgW2/HtYYqDzjANg/KSZl1PgggN9+koDxYiSSKX8DgAB/5gAAATRBbYACwAmALIAAAArsAgzsgICACuwBTMBsAwvsQ0BKwCxAgARErEECjk5MDEjCQEzEwEzCQEjAwFoAlT++azLAbu6/dUBFrTV/h8DCAKu/c0CM/1K/QACgf1/AAAAAQC8AAAEwwW2AAgAfQCyBwAAK7AGM7IAAgArsQEDMzMBsAkvsAfWsQYO6bMBBgcIK7EADumwAC+xAQ7psQoBK7A2Gro+pvLqABUrCg6wBxCwCMCwBhCwBcC6wcPxFgAVKwqxBwgIsAAQsAjADrABELACwACyAgUILi4uAbICBQguLi6wQBoBADAxEzMTATMBAyMTvKqzAenB/Y1xrHcFtv0VAuv8Z/3jAiUAAAH/8AAABJMFtgAJAC4AsgAAACuxBwPpsgQCACuxAwzpAbAKL7ELASsAsQcAERKwATmxBAMRErAGOTAxIzcBITchBwEhBxAcA5z9cSADWhr8ZAK5IYkEkpuL+2+aAAAAAAIAYv/sBGAEXAASACAAXwCyDAAAK7IQAAArsRYJ6bIJAQArsgQBACuxHQnpAbAhL7AA1rETDumwExCxDAErsQsP6bEiASuxDBMRErMEEBYdJBc5sAsRsg0OGjk5OQCxHRYRErQACAcODSQXOTAxEzQSNjMyFhczNzMDIzcjBiMiJjcUFjMyNhI1NCYjIgYCYo76lVyQKAtDf+mFGgizxouerF5VYcB4cFtos2YBXtABZMpjXaz7uNHlxqhycbkBKZVneqz+2gAAAgA7/+wEOQYUABUAIgBbALIAAAArshAAACuxGQnpsgkBACuxHwnpsAEvAbAjL7AB1rECDumwAhCxHQErsQwO6bEkASuxAgERErMFBhAZJBc5sB0RsQkfOTkAsR8ZERK0BgwTFAUkFzkwMTMBMwYCBzM+ATMyFhUUAgYjIiYnIwcTFBYzMjYSNTQjIgYCOwFKqDM3MAldtWCNnon1mmGTJQpGh29pY6tosmDHdQYU8v7/rHZvxq3R/p3HZliqAVpudaIBK6jjvv7gAAAAAQBi/+wDqgRcABgAPQCyFgAAK7EQCemyBAEAK7EJCekBsBkvsADWsQ0O6bEaASsAsRAWERKwFDmwCRGyAAcTOTk5sAQSsAY5MDETNBIkMzIXByYjIgYCFRQWMzI2NxUGIyImYpQBBaOJgy94Y3C5aYV1SIA+fJjC1gGFyAFSvTONM5n+76CAjigbjz/WAAAAAgBi/+wEwwYUABQAIQBuALINAAArshIAACuxFwnpsgQBACuxHgnpsAovAbAiL7AA1rEVDumwFRCxDQErsQwQ6bAMELEKASuxCxPpsSMBK7ENFRESswQSFx4kFzmwDBGyDg8bOTk5sAoSsAY5ALEeFxEStAAHBg8OJBc5MDETNBI2MzIXMzY3EzMBIzcjDgEjIiY3FDMyNhI1NCYjIgYCYpD1mMJXChEcTqb+tosWCGWwXoucrLNeyHVsZ2WtaQFe1gFkwr6bdwFm+ezRfWjEquO7ASOXb3Sl/tUAAAIAYv/sA7QEXAAYACIAaACyFgAAK7EPCemyBAEAK7EgCum0GQoWBA0rsRkJ6QGwIy+wANaxDA7psAwQsR0BK7EHE+mxJAErsR0MERKzBA8WGSQXObAHEbESEzk5ALEPFhESsBM5sAoRsQASOTmxIBkRErAHOTAxEzQSNjMyFhUUBCEjBxQWMzI2NxUOASMiJhMzMjY1NCYjIgZilfaUmZr+tP7LIQR7gT+FY16QV7jSyQzk80lOZ7UBh7wBWcCFd7TNUIOTJDCSLCPaAaR3cTVGvAAAAf8b/hQDgwYfACAApwCyFwEAK7EaB+mwBjKwGhCxCATpsgkBACuwHi+xAgnpsBMvsQ0J6QGwIS+xIgErsDYauj6j8twAFSsKDrAFELAKwLEbEvmwFsAFsAUQswYFChMrswkFChMrsBsQsxcbFhMrsxobFhMrAwCzBQoWGy4uLi4BtwUGCQoWFxobLi4uLi4uLi6wQBoAsQIeERKwIDmwGhGwADmxExcRErARObANEbAQOTAxAxYzMjY3EyM/Aj4BMzIWFwcmIyIGDwEzByMDDgEjIiflQDBMUhnjwQ3OFy6joCh0ICtMPVddHRnuGe3oJ6KERTj+thZ8cwQ6Q0JkyKUXDoEdYYFsf/u2va4VAAAD/4H+FARMBFwAKAA1AEMA8QCyEAEAK7FABemwEjKyDgEAK7FAB+mwJi+xLAjpsBgvsTkG6QGwRC+wANaxKRLpsCkQsQsBK7E2EumwBSDWEbEcEemwNhCxPQErsRUS6bAVELAjINYRsS8S6bAvL7EjEumxRQErsDYauvhlwHQAFSsKDrAzELAywLEfA/mwIcCzIB8hEyuyIB8hIIogiiMGDhESOQCzHyAyMy4uLi4Bsx8gMjMuLi4usEAaAbEcCxESsAM5sDYRsggmLDk5ObAvErQOGhg5QCQXObEVIxESsBM5ALEYLBESswAFHCMkFzmwORGxCBo5ObBAErELFTk5MDEHNDY3JjU0NjcuATU0NjMyFyEPARYVFAYjIicGFRQWHwEeARUUBCEiJjcUFjMyNjU0Ji8BDgEBFBYzMj4BNTQmIyIOAX+QoU5mWz9Q77pOTAFzGdMp6cM3HYtCP3W1o/7c/vfC3KKCgLbNbIKfeIABFlpQT3Y/WFJOdUHTaZo2KVBFYysgfVPC+BRrGD5gv+MINU4pGwgOFoSAuMqTlk1af3Q+SA4QGX4DElVZVJNWUlZRkQAAAAEAOwAABCkGFAAdAOgAsgAAACuxEh0zM7ILAQArsRgJ6bABL7ACMwGwHi+wANaxHQ7psB0QsRYBK7EODumzEg4WCCuxEw7psBMvsRIO6bEfASuwNhq6PpzyuQAVKwqwABCwAcCwHRCwAsC6PpzyuQAVKwuzAx0CEyuzBB0CEyuzBR0CEyuzBh0CEyuzBx0CEyuzHB0CEyuyHB0CIIogiiMGDhESObAHObAFObAGObAEObADOQC1BxwDBAUGLi4uLi4uAbcBAgccAwQFBi4uLi4uLi4usEAaAbETHRESsAg5sBIRsQsYOTkAsRgAERKxCA45OTAxMwEzDgMHMz4BMzIWFRQHBgMjEzY1NCMiDgEHAzsBSqgSISMpGwtet2SDjxcnaqiUEpNZqYEhZQYUUpqfrmZ7apCEPmjB/iECtF4plHbhn/4nAAACADsAAAIfBd8AAwAOAFkAsgAAACuwAzOyAQEAK7ACM7AML7EHDekBsA8vsADWsQMO6bADELEBASuxAg7psAQg1hGxCRfpsRABK7A2Gro+l/KjABUrCgMBsEAasQIEERKxBww5OQAwMTMTMwMTNDYzMhUUBiMiJjvqqOpxQDNYQywoNARI+7gFYDhHWjdMMQAC/v7+FAIdBd8ADAAXAHMAsgUBACuwBjOwCi+xAgnpsBUvsRAN6QGwGC+wBdaxBhPpsA0g1hGxEhfpsRkBK7A2Gro+o/LdABUrCg6wBRCwBMCwBhCwB8AAsQQHLi4BsQQHLi6wQBoBsQYNERKxEBU5OQCxAgoRErAMObAFEbAAOTAxARYzMjcBMwEOASMiJwE0NjMyFRQGIyIm/v49On0rAQim/vYknYdFNgJWQDNWQywmNP62Fs0E2/sWq58VBzc4R1o3TDEAAAEAOQAABCEGFAAOAJ8AsgAAACuxCg4zM7IHAQArsAEvsAIzAbAPL7AA1rEODumwDhCxAQErsQIO6bEQASuwNhq6PrTzLgAVKwq6PpzyuQAVKwuwDhCzAw4CEyuzBA4CEyuzDQ4CEyuyDQ4CIIogiiMGDhESObADObAEOQCyDQMELi4uAbINAwQuLi6wQBoBsQEOERKxBQY5ObACEbAMOQCxBwARErEFDDk5MDEzATMKAQczATMJASMDBwM5AUqqSHItBAIOyf4rASe765hSBhT+sP3sgQIZ/i39iwIMe/5vAAAAAAEAOQAAAi0GFAADAD0AsgAAACuwAzOwAS+wAjMBsAQvsADWsQMO6bADELEBASuxAg7psQUBK7A2Gro+l/KlABUrCgMBsEAaADAxMwEzATkBTKj+tAYU+ewAAAAAAQA7AAAGhwRcACwAwACyAAAAK7IUICEzMzOyAQEAK7IHAQArsA4zsScJ6bAbMgGwLS+wANaxLA7psCwQsQEBK7ECEOmwAhCxIQErsSAO6bAgELEYASuxEQ7psxQRGAgrsRUO6bAVL7EUDumxLgErsDYauj6V8psAFSsKDrAhELAiwLAgELAfwACxHyIuLgGxHyIuLrBAGgGxAgERErEDBDk5sSAhERKxByc5ObAVEbEKCzk5sBQSsQ4bOTkAsScAERK0AwQKCxEkFzkwMTMTMwczPgEzMhYXMz4BMzIWFRQHAyMTNjU0JiMiDgEHAyMTNjU0JiMiDgEHAzvqixYKV61ccXoLCFbCY3+LFpCqlBRFSlGedx9rqJQSPktUn3khZQRIy3dognR9eYiCRG79YAK0aCo+S3TVkv4MArReKUZOeN+d/iUAAAEAOwAABCkEXAAZAJsAsgAAACuxDQ4zM7IBAQArsgcBACuxFAnpAbAaL7AA1rEZDumwGRCxAQErsQIQ6bACELERASuxCg7psw0KEQgrsQ4O6bAOL7ENDumxGwErsDYauj7o9DkAFSsKDrAOELAPwLANELAMwACxDA8uLgGxDA8uLrBAGgGxAgERErEDBDk5sQ0OERKxBxQ5OQCxFAARErIDBAo5OTkwMTMTMwczPgEzMhYVFAcDIxM2NTQmIyIOAQcDO+qLFgpgs2B/kxePqpQUR05ZqYEhZQRIy3pli31PZf1gArRoKD9MeN6e/iUAAAIAYv/wBB0EVgANABsARACyCwAAK7ERCemyBAEAK7EYCekBsBwvsADWsQ4O6bAOELEVASuxBxXpsR0BK7EVDhESsQQLOTkAsRgRERKxBwA5OTAxEzQSNjMyFhUUAgYjIiY3FBYzMjYSNTQmIyIGAmKS+Je+3JD2m8DarH93aKZdfWttrV8Blr4BT7Phxbz+srbiu4OPkgENrXOPlP75AAAC/9X+FAQ5BFoAFQAiAG4Asg0AACuxGQnpsgEBACuyBgEAK7EfCemwAC8BsCMvsADWsRUT6bAVELEBASuxAhDpsAIQsR0BK7EJDumxJAErsQEVERKwEDmwAhGyAwQWOTk5sB0SswYNGR8kFzkAsR8ZERK0BAkQEQMkFzkwMQMBMwczNjMyFhUUAgYjIiYnIwcOAQMTFBYzMjYSNTQjIgYCKwFQixoIs8GJnor0mmGSKAoEAw9rxG9pY6tosmDHdf4UBjTR48Ow1P6exWRaJhla/gMDRm51ogErqOO+/uAAAAIAYv4UBGAEXAAVACIAWwCyEwAAK7EYCemyCQEAK7IEAQArsR8J6bAMLwGwIy+wANaxFg7psBYQsQwBK7ELE+mxJAErsQwWERKxExg5ObALEbMEDxAfJBc5ALEfGBEStAAIBxAPJBc5MDETNBI2MzIWFzM3MwEjEzY3Iw4BIyImNxQzMjYSNTQmIyIGAmKR95dejyUNQ33+sKZlCTAIX7RgjJ+ss1zEeW1iZbBoAV7UAWjCZVus+cwB4C2weWzDq+O4ASKbaXqp/tcAAAEAOwAAA2gEXAASAEwAsgAAACuyAQEAK7ENCOmyCAEAK7ENA+mwCzIBsBMvsADWsRIO6bASELEBASuxAhDpsRQBK7ECARESsQMEOTkAsQ0AERKxAwQ5OTAxMxMzBzM+AjMyFwcmIyIOAQcDO+qLFgpIXmc/RTMkNTRbn3ccawRIy19TLQ6WDXjVgv4KAAAAAAEACP/sA0QEXAAkAGQAsiMAACuxBAnpshABACuxFgrpAbAlL7AN1rEZDumwGRCxBwErsSAO6bEmASuxGQ0RErALObAHEbUEChAWHCMkFzmwIBKwHTkAsQQjERKwADmwFhGzAQ0TICQXObAQErASOTAxNzUeATMyNjU0JicuATU0NjMyFwcnJiMiBhUUFhceAhUUBiMiCEaiRX6ARnSCbMqlq582OGV3XWpHb2tdLt3JqTGeKi5kTjlOREmMYIqpSokZK1dFOFA/PFZjPpyvAAABAFr/7ALbBUQAGgB5ALIUAAArsQ4J6bIFAQArsQgH6bAaMrIFCAors0AFAwkrAbAbL7AX1rELDumxHAErsDYauj6X8qIAFSsKsBouDrAZwAWxCBP5DrAJwACxCRkuLgGzCAkZGi4uLi6wQBoBALEOFBESsBE5sAgRsRAXOTmwBRKwATkwMRM/AjMHIQchAwYVFBYzMjcVDgEjIiY1NDcTWg65fWI3ARIa/u+BEjo0N1kiZB59hRJ/A8lJTuT8f/2kVy04PBqBDhR3dkJUAloAAQBx/+wEXgRIABgAaQCyEQAAK7IWAAArsQkJ6bIDAQArsA4zAbAZL7AA1rEHDumzAwcACCuxBA7psAcQsREBK7EQEOmwEBCxDgErsQ8T6bEaASuxBAcRErEJFjk5sRARERKxEhM5OQCxAwkRErIAEhM5OTkwMTc0NxMzAwYVFDMyPgE3EzMDIzcjDgEjIiZxFpKqlhKTWKqCImSm54sWDGKyX4CS+D5uAqT9SVkyj3jgngHb+7jLfWKLAAABAGIAAAQSBEgACwBRALILAAArsgABACuxAQgzMwGwDC+wANaxAQ7psQ0BK7A2GrrAWflbABUrCrAAELALwA6wARCwAsAAsAIuAbECCy4usEAaAQCxAAsRErAEOTAxEzMTEhUzEjcBMwEjYqhAGAZ/NAFFsv2x5ARI/Zv+/mgBE2ACXPu4AAAAAQB1AAAGBgRIAB8AbACyHgAAK7AVM7EFCumwDzKyAAEAK7EJEzMzAbAgL7AA1rEBEumwARCwAyDWEbEfEOmwHy+xAxDpsAEQsRkBK7EOEumxIQErsQMBERKwBjmwGRGxCR45ObAOErEKFjk5ALEABRESsRobOTkwMRMzExUUBzM2NwEzExYdAQczNhIBMwEjAyY9ASMPAQEjdaQSCAYvWgEntiUGAgYcbgEMsv4GzSAECTJT/t3KBEj9rliTenzGAnX9rqheNSpWAQkCWPu4AlpeTpx2vf2RAAAAAAH/tgAABAYESAALACYAsgAAACuwCDOyAgEAK7AFMwGwDC+xDQErALECABESsQQKOTkwMSMBAzMTATMBEyMDAUoB2++qrgFKwv45/KjA/qYCNQIT/mQBnP3l/dMBsv5OAAH/O/4UBBIESAAYAF0AsgcBACuxCBEzM7AWL7ECCekBsBkvsAfWsQgO6bEaASuwNhq6wJX3ZAAVKwoOsAcQsAbAsAgQsAnAALEGCS4uAbEGCS4usEAaAQCxAhYRErAYObAHEbEADDk5MDEDFjMyNj8BAzMTFhIVMz4BNwEzAQ4BIyInxT9EUnU3TKaoSgoTBiNoGQFFsv1IXbaASET+sBJlY4gEWv3fRf7zUlfiKwJh+v6shhUAAAAB/+MAAAN9BEgACQAsALIAAAArsQcH6bIEAQArsQMH6QGwCi+xCwErALEHABESsAE5sAMRsAY5MDEjNwEhNyEHASEHHRcCtv4hGwKRHf1YAhMZdQNWfYz8wX0AAAEAAAAABEcERwADACcAsgAAACuyAQEAKwGwBC+wANa0AxcABwQrtAMXAAcEK7EFASsAMDExESERBEcER/u5AAABAAAAARmaXJNtGl8PPPUAHwgAAAAAANJD0icAAAAA0kPSJ/7B/hQHgQYfAAIACAACAAAAAAAAAAEAAAhi/bMAAAb6/sH+/geBAGQAFQAAAAAAAAAAAAAAAAA5AuwARAAAAAAEFAAAAhQAAARx/4sEyQBWBK4AlgVUAFYEFwBWA8cAVgVqAJYFbQBWAi8AVgIj/sEEdQBWA8sAVgayAFQFngBUBcMAlgSHAFYFwwCWBI0AVgQEACcD/AC6BWgApARiALwG0QDfBCf/mAQGALwEP//wBIUAYgSeADsDmgBiBJ4AYgPyAGICgf8bBAL/gQSeADsCCAA7Agj+/gPnADkCCAA5BvoAOwSeADsEfQBiBJ7/1QSeAGIDKwA7A20ACAKYAFoEngBxA7IAYgW8AHUD0/+2A7L/OwON/+MERwAAAAAALAAsACwALACKAQYBUAGmAfYCPgKyAx4DTAOWA/oELgTUBTYFjAXqBkwGugcoB2IHxggICHAIogj4CSgJjAnyCjoKqAsSC5oMdg0aDWINxg44DmYPCg+CD9IQQhCoEPARWBHAEh4SYhLQEwATXBOKE6oAAQAAADkARAADAAAAAAACAAEAAgAWAAABAAD2AAAAAAAAABIA3gADAAEECQAAAHIAAAADAAEECQABABIAcgADAAEECQACAAwAhAADAAEECQADAEoAkAADAAEECQAEACAA2gADAAEECQAFABgA+gADAAEECQAGAB4BEgADAAEECQAHAKQBMAADAAEECQAIACgB1AADAAEECQALADgB/AADAAEECQAMAFwCNAADAAEECQANAFwCkAADAAEECQAOAFQC7AADAAEECQDIABYDQAADAAEECQDJADADVgADAAEECQDKAA4DhgADAAEECQDLAAwDlAADAAEECdkDABoDoABEAGkAZwBpAHQAaQB6AGUAZAAgAGQAYQB0AGEAIABjAG8AcAB5AHIAaQBnAGgAdAAgAKkAIAAyADAAMQAwAC0AMgAwADEAMQAsACAARwBvAG8AZwBsAGUAIABDAG8AcgBwAG8AcgBhAHQAaQBvAG4ALgBPAHAAZQBuACAAUwBhAG4AcwBJAHQAYQBsAGkAYwBBAHMAYwBlAG4AZABlAHIAIAAtACAATwBwAGUAbgAgAFMAYQBuAHMAIABJAHQAYQBsAGkAYwAgAEIAdQBpAGwAZAAgADEAMAAwAE8AcABlAG4AIABTAGEAbgBzACAASQB0AGEAbABpAGMAVgBlAHIAcwBpAG8AbgAgADEALgAxADAATwBwAGUAbgBTAGEAbgBzAC0ASQB0AGEAbABpAGMATwBwAGUAbgAgAFMAYQBuAHMAIABpAHMAIABhACAAdAByAGEAZABlAG0AYQByAGsAIABvAGYAIABHAG8AbwBnAGwAZQAgAGEAbgBkACAAbQBhAHkAIABiAGUAIAByAGUAZwBpAHMAdABlAHIAZQBkACAAaQBuACAAYwBlAHIAdABhAGkAbgAgAGoAdQByAGkAcwBkAGkAYwB0AGkAbwBuAHMALgBBAHMAYwBlAG4AZABlAHIAIABDAG8AcgBwAG8AcgBhAHQAaQBvAG4AaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGEAcwBjAGUAbgBkAGUAcgBjAG8AcgBwAC4AYwBvAG0ALwBoAHQAdABwADoALwAvAHcAdwB3AC4AYQBzAGMAZQBuAGQAZQByAGMAbwByAHAALgBjAG8AbQAvAHQAeQBwAGUAZABlAHMAaQBnAG4AZQByAHMALgBoAHQAbQBsAEwAaQBjAGUAbgBzAGUAZAAgAHUAbgBkAGUAcgAgAHQAaABlACAAQQBwAGEAYwBoAGUAIABMAGkAYwBlAG4AcwBlACwAIABWAGUAcgBzAGkAbwBuACAAMgAuADAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGEAcABhAGMAaABlAC4AbwByAGcALwBsAGkAYwBlAG4AcwBlAHMALwBMAEkAQwBFAE4AUwBFAC0AMgAuADAAVwBlAGIAZgBvAG4AdAAgADEALgAwAFcAZQBkACAATwBjAHQAIAAxADQAIAAwADUAOgAzADQAOgAzADEAIAAyADAAMQA1AGQAZQBmAGEAdQBsAHQAdABhAHUAcgB1AHMARgBvAG4AdAAgAFMAcQB1AGkAcgByAGUAbAACAAD/9AAA/2YAZgAAAAAAAAAAAAAAAAAAAAAAAAAAADkAAAECAQMAAwAkACUAJgAnACgAKQAqACsALAAtAC4ALwAwADEAMgAzADQANQA2ADcAOAA5ADoAOwA8AD0ARABFAEYARwBIAEkASgBLAEwATQBOAE8AUABRAFIAUwBUAFUAVgBXAFgAWQBaAFsAXABdAQQGZ2x5cGgxB3VuaTAwMEQHdW5pMjVGQwC4Af+FsAGNAEuwCFBYsQEBjlmxRgYrWCGwEFlLsBRSWCGwgFkdsAYrXFgAsAMgRbADK0SwCyBFsgPRAiuwAytEsAogRbILgAIrsAMrRLAJIEWyClgCK7ADK0SwCCBFsgk9AiuwAytEsAcgRbIIMAIrsAMrRLAGIEWyByICK7ADK0SwBSBFsgZhAiuwAytEsAQgRbIFFQIrsAMrRLAMIEW6AAMBFAACK7ADK0SwDSBFsgwTAiuwAytEAbAOIEWwAytEsBMgRboADgEDAAIrsQNGditEsBIgRbITiwIrsQNGditEsBEgRbISTwIrsQNGditEsBAgRbIRKwIrsQNGditEsA8gRbIQHwIrsQNGditEsBQgRboADn//AAIrsQNGditEsBUgRbIUxgIrsQNGditEsBYgRbIVWgIrsQNGditEsBcgRbIWKQIrsQNGditEWbAUKwAAAAFWHiGnAAA=) format('truetype');font-weight:400;font-style:normal}.st1{fill:#c6dd7f}.st2{fill:#e9ddb7}.st3{fill:#a6d0e4}.st4{fill:#e6e6e6;stroke:#000;stroke-miterlimit:10}.st5{font-family:'open_sanssemibold',sans-serif}.st6{font-size:16px}.st7{fill:#bef0f0;stroke:#000;stroke-miterlimit:10}.st11{font-family:'open_sansitalic',sans-serif}</style><pattern width="144.13" height="138.362" patternUnits="userSpaceOnUse" id="Alysse" viewBox="99.963 -216.829 144.13 138.362" overflow="visible"><path fill="none" d="M99.963-216.829h144.13v138.362H99.963z"/><path class="st1" d="M311.036-58.307c-11.76-1.384-19.369.346-22.654 3.113-3.02 2.543-4.955 5.405-2.248 11.932 2.939 7.091 1.533 14.732-5.535 15.91-6.225 1.037-10.895-4.842-11.24-12.278-.24-5.183-1.902-8.301-5.533-7.608-3.633.691-4.629 5.9-3.633 11.759 1.385 8.128 5.535 11.76 6.227 20.233.494 6.055-2.939 13.662-12.451 15.045-9.301 1.354-15.91-4.322-16.602-10.549-.732-6.588 3.631-10.894 3.111-17.639-.518-6.745-4.012-10.172-5.879-17.294-2.768-10.549 1.211-19.022 7.781-22.654 14.746-8.148 22.832 3.642 35.971 1.556 10.897-1.729 23.348-18.157 33.031-19.541 8.227-1.175 13.834 4.669 15.045 14.008 1.211 9.338-4.74 15.261-15.391 14.007zm-42.195.519a4.15 4.15 0 10-8.301.001 4.15 4.15 0 008.301-.001zM318.3-73.179a1.728 1.728 0 10-3.458 0 1.728 1.728 0 103.458 0z"/><path class="st2" d="M148.796-77.494c0 7.166 4.588 13.813-1 16.333-8.5 3.833-28-14.333-28-36.167 0-12 8.668-19 17.834-19 12.334 0 18 8.167 18 17.5 0 9.332-6.834 13.139-6.834 21.334zm-5.409-5.37a2.075 2.075 0 10-4.15 0 2.075 2.075 0 004.15 0z"/><path class="st3" d="M223.494-54c-7.871 2.737-19.439-15.297-17.67-27.019 1.24-8.228 7.123-13.189 13.088-14.217 7.525-1.297 12.898 2.601 13.299 7.243.547 6.309-3.633 7.518-4.223 14.958-.562 7.135 3.692 16.186-4.494 19.035zm-3.789-27.508a2.594 2.594 0 10-5.189-.001 2.594 2.594 0 005.189.001z"/><path class="st2" d="M119.35-76.465a2.594 2.594 0 11-5.188 0 2.594 2.594 0 015.188 0z"/><path class="st3" d="M184.573-84.189c.74 8.101 12.671 7.017 17.904 14.214 10.52 14.475-1.219 46.365-21.63 46.365-11.74 0-24.217-9.719-24.217-29.219 0-15.834 10.166-21.5 8.25-42.166-1.006-10.834-12.5-20.343-12.5-34.75 0-5.922 3.586-13.447 11.553-13.447 7.055 0 10.822 5.953 10.822 12.9 0 6.798-5.381 15.74 1.375 19.047 5.242 2.565 13.211-4.77 19.499-6.75 5.191-1.636 12.389.225 14.75 8.5 2.531 8.876-3.252 14.745-11.592 16.693-6.318 1.477-14.802 2.172-14.214 8.613zm-15.984-30.558a3.286 3.286 0 10-6.573-.001 3.286 3.286 0 006.573.001zm25.983 9.695a2.33 2.33 0 10-.003-4.659 2.33 2.33 0 00.003 4.659zM174.589-45.38a3.287 3.287 0 10-6.574 0 3.287 3.287 0 006.574 0z"/><path class="st1" d="M166.907-58.307c-11.76-1.384-19.369.346-22.654 3.113-3.02 2.543-4.955 5.405-2.248 11.932 2.939 7.091 1.533 14.732-5.535 15.91-6.225 1.037-10.895-4.842-11.24-12.278-.24-5.183-1.902-8.301-5.533-7.608-3.633.691-4.629 5.9-3.633 11.759 1.385 8.128 5.535 11.76 6.227 20.233.494 6.055-2.939 13.662-12.451 15.045-9.301 1.354-15.91-4.322-16.602-10.549-.732-6.588 3.631-10.894 3.111-17.639-.517-6.745-4.012-10.172-5.879-17.294-2.768-10.549 1.211-19.022 7.781-22.654 14.746-8.148 22.832 3.642 35.971 1.556 10.896-1.729 23.348-18.157 33.031-19.541 8.227-1.175 13.834 4.669 15.045 14.008 1.21 9.338-4.741 15.261-15.391 14.007zm-42.196.519a4.15 4.15 0 10-8.301.001 4.15 4.15 0 008.301-.001zm49.46-15.391a1.73 1.73 0 10-3.461.001 1.73 1.73 0 003.461-.001z"/><path class="st3" d="M290.284-104.841c0 6.227-4.15 10.721-8.646 11.586-4.496.865-8.318-1.281-12.971 1.211-4.842 2.594-7.09 11.068-16.775 11.068-7.955 0-15.217-7.955-15.217-18.85 0-20.234 13.143-29.226 25.594-29.226 16.601 0 28.015 12.625 28.015 24.211zm-19.714-14.354c0-2.1-1.703-3.803-3.805-3.803a3.804 3.804 0 100 7.608 3.805 3.805 0 003.805-3.805z"/><path class="st1" d="M311.036-196.669c-11.76-1.384-19.369.346-22.654 3.113-3.02 2.543-4.955 5.405-2.248 11.932 2.939 7.091 1.533 14.732-5.535 15.91-6.225 1.037-10.895-4.842-11.24-12.278-.24-5.183-1.902-8.301-5.533-7.608-3.633.691-4.629 5.9-3.633 11.759 1.385 8.128 5.535 11.76 6.227 20.233.494 6.055-2.939 13.662-12.451 15.045-9.301 1.354-15.91-4.322-16.602-10.549-.732-6.588 3.631-10.895 3.111-17.639-.518-6.745-4.012-10.172-5.879-17.294-2.768-10.549 1.211-19.023 7.781-22.654 14.746-8.148 22.832 3.642 35.971 1.556 10.897-1.729 23.348-18.157 33.031-19.541 8.227-1.175 13.834 4.669 15.045 14.008 1.211 9.338-4.74 15.261-15.391 14.007zm-42.195.518a4.15 4.15 0 10-8.301.001 4.15 4.15 0 008.301-.001zm49.459-15.39a1.728 1.728 0 10-3.458 0 1.728 1.728 0 103.458 0z"/><path class="st3" d="M131.796-133.191c-13.957 1.988-21.166-13.332-17.666-20.332 3.666-7.334 12.119-4.168 19.5-4.168 9.666 0 16.367-7.568 20.416-2.25 4.25 5.584-5.01 24.295-22.25 26.75zm.523-17.478a2.249 2.249 0 10-4.497.001 2.249 2.249 0 004.497-.001z"/><path class="st2" d="M148.796-215.857c0 7.166 4.588 13.813-1 16.333-8.5 3.833-28-14.333-28-36.167 0-12 8.668-19 17.834-19 12.334 0 18 8.167 18 17.5 0 9.332-6.834 13.14-6.834 21.334zm-5.409-5.369a2.075 2.075 0 10-4.15 0 2.075 2.075 0 004.15 0z"/><path class="st3" d="M146.155-104.841c0 6.227-4.15 10.721-8.646 11.586-4.496.865-8.318-1.281-12.971 1.211-4.842 2.594-7.09 11.068-16.775 11.068-7.955 0-15.217-7.955-15.217-18.85 0-20.234 13.143-29.226 25.594-29.226 16.601 0 28.015 12.625 28.015 24.211zm-19.715-14.354c0-2.1-1.703-3.803-3.805-3.803a3.804 3.804 0 100 7.608 3.804 3.804 0 003.805-3.805z"/><path class="st1" d="M145.464-128.533a2.421 2.421 0 11-4.842-.002 2.421 2.421 0 014.842.002z"/><path class="st3" d="M229.162-147.037c-3.191 4.68 1.039 10.721-1.383 15.217-2.422 4.498-6.744 5.016-9.857 2.596-3.635-2.828-3.41-6.643-8.301-8.82-5.529-2.465-17.984 2.248-19.714-7.264-.875-4.811 2.375-8.566 7.263-9.684 6.053-1.383 9.352-.18 15.391-3.113 6.053-2.939 11.242-8.993 22.137-12.105 10.406-2.975 16.072 1.557 16.602 5.879 1.036 8.474-17.128 9.949-22.138 17.294zm-2.248-7.437a2.249 2.249 0 10-4.497.001 2.249 2.249 0 004.497-.001z"/><path class="st2" d="M256.129-107.857c0 17.166-14.5 25.5-27 22.832-10.264-2.19-12.834-17.332-16.668-26.166-3.713-8.557-8.832-22.5-20.165-22.5-11.197 0-12.832 14.5-23.666 14.5-11 0-24.5-15.666-24.5-39.666 0-14.667 9.799-31.455 20.834-30.667 11.666.833 4.5 19.667 15.332 19.667 9.5 0 7.857-16.259 9.168-23.334 1.666-9 6.831-14.166 18.497-13.166 14.443 1.237 22.334 13.5 18.871 23.344-4.029 11.451-23.869 17.322-21.537 30.49 1.346 7.592 13 11.998 26 16.166 14.529 4.656 24.834 11.332 24.834 28.5zM211.178-183.7a3.286 3.286 0 106.571 0 3.286 3.286 0 00-6.571 0zm-46.693 24.904a1.73 1.73 0 10-3.458-.002 1.73 1.73 0 003.458.002zm17.467 10.72a3.804 3.804 0 10-7.61 0 3.806 3.806 0 007.61 0zm19.888-15.563a1.557 1.557 0 10-3.113.001 1.557 1.557 0 003.113-.001zm29.642 54.694a3.174 3.174 0 10-6.348 0 3.174 3.174 0 006.348 0z"/><path class="st3" d="M223.494-192.363c-7.871 2.737-19.439-15.297-17.67-27.018 1.24-8.228 7.123-13.189 13.088-14.217 7.525-1.297 12.898 2.6 13.299 7.243.547 6.309-3.633 7.518-4.223 14.958-.562 7.135 3.692 16.186-4.494 19.034zm-3.789-27.508a2.594 2.594 0 10-5.189-.001 2.594 2.594 0 005.189.001z"/><path class="st2" d="M119.35-214.828a2.594 2.594 0 11-5.188 0 2.594 2.594 0 015.188 0zm133.998 86.737c0-8.41-5.078-15.227-11.34-15.227s-11.34 6.816-11.34 15.227c0 8.408 5.078 12.441 11.34 12.441s11.34-4.033 11.34-12.441z"/><path class="st3" d="M184.573-222.551c.74 8.101 12.671 7.017 17.904 14.214 10.52 14.475-1.219 46.365-21.63 46.365-11.74 0-24.217-9.719-24.217-29.219 0-15.834 10.166-21.5 8.25-42.166-1.006-10.834-12.5-20.343-12.5-34.75 0-5.922 3.586-13.447 11.553-13.447 7.055 0 10.822 5.953 10.822 12.9 0 6.798-5.381 15.74 1.375 19.047 5.242 2.565 13.211-4.77 19.499-6.75 5.191-1.636 12.389.225 14.75 8.5 2.531 8.876-3.252 14.745-11.592 16.693-6.318 1.477-14.802 2.171-14.214 8.613zm-15.984-30.559a3.286 3.286 0 10-6.573-.001 3.286 3.286 0 006.573.001zm25.983 9.695a2.33 2.33 0 10-.003-4.659 2.33 2.33 0 00.003 4.659zm-19.983 59.672a3.287 3.287 0 10-6.574 0 3.287 3.287 0 006.574 0z"/><path class="st1" d="M166.907-196.669c-11.76-1.384-19.369.346-22.654 3.113-3.02 2.543-4.955 5.405-2.248 11.932 2.939 7.091 1.533 14.732-5.535 15.91-6.225 1.037-10.895-4.842-11.24-12.278-.24-5.183-1.902-8.301-5.533-7.608-3.633.691-4.629 5.9-3.633 11.759 1.385 8.128 5.535 11.76 6.227 20.233.494 6.055-2.939 13.662-12.451 15.045-9.301 1.354-15.91-4.322-16.602-10.549-.732-6.588 3.631-10.895 3.111-17.639-.517-6.745-4.012-10.172-5.879-17.294-2.768-10.549 1.211-19.023 7.781-22.654 14.746-8.148 22.832 3.642 35.971 1.556 10.896-1.729 23.348-18.157 33.031-19.541 8.227-1.175 13.834 4.669 15.045 14.008 1.21 9.338-4.741 15.261-15.391 14.007zm-42.196.518a4.15 4.15 0 10-8.301.001 4.15 4.15 0 008.301-.001zm49.46-15.39a1.73 1.73 0 10-3.461.001 1.73 1.73 0 003.461-.001zm56.03 37.18a1.384 1.384 0 11-2.768 0 1.384 1.384 0 012.768 0z"/><path class="st2" d="M235.734-212.752a2.248 2.248 0 11-4.497.001 2.248 2.248 0 014.497-.001z"/><path class="st3" d="M152.208-189.58a1.212 1.212 0 01-2.422 0 1.212 1.212 0 012.422 0zm-3.633 68.483c0 .764-.619 1.385-1.383 1.385a1.384 1.384 0 010-2.768c.764 0 1.383.619 1.383 1.383z"/><path class="st2" d="M233.141-143.06a1.21 1.21 0 11-2.42.001 1.21 1.21 0 012.42-.001z"/><path class="st1" d="M195.852-125.134a3.408 3.408 0 11-6.816 0 3.408 3.408 0 016.816 0z"/><path class="st2" d="M200.832-85.283a2.097 2.097 0 11-4.193-.001 2.097 2.097 0 014.193.001zm-38.802-6.293a1.573 1.573 0 11-3.147-.001 1.573 1.573 0 013.147.001z"/><path class="st1" d="M235.701-205.623a2.622 2.622 0 11-5.243-.001 2.622 2.622 0 015.243.001z"/><path class="st3" d="M225.477-170.754a2.36 2.36 0 11-4.719 0 2.36 2.36 0 014.719 0z"/><path class="st2" d="M127.686-164.2a2.622 2.622 0 11-5.245 0 2.622 2.622 0 015.245 0z"/><path class="st3" d="M122.704-171.279a1.31 1.31 0 11-2.62.001 1.31 1.31 0 012.62-.001z"/><path class="st2" d="M186.938-119.367a1.573 1.573 0 11-3.145-.001 1.573 1.573 0 013.145.001z"/><path class="st3" d="M85.033-147.037c-3.191 4.68 1.039 10.721-1.383 15.217-2.422 4.498-6.744 5.016-9.857 2.596-3.635-2.828-3.41-6.643-8.301-8.82-5.529-2.465-17.984 2.248-19.714-7.264-.875-4.811 2.375-8.566 7.263-9.684 6.053-1.383 9.352-.18 15.391-3.113 6.053-2.939 11.242-8.993 22.137-12.105 10.406-2.975 16.072 1.557 16.601 5.879 1.036 8.474-17.128 9.949-22.137 17.294zm-2.248-7.437a2.249 2.249 0 10-4.497.001 2.249 2.249 0 004.497-.001z"/><path class="st2" d="M111.999-107.857c0 17.166-14.5 25.5-27 22.832-10.264-2.19-12.834-17.332-16.668-26.166-3.713-8.557-8.832-22.5-20.165-22.5-11.197 0-12.832 14.5-23.666 14.5-11 0-24.5-15.666-24.5-39.666 0-14.667 9.799-31.455 20.834-30.667 11.666.833 4.5 19.667 15.332 19.667 9.5 0 7.857-16.259 9.168-23.334 1.666-9 6.832-14.166 18.497-13.166 14.443 1.237 22.334 13.5 18.871 23.344-4.029 11.451-23.869 17.322-21.537 30.49 1.346 7.592 13 11.998 26 16.166 14.53 4.656 24.834 11.332 24.834 28.5zM67.048-183.7a3.286 3.286 0 106.571 0 3.286 3.286 0 00-6.571 0zm-46.693 24.904a1.73 1.73 0 10-3.458-.002 1.73 1.73 0 003.458.002zm17.467 10.72a3.804 3.804 0 10-7.61 0 3.806 3.806 0 007.61 0zm19.888-15.563a1.557 1.557 0 10-3.113.001 1.557 1.557 0 003.113-.001zm29.643 54.694a3.174 3.174 0 10-6.348 0 3.174 3.174 0 006.348 0z"/><path class="st2" d="M109.218-128.091c0-8.41-5.078-15.227-11.34-15.227s-11.34 6.816-11.34 15.227c0 8.408 5.078 12.441 11.34 12.441s11.34-4.033 11.34-12.441z"/></pattern><path class="st4" d="M100 105H10a5 5 0 01-5-5V10a5 5 0 015-5h90a5 5 0 015 5v90a5 5 0 01-5 5z"/><text transform="translate(36.152 51.322)"><tspan x="0" y="0" class="st5 st6">Load</tspan><tspan x="-3.406" y="19.2" class="st5 st6">HTML</tspan></text><path class="st7" d="M235 105h-90a5 5 0 01-5-5V10a5 5 0 015-5h90a5 5 0 015 5v90a5 5 0 01-5 5z"/><text transform="translate(168.484 51.322)"><tspan x="0" y="0" class="st5 st6">Parse</tspan><tspan x="-.738" y="19.2" class="st5 st6">HTML</tspan></text><path class="st4" d="M235 240h-90a5 5 0 01-5-5v-90a5 5 0 015-5h90a5 5 0 015 5v90a5 5 0 01-5 5z"/><text transform="translate(171.152 186.322)"><tspan x="0" y="0" class="st5 st6">Load</tspan><tspan x="4.98" y="19.2" class="st5 st6">CSS</tspan></text><path class="st7" d="M370 240h-90a5 5 0 01-5-5v-90a5 5 0 015-5h90a5 5 0 015 5v90a5 5 0 01-5 5z"/><text transform="translate(303.484 186.322)"><tspan x="0" y="0" class="st5 st6">Parse</tspan><tspan x="7.648" y="19.2" class="st5 st6">CSS</tspan></text><path d="M490 105H280a5 5 0 01-5-5V10a5 5 0 015-5h210a5 5 0 015 5v90a5 5 0 01-5 5z" fill="#f0c8b4" stroke="#000" stroke-miterlimit="10"/><text transform="translate(359.477 51.322)"><tspan x="0" y="0" class="st5 st6">Create</tspan><tspan x="-11.918" y="19.2" class="st5 st6">DOM tree</tspan></text><path d="M625 105h-90a5 5 0 01-5-5V10a5 5 0 015-5h90a5 5 0 015 5v90a5 5 0 01-5 5z" fill="url(#Alysse)" stroke="#000" stroke-miterlimit="10"/><text transform="translate(550.773 59.597)" class="st6" font-family="'open_sansbold',sans-serif">Display</text><path d="M145 53.33l-11.25-6.495A2.502 2.502 0 00130 49v4h-25v5h25v3.99a2.502 2.502 0 003.75 2.165L145 57.66a2.502 2.502 0 000-4.33zm135 0l-11.25-6.495A2.502 2.502 0 00265 49v4h-25v5h25v3.99a2.502 2.502 0 003.75 2.165L280 57.66a2.502 2.502 0 000-4.33zm255 0l-11.25-6.495A2.502 2.502 0 00520 49v4h-25v5h25v3.99a2.502 2.502 0 003.75 2.165L535 57.66a2.502 2.502 0 000-4.33zm-336.84 77.92a2.502 2.502 0 00-2.165-1.25H192v-25h-5v25h-3.995a2.502 2.502 0 00-2.165 3.75l6.495 11.25a2.502 2.502 0 004.33 0l6.495-11.25a2.498 2.498 0 000-2.5zM280 188.33l-11.25-6.495A2.502 2.502 0 00265 184v4h-25v5h25v3.99a2.502 2.502 0 003.75 2.165L280 192.66a2.502 2.502 0 000-4.33zm173.28-78.08L446.785 99a2.5 2.5 0 00-4.33 0l-6.495 11.25a2.5 2.5 0 002.165 3.75h4.149c-1.272 24.495-8.289 43.332-20.947 56.042C409.952 181.463 393.933 187.5 375 187.5v5c20.291 0 37.535-6.546 49.869-18.93 13.599-13.655 21.105-33.68 22.407-59.57h3.839a2.5 2.5 0 002.165-3.75z"/><text transform="translate(446.363 159)"><tspan x="0" y="0" class="st11 st6">Attach style</tspan><tspan x="-9.98" y="19.2" class="st11 st6">to DOM nodes</tspan></text></svg> | 0 |
Subsets and Splits