title
stringlengths 2
136
| text
stringlengths 20
75.4k
|
---|---|
Introduction to HTML - Learn web development | Introduction to HTML
====================
At its heart, HTML is a language made up of elements, which can be applied to pieces of text to give them different meaning in a document (Is it a paragraph? Is it a bulleted list? Is it part of a table?), structure a document into logical sections (Does it have a header? Three columns of content? A navigation menu?), and embed content such as images and videos into a page. This module will introduce the first two of these and introduce fundamental concepts and syntax you need to know to understand HTML.
#### 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**
Prerequisites
-------------
Before starting this module, you don't need any previous HTML knowledge, but you should have at least basic familiarity with using computers and using the web passively (i.e., just looking at it and consuming content). You should have a basic work environment set up (as detailed in Installing basic software), and understand how to create and manage files (as detailed in Dealing with files). Both are parts of our Getting started with the web complete beginner's 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 or Glitch.
Guides
------
This module contains the following articles, which will take you through all the basic theory of HTML and provide ample opportunity for you to test out some skills.
Getting started with HTML
Covers the absolute basics of HTML, to get you started β we define elements, attributes, and other important terms, and show where they fit in the language. We also show how a typical HTML page is structured and how an HTML element is structured, and explain other important basic language features. Along the way, we'll play with some HTML to get you interested!
What's in the head? Metadata in HTML
The head of an HTML document is the part that **is not** displayed in the web browser when the page is loaded. It contains information such as the page `<title>`, links to CSS (if you want to style your HTML content with CSS), links to custom favicons, and metadata (data about the HTML, such as who wrote it, and important keywords that describe the document).
HTML text fundamentals
One of HTML's main jobs is to give text meaning (also known as semantics), so that the browser knows how to display it correctly. This article looks at how to use HTML to break up a block of text into a structure of headings and paragraphs, add emphasis/importance to words, create lists, and more.
Creating hyperlinks
Hyperlinks are really important β they are what makes the web a web. This article shows the syntax required to make a link and discusses best practices for links.
Advanced text formatting
There are many other elements in HTML for formatting text that we didn't get to in the HTML text fundamentals article. The elements here are less well-known, but still useful to know about. In this article, you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.
Document and website structure
As well as defining individual parts of your page (such as "a paragraph" or "an image"), HTML is also used to define areas of your website (such as "the header", "the navigation menu", or "the main content column"). This article looks into how to plan a basic website structure and how to write the HTML to represent this structure.
Debugging HTML
Writing HTML is fine, but what if something goes wrong, and you can't work out where the error in the code is? This article will introduce you to some tools that can help.
Assessments
-----------
The following assessments will test your understanding of the HTML basics covered in the guides above.
Marking up a letter
We all learn to write a letter sooner or later; it is also a useful example to test out text formatting skills. In this assessment, you'll be given a letter to mark up.
Structuring a page of content
This assessment tests your ability to use HTML to structure a simple page of content, containing a header, a footer, a navigation menu, main content, and a sidebar. |
HTML Cheat Sheet - Learn web development | HTML Cheat Sheet
================
While using HTML it can be very handy to have an easy way to remember how to use HTML tags properly and how to apply them. MDN provides you with an extended HTML documentation as well as a deep instructional HTML how-to. However, in many cases we just need some quick hints as we go. That's the whole purpose of the cheat sheet, to give you some quick accurate ready to use code snippets for common usages.
**Note:** HTML tags must be used for their semantic, not their appearance. It's always possible to totally change the look and feel of a given tag using CSS so, when using HTML, take the time to focus on the meaning rather than the appearance.
Inline elements
---------------
An "element" is a single part of a webpage. Some elements are large and hold smaller elements like containers. Some elements are small and are "nested" inside larger ones. By default, "inline elements" appear next to one another in a webpage. They take up only as much width as they need in a page and fit together horizontally like words in a sentence or books shelved side-by-side in a row. All inline elements can be placed within the `<body>` element.
Inline elements: usage and examples| Usage | Element | Example |
| --- | --- | --- |
| A link | `<a>` |
```html
<a href="https://example.org">
A link to example.org</a>.
```
|
| An image | `<img>` |
```html
<img src="beast.png" width="50" />
```
|
| An inline container | `<span>` |
```html
Used to group elements: for example,
to <span style="color:blue">style
them</span>.
```
|
| Emphasize text | `<em>` |
```html
<em>I'm posh</em>.
```
|
| Italic text | `<i>` |
```html
Mark a phrase in <i>italics</i>.
```
|
| Bold text | `<b>` |
```html
Bold <b>a word or phrase</b>.
```
|
| Important text | `<strong>` |
```html
<strong>I'm important!</strong>
```
|
| Highlight text | `<mark>` |
```html
<mark>Notice me!</mark>
```
|
| Strikethrough text | `<s>` |
```html
<s>I'm irrelevant.</s>
```
|
| Subscript | `<sub>` |
```html
H<sub>2</sub>O
```
|
| Small text | `<small>` |
```html
Used to represent the <small>small
print </small>of a document.
```
|
| Address | `<address>` |
```html
<address>Main street 67</address>
```
|
| Textual citation | `<cite>` |
```html
For more monsters,
see <cite>The Monster Book of Monsters</cite>.
```
|
| Superscript | `<sup>` |
```html
x<sup>2</sup>
```
|
| Inline quotation | `<q>` |
```html
<q>Me?</q>, she said.
```
|
| A line break | `<br>` |
```html
Line 1<br>Line 2
```
|
| A possible line break | `<wbr>` |
```html
<div style="width: 200px">
Llanfair<wbr>pwllgwyngyllgogerychwyrngogogoch.
</div>
```
|
| Date | `<time>` |
```html
Used to format the date. For example:
<time datetime="2020-05-24" pubdate>
published on 23-05-2020</time>.
```
|
| Code format | `<code>` |
```html
This text is in normal format,
but <code>this text is in code
format</code>.
```
|
| Audio | `<audio>` |
```html
<audio controls>
<source src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3" type="audio/mpeg">
</audio>
```
|
| Video | `<video>` |
```html
<video controls width="250"
src="https://archive.org/download/ElephantsDream/ed\_hd.ogv" >
<a href="https://archive.org/download/ElephantsDream/ed\_hd.ogv">Download OGV video</a>
</video>
```
|
Block elements
--------------
"Block elements," on the other hand, take up the entire width of a webpage. They also take up a full line of a webpage; they do not fit together side-by-side. Instead, they stack like paragraphs in an essay or toy blocks in a tower.
**Note:** Because this cheat sheet is limited to a few elements representing specific structures or having special semantics, the `div` element is intentionally not included β because the `div` element doesn't represent anything and doesn't have any special semantics.
| Usage | Element | Example |
| --- | --- | --- |
| A simple paragraph | `<p>` |
```html
<p>I'm a paragraph</p>
<p>I'm another paragraph</p>
```
|
| An extended quotation | `<blockquote>` |
```html
They said:
<blockquote>The blockquote element indicates
an extended quotation.</blockquote>
```
|
| Additional information | `<details>` |
```html
<details>
<summary>Html Cheat Sheet</summary>
<p>Inline elements</p>
<p>Block elements</p>
</details>
```
|
| An unordered list | `<ul>` |
```html
<ul>
<li>I'm an item</li>
<li>I'm another item</li>
</ul>
```
|
| An ordered list | `<ol>` |
```html
<ol>
<li>I'm the first item</li>
<li>I'm the second item</li>
</ol>
```
|
| A definition list | `<dl>` |
```html
<dl>
<dt>A Term</dt>
<dd>Definition of a term</dd>
<dt>Another Term</dt>
<dd>Definition of another term</dd>
</dl>
```
|
| A horizontal rule | `<hr>` |
```html
before<hr>after
```
|
| Text Heading | <h1>-<h6> |
```html
<h1> This is Heading 1 </h1>
<h2> This is Heading 2 </h2>
<h3> This is Heading 3 </h3>
<h4> This is Heading 4 </h4>
<h5> This is Heading 5 </h5>
<h6> This is Heading 6 </h6>
```
| |
Use HTML to solve common problems - Learn web development | Use HTML to solve common problems
=================================
The following links point to solutions to common everyday problems you'll need to solve with HTML.
### Basic structure
The most basic application of HTML is document structure. If you're new to HTML you should start with this.
* How to create a basic HTML document
* How to divide a webpage into logical sections
* How to set up a proper structure of headings and paragraphs
### Basic text-level semantics
HTML specializes in providing semantic information for a document, so HTML answers many questions you might have about how to get your message across best in your document.
* How to create a list of items with HTML
* How to stress or emphasize content
* How to indicate that text is important
* How to display computer code with HTML
* How to annotate images and graphics
* How to mark abbreviations and make them understandable
* How to add quotations and citations to web pages
* How to define terms with HTML
### Hyperlinks
One of the main reasons for HTML is making navigation easy with hyperlinks, which can be used in many different ways:
* How to create a hyperlink
* How to create a table of contents with HTML
### Images & multimedia
* How to add images to a webpage
* How to add video content to a webpage
### Scripting & styling
HTML only sets up document structure. To solve presentation issues, use CSS, or use scripting to make your page interactive.
* How to use CSS within a webpage
* How to use JavaScript within a webpage
### Embedded content
* How to embed a webpage within another webpage
Uncommon or advanced problems
-----------------------------
Beyond the basics, HTML is very rich and offers advanced features for solving complex problems. These articles help you tackle the less common use cases you may face:
### Forms
Forms are a complex HTML structure made to send data from a webpage to a web server. We encourage you to go over our full dedicated guide. Here is where you should start:
* How to create a simple Web form
* How to structure a Web form
### Tabular information
Some information, called tabular data, needs to be organized into tables with columns and rows. It's one of the most complex HTML structures, and mastering it is not easy:
* How to create a data table
* How to make HTML tables accessible
### Data representation
* How to represent numeric and code values with HTML β see Superscript and Subscript, and Representing computer code.
* How to use data attributes
### Advanced text semantics
* How to take control of HTML line breaking
* How to mark changes (added and removed text) β see the `<ins>` and `<del>` elements.
### Advanced images & multimedia
* How to add a responsive image to a webpage
* How to add vector image to a webpage
* How to add a hit map on top of an image
### Internationalization
HTML is not monolingual. It provides tools to handle common internationalization issues.
* How to add multiple languages into a single webpage
* How to display time and date with HTML
### Performance
* How to author fast-loading HTML pages |
Multimedia and embedding - Learn web development | Multimedia and embedding
========================
We've looked at a lot of text so far in this course, but the web would be really boring only using text. Let's start looking at how to make the web come alive with more interesting content! This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire webpages.
#### 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**
Prerequisites
-------------
Before starting this module, you should have a reasonable understanding of the basics of HTML, as previously covered in Introduction to HTML. If you have not worked through this module (or something similar), work through it first, then come back!
**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 or Glitch.
Guides
------
This module contains the following articles, which will take you through all the fundamentals of embedding multimedia on webpages.
Images in HTML
There are other types of multimedia to consider, but it is logical to start with the humble `<img>` element used to embed a simple image in a webpage. In this article we'll look at how to use it in more depth, including basics, annotating it with captions using `<figure>`, and how it relates to CSS background images.
Video and audio content
Next, we'll look at how to use the HTML `<video>` and `<audio>` elements to embed video and audio on our pages, including basics, providing access to different file formats to different browsers, adding captions and subtitles, and how to add fallbacks for older browsers.
From <object> to <iframe> β other embedding technologies
At this point we'd like to take somewhat of a sideways step, looking at a couple of elements that allow you to embed a wide variety of content types into your webpages: the `<iframe>`, `<embed>` and `<object>` elements. `<iframe>`s are for embedding other web pages, and the other two allow you to embed external resources such as PDF files.
Adding vector graphics to the Web
Vector graphics can be very useful in certain situations. Unlike regular formats like PNG/JPG, they don't distort/pixelate when zoomed in β they can remain smooth when scaled. This article introduces you to what vector graphics are and how to include the popular SVG format in web pages.
Responsive images
In this article, we'll learn about the concept of responsive images β images that work well on devices with widely differing screen sizes, resolutions, and other such features β and look at what tools HTML provides to help implement them. This helps to improve performance across different devices. Responsive images are just one part of responsive design, a future CSS topic for you to learn.
Assessments
-----------
The following assessment will test your understanding of the material covered in the guides above.
Mozilla splash page
In this assessment, we'll test your knowledge of some of the techniques discussed in this module's articles, getting you to add some images and video to a funky splash page all about Mozilla!
See also
--------
Add a hitmap on top of an image
Image maps provide a mechanism to make different parts of an image link to different places. (Think of a map linking through to further information about each different country you click on.) This technique can sometimes be useful.
Web literacy basics II
An excellent Mozilla foundation course that explores and tests some of the skills talked about in this *Multimedia and embedding* module. Dive deeper into the basics of composing webpages, designing for accessibility, sharing resources, using online media, and working open (meaning that your content is freely available and shareable by others). |
HTML tables - Learn web development | HTML tables
===========
A very common task in HTML is structuring tabular data, and it has a number of elements and attributes for just this purpose. Coupled with a little CSS for styling, HTML makes it easy to display tables of information on the web such as your school lesson plan, the timetable at your local swimming pool, or statistics about your favorite dinosaurs or football team. This module takes you through all you need to know about structuring tabular data using HTML.
#### 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**
Prerequisites
-------------
Before starting this module, you should already have covered the basics of HTML β see Introduction to HTML.
**Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Glitch.
Guides
------
This module contains the following articles, which will take you through all the fundamentals of creating tables in HTML.
HTML table basics
This article gets you started with HTML tables, covering the very basics such as rows and cells, headings, making cells span multiple columns and rows, and how to group together all the cells in a column for styling purposes.
HTML table advanced features and accessibility
This article looks at some more advanced features of HTML tables β such as captions/summaries and grouping your rows into table head, body and footer sections β as well as looking at the accessibility of tables for visually impaired users.
Assessments
-----------
The following assessment will test your understanding of the HTML table techniques covered in the guides above.
Structuring planet data
In our table assessment, we provide you with some data on the planets in our solar system, and get you to structure it into an HTML table. |
Images in HTML - Learn web development | Images in HTML
==============
* Overview: Multimedia and embedding
* Next
In the beginning, the Web was just text, and it was really quite boring. Fortunately, it wasn't too long before the ability to embed images (and other more interesting types of content) inside web pages was added. It is logical to start with the humble `<img>` element, used to embed a simple image in a webpage, but there are other types of multimedia to consider. In this article we'll look at how to use it in depth, including the basics, annotating it with captions using `<figure>`, and detailing how it relates to CSS background images, and we'll introduce other graphics available to the web platform.
Multimedia and Embedding Images| Prerequisites: | Basic software installed, basic knowledge of
working with files, familiarity with HTML fundamentals (as covered in
Getting started with HTML.)
|
| Objective: |
To learn how to embed simple images in HTML, annotate them with
captions, and how HTML images relate to CSS background images.
|
How do we put an image on a webpage?
------------------------------------
In order to put a simple image on a web page, we use the `<img>` element. This is a void element (meaning, it cannot have any child content and cannot have an end tag) that requires two attributes to be useful: `src` and `alt`. The `src` attribute contains a URL pointing to the image you want to embed in the page. As with the `href` attribute for `<a>` elements, the `src` attribute can be a relative URL or an absolute URL. Without a `src` attribute, an `img` element has no image to load.
The `alt` attribute is described below.
**Note:** You should read A quick primer on URLs and paths to refresh your memory on relative and absolute URLs before continuing.
So for example, if your image is called `dinosaur.jpg`, and it sits in the same directory as your HTML page, you could embed the image like so:
```html
<img src="dinosaur.jpg" alt="Dinosaur" />
```
If the image was in an `images` subdirectory, which was inside the same directory as the HTML page, then you'd embed it like this:
```html
<img src="images/dinosaur.jpg" alt="Dinosaur" />
```
And so on.
**Note:** Search engines also read image filenames and count them towards SEO. Therefore, you should give your image a descriptive filename; `dinosaur.jpg` is better than `img835.png`.
You could also embed the image using its absolute URL, for example:
```html
<img src="https://www.example.com/images/dinosaur.jpg" alt="Dinosaur" />
```
Linking via absolute URLs is not recommended, however. You should host the images you want to use on your site, which in simple setups means keeping the images for your website on the same server as your HTML. In addition, it is more efficient to use relative URLs than absolute URLs in terms of maintenance (when you move your site to a different domain, you won't need to update all your URLs to include the new domain). In more advanced setups, you might use a CDN (Content Delivery Network) to deliver your images.
If you did not create the images, you should make sure you have the permission to use them under the conditions of the license they are published under (see Media assets and licensing below for more information).
**Warning:** *Never* point the `src` attribute at an image hosted on someone else's website *without permission*. This is called "hotlinking". It is considered unethical, since someone else would be paying the bandwidth costs for delivering the image when someone visits your page. It also leaves you with no control over the image being removed or replaced with something embarrassing.
The previous code snippet, either with the absolute or the relative URL, will give us the following result:
![A basic image of a dinosaur, embedded in a browser, with "Images in HTML" written above it](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML/basic-image.png)
**Note:** Elements like `<img>` and `<video>` are sometimes referred to as **replaced elements**. This is because the element's content and size are defined by an external resource (like an image or video file), not by the contents of the element itself. You can read more about them at Replaced elements.
**Note:** You can find the finished example from this section running on GitHub (see the source code too.)
### Alternative text
The next attribute we'll look at is `alt`. Its value is supposed to be a textual description of the image, for use in situations where the image cannot be seen/displayed or takes a long time to render because of a slow internet connection. For example, our above code could be modified like so:
```html
<img
src="images/dinosaur.jpg"
alt="The head and torso of a dinosaur skeleton;
it has a large head with long sharp teeth" />
```
The easiest way to test your `alt` text is to purposely misspell your filename. If for example our image name was spelled `dinosooooor.jpg`, the browser wouldn't display the image, and would display the alt text instead:
![The Images in HTML title, but this time the dinosaur image is not displayed, and alt text is in its place.](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML/alt-text.png)
So, why would you ever see or need alt text? It can come in handy for a number of reasons:
* The user is visually impaired, and is using a screen reader to read the web out to them. In fact, having alt text available to describe images is useful to most users.
* As described above, the spelling of the file or path name might be wrong.
* The browser doesn't support the image type. Some people still use text-only browsers, such as Lynx, which displays the alt text of images.
* You may want to provide text for search engines to utilize; for example, search engines can match alt text with search queries.
* Users have turned off images to reduce data transfer volume and distractions. This is especially common on mobile phones, and in countries where bandwidth is limited or expensive.
What exactly should you write inside your `alt` attribute? It depends on *why* the image is there in the first place. In other words, what you lose if your image doesn't show up:
* **Decoration.** You should use CSS background images for decorative images, but if you must use HTML, add a blank `alt=""`. If the image isn't part of the content, a screen reader shouldn't waste time reading it.
* **Content.** If your image provides significant information, provide the same information in a *brief* `alt` text β or even better, in the main text which everybody can see. Don't write redundant `alt` text. How annoying would it be for a sighted user if all paragraphs were written twice in the main content? If the image is described adequately by the main text body, you can just use `alt=""`.
* **Link.** If you put an image inside `<a>` tags, to turn an image into a link, you still must provide accessible link text. In such cases you may, either, write it inside the same `<a>` element, or inside the image's `alt` attribute β whichever works best in your case.
* **Text.** You should not put your text into images. If your main heading needs a drop shadow, for example, use CSS for that rather than putting the text into an image. However, If you *really can't avoid doing this*, you should supply the text inside the `alt` attribute.
Essentially, the key is to deliver a usable experience, even when the images can't be seen. This ensures all users are not missing any of the content. Try turning off images in your browser and see how things look. You'll soon realize how helpful alt text is if the image cannot be seen.
**Note:** For more information, see our guide to Text Alternatives.
### Width and height
You can use the `width` and `height` attributes to specify the width and height of your image. They are given as integers without a unit, and represent the image's width and height in pixels.
You can find your image's width and height in a number of ways. For example, on the Mac you can use `Cmd` + `I` to get the display information for the image file. Returning to our example, we could do this:
```html
<img
src="images/dinosaur.jpg"
alt="The head and torso of a dinosaur skeleton;
it has a large head with long sharp teeth"
width="400"
height="341" />
```
There's a very good reason to do this. The HTML for your page and the image are separate resources, fetched by the browser as separate HTTP(S) requests. As soon as the browser has received the HTML, it will start to display it to the user. If the images haven't yet been received (and this will often be the case, as image file sizes are often much larger than HTML files), then the browser will render only the HTML, and will update the page with the image as soon as it is received.
For example, suppose we have some text after the image:
```html
<h1>Images in HTML</h1>
<img
src="dinosaur.jpg"
alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"
title="A T-Rex on display in the Manchester University Museum" />
<blockquote>
<p>
But down there it would be dark now, and not the lovely lighted aquarium she
imagined it to be during the daylight hours, eddying with schools of tiny,
delicate animals floating and dancing slowly to their own serene currents
and creating the look of a living painting. That was wrong, in any case. The
ocean was different from an aquarium, which was an artificial environment.
The ocean was a world. And a world is not art. Dorothy thought about the
living things that moved in that world: large, ruthless and hungry. Like us
up here.
</p>
<footer>- Rachel Ingalls, <cite>Mrs. Caliban</cite></footer>
</blockquote>
```
As soon as the browser downloads the HTML, the browser will start to display the page.
Once the image is loaded, the browser adds the image to the page. Because the image takes up space, the browser has to move the text down the page, to fit the image above it:
![Comparison of page layout while the browser is loading a page and when it has finished, when no size is specified for the image.](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML/no-size.png)
Moving the text like this is extremely distracting to users, especially if they have already started to read it.
If you specify the actual size of the image in your HTML, using the `width` and `height` attributes, then the browser knows, before it has downloaded the image, how much space it has to allow for it.
This means that when the image has been downloaded, the browser doesn't have to move the surrounding content.
![Comparison of page layout while the browser is loading a page and when it has finished, when the image size is specified.](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML/size.png)
For an excellent article on the history of this feature, see Setting height and width on images is important again.
**Note:** Although, as we have said, it is good practice to specify the *actual* size of your images using HTML attributes, you should not use them to *resize* images.
If you set the image size too big, you'll end up with images that look grainy, fuzzy, or too small, and wasting bandwidth downloading an image that is not fitting the user's needs. The image may also end up looking distorted, if you don't maintain the correct aspect ratio. You should use an image editor to put your image at the correct size before putting it on your webpage.
If you do need to alter an image's size, you should use CSS instead.
### Image titles
As with links, you can also add `title` attributes to images, to provide further supporting information if needed. In our example, we could do this:
```html
<img
src="images/dinosaur.jpg"
alt="The head and torso of a dinosaur skeleton;
it has a large head with long sharp teeth"
width="400"
height="341"
title="A T-Rex on display in the Manchester University Museum" />
```
This gives us a tooltip on mouse hover, just like link titles:
![The dinosaur image, with a tooltip title on top of it that reads A T-Rex on display at the Manchester University Museum ](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML/image-with-title.png)
However, this is not recommended β `title` has a number of accessibility problems, mainly based around the fact that screen reader support is very unpredictable and most browsers won't show it unless you are hovering with a mouse (so e.g. no access to keyboard users). If you are interested in more information about this, read The Trials and Tribulations of the Title Attribute by Scott O'Hara.
It is better to include such supporting information in the main article text, rather than attached to the image.
### Active learning: embedding an image
It is now your turn to play! This active learning section will have you up and running with a simple embedding exercise. You are provided with a basic `<img>` tag; we'd like you to embed the image located at the following URL:
```url
https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur\_small.jpg
```
Earlier we said to never hotlink to images on other servers, but this is just for learning purposes, so we'll let you off this one time.
We would also like you to:
* Add some alt text, and check that it works by misspelling the image URL.
* Set the image's correct `width` and `height` (hint: it is 200px wide and 171px high), then experiment with other values to see what the effect is.
* Set a `title` on the image.
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 an answer:
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 100px; width: 95%">
<img>
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
'<img src="https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur\_small.jpg"\n alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"\n width="200"\n height="171"\n title="A T-Rex on display in the Manchester University Museum">';
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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 = 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();
};
```
Media assets and licensing
--------------------------
Images (and other media asset types) you find on the web are released under various license types. Before you use an image on a site you are building, ensure you own it, have permission to use it, or comply with the owner's licensing conditions.
### Understanding license types
Let's look at some common categories of licenses you are likely to find on the web.
#### All rights reserved
Creators of original work such as songs, books, or software often release their work under closed copyright protection. This means that, by default, they (or their publisher) have exclusive rights to use (for example, display or distribute) their work. If you want to use copyrighted images with an *all rights reserved* license, you need to do one of the following:
* Obtain explicit, written permission from the copyright holder.
* Pay a license fee to use them. This can be a one-time fee for unlimited use ("royalty-free"), or it might be "rights-managed", in which case you might have to pay specific fees per use by time slot, geographic region, industry or media type, etc.
* Limit your uses to those that would be considered fair use or fair dealing in your jurisdiction.
Authors are not required to include a copyright notice or license terms with their work. Copyright exists automatically in an original work of authorship once it is created in a tangible medium. So if you find an image online and there are no copyright notices or license terms, the safest course is to assume it is protected by copyright with all rights reserved.
#### Permissive
If the image is released under a permissive license, such as MIT, BSD, or a suitable Creative Commons (CC) license, you do not need to pay a license fee or seek permission to use it. Still, there are various licensing conditions you will have to fulfill, which vary by license.
For example, you might have to:
* Provide a link to the original source of the image and credit its creator.
* Indicate whether any changes were made to it.
* Share any derivative works created using the image under the same license as the original.
* Not share any derivative works at all.
* Not use the image in any commercial work.
* Include a copy of the license along with any release that uses the image.
You should consult the applicable license for the specific terms you will need to follow.
**Note:** You may come across the term "copyleft" in the context of permissive licenses. Copyleft licenses (such as the GNU General Public License (GPL) or "Share Alike" Creative Commons licenses) stipulate that derivative works need to be released under the same license as the original.
Copyleft licenses are prominent in the software world. The basic idea is that a new project built with the code of a copyleft-licensed project (this is known as a "fork" of the original software) will also need to be licensed under the same copyleft license. This ensures that the source code of the new project will also be made available for others to study and modify. Note that, in general, licenses that were drafted for software, such as the GPL, are not considered to be good licenses for non-software works as they were not drafted with non-software works in mind.
Explore the links provided earlier in this section to read about the different license types and the kinds of conditions they specify.
#### Public domain/CC0
Work released into the public domain is sometimes referred to as "no rights reserved" β no copyright applies to it, and it can be used without permission and without having to fulfill any licensing conditions. Work can end up in the public domain by various means such as expiration of copyright, or specific waiving of rights.
One of the most effective ways to place work in the public domain is to license it under CC0, a specific creative commons license that provides a clear and unambiguous legal tool for this purpose.
When using public domain images, obtain proof that the image is in the public domain and keep the proof for your records. For example, take a screenshot of the original source with the licensing status clearly displayed, and consider adding a page to your website with a list of the images acquired along with their license requirements.
### Searching for permissively-licensed images
You can find permissive-licensed images for your projects using an image search engine or directly from image repositories.
Search for images using a description of the image you are seeking along with relevant licensing terms. For example, when searching for "yellow dinosaur" add "public domain images", "public domain image library", "open licensed images", or similar terms to the search query.
Some search engines have tools to help you find images with permissive licenses. For example, when using Google, go to the "Images" tab to search for images, then click "Tools". There is a "Usage Rights" dropdown in the resulting toolbar where you can choose to search specifically for images under creative commons licenses.
Image repository sites, such as Flickr, ShutterStock, and Pixabay, have search options to allow you to search just for permissively-licensed images. Some sites exclusively distribute permissively-licensed images and icons, such as Picryl and The Noun Project.
Complying with the license the image has been released under is a matter of finding the license details, reading the license or instruction page provided by the source, and then following those instructions. Reputable image repositories make their license conditions clear and easy to find.
Annotating images with figures and figure captions
--------------------------------------------------
Speaking of captions, there are a number of ways that you could add a caption to go with your image. For example, there would be nothing to stop you from doing this:
```html
<div class="figure">
<img
src="images/dinosaur.jpg"
alt="The head and torso of a dinosaur skeleton;
it has a large head with long sharp teeth"
width="400"
height="341" />
<p>A T-Rex on display in the Manchester University Museum.</p>
</div>
```
This is OK. It contains the content you need, and is nicely stylable using CSS. But there is a problem here: there is nothing that semantically links the image to its caption, which can cause problems for screen readers. For example, when you have 50 images and captions, which caption goes with which image?
A better solution, is to use the HTML `<figure>` and `<figcaption>` elements. These are created for exactly this purpose: to provide a semantic container for figures, and to clearly link the figure to the caption. Our above example could be rewritten like this:
```html
<figure>
<img
src="images/dinosaur.jpg"
alt="The head and torso of a dinosaur skeleton;
it has a large head with long sharp teeth"
width="400"
height="341" />
<figcaption>
A T-Rex on display in the Manchester University Museum.
</figcaption>
</figure>
```
The `<figcaption>` element tells browsers, and assistive technology that the caption describes the other content of the `<figure>` element.
**Note:** From an accessibility viewpoint, captions and `alt` text have distinct roles. Captions benefit even people who can see the image, whereas `alt` text provides the same functionality as an absent image. Therefore, captions and `alt` text shouldn't just say the same thing, because they both appear when the image is gone. Try turning images off in your browser and see how it looks.
A figure doesn't have to be an image. It is an independent unit of content that:
* Expresses your meaning in a compact, easy-to-grasp way.
* Could go in several places in the page's linear flow.
* Provides essential information supporting the main text.
A figure could be several images, a code snippet, audio, video, equations, a table, or something else.
### Active learning: creating a figure
In this active learning section, we'd like you to take the finished code from the previous active learning section, and turn it into a figure:
1. Wrap it in a `<figure>` element.
2. Copy the text out of the `title` attribute, remove the `title` attribute, and put the text inside a `<figcaption>` element below the image.
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 an answer:
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input"
style="min-height: 100px; width: 95%"></textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
'<figure>\n <img src="https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur\_small.jpg"\n alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"\n width="200"\n height="171">\n <figcaption>A T-Rex on display in the Manchester University Museum</figcaption>\n</figure>';
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
CSS background images
---------------------
You can also use CSS to embed images into webpages (and JavaScript, but that's another story entirely). The CSS `background-image` property, and the other `background-*` properties, are used to control background image placement. For example, to place a background image on every paragraph on a page, you could do this:
```css
p {
background-image: url("images/dinosaur.jpg");
}
```
The resulting embedded image is arguably easier to position and control than HTML images. So why bother with HTML images? As hinted to above, CSS background images are for decoration only. If you just want to add something pretty to your page to enhance the visuals, this is fine. Though, such images have no semantic meaning at all. They can't have any text equivalents, are invisible to screen readers, and so on. This is where HTML images shine!
Summing up: if an image has meaning, in terms of your content, you should use an HTML image. If an image is purely decoration, you should use CSS background images.
**Note:** You'll learn a lot more about CSS background images in our CSS topic.
Other graphics on the web
-------------------------
We've seen that static images can be displayed using the `<img>` element, or by setting the background of HTML elements using the `background-image` property. You can also construct graphics on-the-fly, or manipulate images after the fact. The browser offers ways of creating 2D and 3D graphics with code, as well as including video from uploaded files or live streamed from a user's camera. Here are links to articles that provide insight into these more advanced graphics topics:
Canvas
The `<canvas>` element provides APIs to draw 2D graphics using JavaScript.
SVG
Scalable Vector Graphics (SVG) lets you use lines, curves, and other geometric shapes to render 2D graphics. With vectors, you can create images that scale cleanly to any size.
WebGL
The WebGL API guide will get your started with WebGL, the 3D graphics API for the Web that lets you use standard OpenGL ES in web content.
Using HTML audio and video
Just like `<img>`, you can use HTML to embed `<video>` and `<audio>` into a web page and control its playback.
WebRTC
The RTC in WebRTC stands for Real-Time Communications, a technology that enables audio/video streaming and data sharing between browser clients (peers).
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: HTML images.
Summary
-------
That's all for now. We have covered images and captions in detail. In the next article, we'll move it up a gear, looking at how to use HTML to embed video and audio content in web pages.
* Overview: Multimedia and embedding
* Next |
Video and audio content - Learn web development | Video and audio content
=======================
* Previous
* Overview: Multimedia and embedding
* Next
Now that we are comfortable with adding simple images to a webpage, the next step is to start adding video and audio players to your HTML documents! In this article we'll look at doing just that with the `<video>` and `<audio>` elements; we'll then finish off by looking at how to add captions/subtitles to your videos.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, familiarity with HTML fundamentals (as covered in
Getting started with HTML) and
Images in HTML.
|
| Objective: |
To learn how to embed video and audio content into a webpage, and add
captions/subtitles to video.
|
Video and audio on the web
--------------------------
The first influx of online videos and audio were made possible by proprietary plugin-based technologies like Flash and Silverlight. Both of these had security and accessibility issues, and are now obsolete, in favor of native HTML solutions `<video>` and `<audio>` elements and the availability of JavaScript APIs for controlling them. We'll not be looking at JavaScript here β just the basic foundations that can be achieved with HTML.
We won't be teaching you how to produce audio and video files β that requires a completely different skill set. We have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own.
**Note:** Before you begin here, you should also know that there are quite a few OVPs (online video providers) like YouTube, Dailymotion, and Vimeo, and online audio providers like Soundcloud. Such companies offer a convenient, easy way to host and consume videos, so you don't have to worry about the enormous bandwidth consumption. OVPs even usually offer ready-made code for embedding video/audio in your webpages; if you use that route, you can avoid some of the difficulties we discuss in this article. We'll be discussing this kind of service a bit more in the next article.
### The <video> element
The `<video>` element allows you to embed a video very easily. A really simple example looks like this:
```html
<video src="rabbit320.webm" controls>
<p>
Your browser doesn't support HTML video. Here is a
<a href="rabbit320.webm">link to the video</a> instead.
</p>
</video>
```
The features of note are:
`src`
In the same way as for the `<img>` element, the `src` (source) attribute contains a path to the video you want to embed. It works in exactly the same way.
`controls`
Users must be able to control video and audio playback (it's especially critical for people who have epilepsy.) You must either use the `controls` attribute to include the browser's own control interface, or build your interface using the appropriate JavaScript API. At a minimum, the interface must include a way to start and stop the media, and to adjust the volume.
The paragraph inside the `<video>` tags
This is called **fallback content** β this will be displayed if the browser accessing the page doesn't support the `<video>` element, allowing us to provide a fallback for older browsers. This can be anything you like; in this case, we've provided a direct link to the video file, so the user can at least access it some way regardless of what browser they are using.
The embedded video will look something like this:
![A simple video player showing a video of a small white rabbit](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content/simple-video.png)
You can try the example live here (see also the source code.)
### Using multiple source formats to improve compatibility
There's a problem with the above example. It is possible that the video might not play for you, because different browsers support different video (and audio) formats. Fortunately, there are things you can do to help prevent this from being an issue.
#### Contents of a media file
First, let's go through the terminology quickly. Formats like MP3, MP4 and WebM are called **container formats**. They define a structure in which the audio and/or video tracks that make up the media are stored, along with metadata describing the media, what codecs are used to encode its channels, and so forth.
A WebM file containing a movie which has a main video track and one alternate angle track, plus audio for both English and Spanish, in addition to audio for an English commentary track can be conceptualized as shown in the diagram below. Also included are text tracks containing closed captions for the feature film, Spanish subtitles for the film, and English captions for the commentary.
![Diagram conceptualizing the contents of a media file at the track level.](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content/containersandtracks.png)
The audio and video tracks within the container hold data in the appropriate format for the codec used to encode that media. Different formats are used for audio tracks versus video tracks. Each audio track is encoded using an audio codec, while video tracks are encoded using (as you probably have guessed) a video codec. As we talked about before, different browsers support different video and audio formats, and different container formats (like MP3, MP4, and WebM, which in turn can contain different types of video and audio).
For example:
* A WebM container typically packages Vorbis or Opus audio with VP8/VP9 video. This is supported in all modern browsers, though older versions may not work.
* An MP4 container often packages AAC or MP3 audio with H.264 video. This is also supported in all modern browsers.
* The Ogg container tends to use Vorbis audio and Theora video. This is best supported in Firefox and Chrome, but has basically been superseded by the better quality WebM format.
There are some special cases. For example, for some types of audio, a codec's data is often stored without a container, or with a simplified container. One such instance is the FLAC codec, which is stored most commonly in FLAC files, which are just raw FLAC tracks.
Another such situation is the always-popular MP3 file. An "MP3 file" is actually an MPEG-1 Audio Layer III (MP3) audio track stored within an MPEG or MPEG-2 container. This is especially interesting since while most browsers don't support using MPEG media in the `<video>` and `<audio>` elements, they may still support MP3 due to its popularity.
An audio player will tend to play an audio track directly, e.g. an MP3 or Ogg file. These don't need containers.
#### Media file support in browsers
**Note:** Several popular formats, such as MP3 and MP4/H.264, are excellent but are encumbered by patents; that is, there are patents covering some or all of the technology that they're based upon. In the United States, patents covered MP3 until 2017, and H.264 is encumbered by patents through at least 2027.
Because of those patents, browsers that wish to implement support for those codecs must pay typically enormous license fees. In addition, some people prefer to avoid restricted software and prefer to use only open formats. Due to these legal and preferential reasons, web developers find themselves having to support multiple formats to capture their entire audience.
The codecs described in the previous section exist to compress video and audio into manageable files, since raw audio and video are both exceedingly large. Each web browser supports an assortment of **codecs**, like Vorbis or H.264, which are used to convert the compressed audio and video into binary data and back. Each codec offers its own advantages and drawbacks, and each container may also offer its own positive and negative features affecting your decisions about which to use.
Things become slightly more complicated because not only does each browser support a different set of container file formats, they also each support a different selection of codecs. In order to maximize the likelihood that your website or app will work on a user's browser, you may need to provide each media file you use in multiple formats. If your site and the user's browser don't share a media format in common, your media won't play.
Due to the intricacies of ensuring your app's media is viewable across every combination of browsers, platforms, and devices you wish to reach, choosing the best combination of codecs and container can be a complicated task. See Choosing the right container for help selecting the container file format best suited for your needs; similarly, see Choosing a video codec and Choosing an audio codec for help selecting the first media codecs to use for your content and your target audience.
One additional thing to keep in mind: mobile browsers may support additional formats not supported by their desktop equivalents, just like they may not support all the same formats the desktop version does. On top of that, both desktop and mobile browsers *may* be designed to offload handling of media playback (either for all media or only for specific types it can't handle internally). This means media support is partly dependent on what software the user has installed.
So how do we do this? Take a look at the following updated example (try it live here, also):
```html
<video controls>
<source src="rabbit320.mp4" type="video/mp4" />
<source src="rabbit320.webm" type="video/webm" />
<p>
Your browser doesn't support this video. Here is a
<a href="rabbit320.mp4">link to the video</a> instead.
</p>
</video>
```
Here we've taken the `src` attribute out of the actual `<video>` tag, and instead included separate `<source>` elements that point to their own sources. In this case the browser will go through the `<source>` elements and play the first one that it has the codec to support. Including WebM and MP4 sources should be enough to play your video on most platforms and browsers these days.
Each `<source>` element also has a `type` attribute. This is optional, but it is advised that you include it. The `type` attribute contains the MIME type of the file specified by the `<source>`, and browsers can use the `type` to immediately skip videos they don't understand. If `type` isn't included, browsers will load and try to play each file until they find one that works, which obviously takes time and is an unnecessary use of resources.
Refer to our guide to media types and formats for help selecting the best containers and codecs for your needs, as well as to look up the right MIME types to specify for each.
### Other <video> features
There are a number of other features you can include when displaying an HTML video. Take a look at our next example:
```html
<video
controls
width="400"
height="400"
autoplay
loop
muted
preload="auto"
poster="poster.png">
<source src="rabbit320.mp4" type="video/mp4" />
<source src="rabbit320.webm" type="video/webm" />
<p>
Your browser doesn't support this video. Here is a
<a href="rabbit320.mp4">link to the video</a> instead.
</p>
</video>
```
The resulting UI looks something like this:
![A video player showing a poster image before it plays. The poster image says HTML video example, OMG hell yeah!](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content/poster_screenshot_updated.png)
Features include:
`width` and `height`
You can control the video size either with these attributes or with CSS. In both cases, videos maintain their native width-height ratio β known as the **aspect ratio**. If the aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default.
`autoplay`
Makes the audio or video start playing right away, while the rest of the page is loading. You are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying.
`loop`
Makes the video (or audio) start playing again whenever it finishes. This can also be annoying, so only use if really necessary.
`muted`
Causes the media to play with the sound turned off by default.
`poster`
The URL of an image which will be displayed before the video is played. It is intended to be used for a splash screen or advertising screen.
`preload`
Used for buffering large files; it can take one of three values:
* `"none"` does not buffer the file
* `"auto"` buffers the media file
* `"metadata"` buffers only the metadata for the file
You can find the above example available to play live on GitHub (also see the source code.) Note that we haven't included the `autoplay` attribute in the live version β if the video starts to play as soon as the page loads, you don't get to see the poster!
### The <audio> element
The `<audio>` element works just like the `<video>` element, with a few small differences as outlined below. A typical example might look like so:
```html
<audio controls>
<source src="viper.mp3" type="audio/mp3" />
<source src="viper.ogg" type="audio/ogg" />
<p>
Your browser doesn't support this audio file. Here is a
<a href="viper.mp3">link to the audio</a> instead.
</p>
</audio>
```
This produces something like the following in a browser:
![A simple audio player with a play button, timer, volume control, and progress bar](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content/audio-player.png)
**Note:** You can run the audio demo live on GitHub (also see the audio player source code.)
This takes up less space than a video player, as there is no visual component β you just need to display controls to play the audio. Other differences from HTML video are as follows:
* The `<audio>` element doesn't support the `width`/`height` attributes β again, there is no visual component, so there is nothing to assign a width or height to.
* It also doesn't support the `poster` attribute β again, no visual component.
Other than this, `<audio>` supports all the same features as `<video>` β review the above sections for more information about them.
Displaying video text tracks
----------------------------
Now we'll discuss a slightly more advanced concept that is really useful to know about. Many people can't or don't want to hear the audio/video content they find on the Web, at least at certain times. For example:
* Many people have auditory impairments (such as being hard of hearing or deaf) so can't hear the audio clearly if at all.
* Others 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).
* Similarly, in environments where having the audio playing would be a distraction or disruption (such as in a library or when a partner is trying to sleep), having captions can be very useful.
* People who don't speak the language of the video might want a text transcript or even translation to help them understand the media content.
Wouldn't it be nice to be able to provide these people with a transcript of the words being spoken in the audio/video? Well, thanks to HTML video, you can. To do so we use the WebVTT file format and the `<track>` element.
**Note:** "Transcribe" means "to write down spoken words as text." The resulting text is a "transcript."
WebVTT is a format for writing text files containing multiple strings of text along with metadata such as the time in the video at which each text string should be displayed, and even limited styling/positioning information. These text strings are called **cues**, and there are several kinds of cues which are used for different purposes. The most common cues are:
subtitles
Translations of foreign material, for people who don't understand the words spoken in the audio.
captions
Synchronized transcriptions of dialog or descriptions of significant sounds, to let people who can't hear the audio understand what is going on.
timed descriptions
Text which should be spoken by the media player in order to describe important visuals to blind or otherwise visually impaired users.
A typical WebVTT file will look something like this:
```
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:
1. Save it as a `.vtt` file in a sensible place.
2. Link to the `.vtt` file with the `<track>` element. `<track>` should be placed within `<audio>` or `<video>`, but after all `<source>` elements. Use the `kind` attribute to specify whether the cues are `subtitles`, `captions`, or `descriptions`. Further, use `srclang` to tell the browser what language you have written the subtitles in. Finally, add `label` to help readers identify the language they are searching for.
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\_es.vtt" srclang="es" label="Spanish" />
</video>
```
This will result in a video that has subtitles displayed, kind of like this:
![Video player with stand controls such as play, stop, volume, and captions on and off. The video playing shows a scene of a man holding a spear-like weapon, and a caption reads "Esta hoja tiene pasado oscuro."](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content/video-player-with-captions.png)
For more details, including on how to add labels please read Adding captions and subtitles to HTML video. You can find the example that goes along with this article on GitHub, written by Ian Devlin (see the source code too.) This example uses some 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 also help you with SEO, since search engines especially thrive on text. Text tracks even allow search engines to link directly to a spot partway through the video.
### Active learning: Embedding your own audio and video
For this active learning, we'd (ideally) like you to go out into the world and record some of your own video and audio β most phones these days allow you to record audio and video very easily and, provided you can transfer it on to your computer, you can use it. You may have to do some conversion to end up with a WebM and MP4 in the case of video, and an MP3 and Ogg in the case of audio, but there are enough programs out there to allow you to do this without too much trouble, such as Miro Video Converter and Audacity. We'd like you to have a go!
If you are unable to source any video or audio, then you can feel free to use our sample audio and video files to carry out this exercise. You can also use our sample code for reference.
We would like you to:
1. Save your audio and video files in a new directory on your computer.
2. Create a new HTML file in the same directory, called `index.html`.
3. Add `<audio>` and `<video>` elements to the page; make them display the default browser controls.
4. Give both of them `<source>` elements so that browsers will find the audio format they support best and load it. These should include `type` attributes.
5. Give the `<video>` element a poster that will be displayed before the video starts to be played. Have fun creating your own poster graphic.
For an added bonus, you could try researching text tracks, and work out how to add some captions to your video.
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: Multimedia and embedding. Note that the third assessment question in this test assumes knowledge of some of the techniques covered in the next article, so you may want to read that before attempting it.
Summary
-------
And that's a wrap β we hope you had fun playing with video and audio in web pages! In the next article, we'll look at other ways of embedding content on the Web, using technologies like `<iframe>` and `<object>`.
See also
--------
* The HTML media elements: `<audio>`, `<video>`, `<source>`, and `<track>`
* Adding captions and subtitles to video
* Audio and Video delivery: A LOT of detail about putting audio and video onto web pages using HTML and JavaScript.
* Audio and Video manipulation: A LOT of detail about manipulating audio and video using JavaScript (for example adding filters.)
* Web media technologies
* Guide to media types and formats on the web
* Event reference > Media
* Previous
* Overview: Multimedia and embedding
* Next |
Responsive images - Learn web development | Responsive images
=================
* Previous
* Overview: Multimedia and embedding
* Next
In this article, we'll learn about the concept of responsive images β images that work well on devices with widely differing screen sizes, resolutions, and other such features β and look at what tools HTML provides to help implement them. This helps to improve performance across different devices. Responsive images are just one part of responsive design, a future CSS topic for you to learn.
| | |
| --- | --- |
| Prerequisites: |
You should already know the
basics of HTML
and how to
add static images to a web page.
|
| Objective: |
Learn how to use features like
`srcset` and the
`<picture>` element to implement responsive
image solutions on websites.
|
Why responsive images?
----------------------
Let's examine a typical scenario. A typical website may contain a header image and some content images below the header. The header image will likely span the whole of the width of the header, and the content image will fit somewhere inside the content column. Here's a simple example:
![Our example site as viewed on a wide screen - here the first image works OK, as it is big enough to see the detail in the center.](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images/picture-element-wide.png)
This works well on a wide screen device, such as a laptop or desktop (you can see the example live and find the source code on GitHub.) We won't discuss the CSS much in this lesson, except to say that:
* The body content has been set to a maximum width of 1200 pixels β in viewports above that width, the body remains at 1200px and centers itself in the available space. In viewports below that width, the body will stay at 100% of the width of the viewport.
* The header image has been set so that its center always stays in the center of the header, no matter what width the heading is set at. If the site is being viewed on a narrower screen, the important detail in the center of the image (the people) can still be seen, and the excess is lost off either side. It is 200px high.
* The content images have been set so that if the body element becomes smaller than the image, the images start to shrink so that they always stay inside the body, rather than overflowing it.
However, issues arise when you start to view the site on a narrow screen device. The header below looks OK, but it's starting to take up a lot of the screen height for a mobile device. And at this size, it is difficult to see faces of the two people within the first content image.
![Our example site as viewed on a narrow screen; the first image has shrunk to the point where it is hard to make out the detail on it.](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images/non-responsive-narrow.png)
An improvement would be to display a cropped version of the image which displays the important details of the image when the site is viewed on a narrow screen. A second cropped image could be displayed for a medium-width screen device, like a tablet. The general problem whereby you want to serve different cropped images in that way, for various layouts, is commonly known as the **art direction problem**.
In addition, there is no need to embed such large images on the page if it is being viewed on a mobile screen. Doing so can waste bandwidth; in particular, mobile users don't want to waste bandwidth by downloading a large image intended for desktop users, when a small image would do for their device. Conversely, a small raster image starts to look grainy when displayed larger than its original size (a raster image is a set number of pixels wide and a set number of pixels tall, as we saw when we looked at vector graphics). Ideally, multiple resolutions would be made available to the user's web browser. The browser could then determine the optimal resolution to load based on the screen size of the user's device. This is called the **resolution switching problem**.
To make things more complicated, some devices have high resolution screens that need larger images than you might expect to display nicely. This is essentially the same problem, but in a slightly different context.
You might think that vector images would solve these problems, and they do to a certain degree β they are small in file size and scale well, and you should use them wherever possible. However, they aren't suitable for all image types. Vector images are great for simple graphics, patterns, interface elements, etc., but it starts to get very complex to create a vector-based image with the kind of detail that you'd find in say, a photo. Raster image formats such as JPEGs are more suited to the kind of images we see in the above example.
This kind of problem didn't exist when the web first existed, in the early to mid 90s β back then the only devices in existence to browse the Web were desktops and laptops, so browser engineers and spec writers didn't even think to implement solutions. *Responsive image technologies* were implemented recently to solve the problems indicated above by letting you offer the browser several image files, either all showing the same thing but containing different numbers of pixels (*resolution switching*), or different images suitable for different space allocations (*art direction*).
**Note:** The new features discussed in this article β `srcset`/`sizes`/`<picture>` β are all supported in modern desktop and mobile browsers.
How do you create responsive images?
------------------------------------
In this section, we'll look at the two problems illustrated above and show how to solve them using HTML's responsive image features. You should note that we will be focusing on `<img>` elements for this section, as seen in the content area of the example above β the image in the site header is only for decoration, and therefore implemented using CSS background images. CSS arguably has better tools for responsive design than HTML, and we'll talk about those in a future CSS module.
### Resolution switching: Different sizes
So, what is the problem that we want to solve with resolution switching? We want to display identical image content, just larger or smaller depending on the device β this is the situation we have with the second content image in our example. The standard `<img>` element traditionally only lets you point the browser to a single source file:
```html
<img src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy" />
```
We can however use two attributes β `srcset` and `sizes` β to provide several additional source images along with hints to help the browser pick the right one. You can see an example of this in our responsive.html example on GitHub (see also the source code):
```html
<img
srcset="elva-fairy-480w.jpg 480w, elva-fairy-800w.jpg 800w"
sizes="(max-width: 600px) 480px,
800px"
src="elva-fairy-800w.jpg"
alt="Elva dressed as a fairy" />
```
The `srcset` and `sizes` attributes look complicated, but they're not too hard to understand if you format them as shown above, with a different part of the attribute value on each line. Each value contains a comma-separated list, and each part of those lists is made up of three sub-parts. Let's run through the contents of each now:
**`srcset`** defines the set of images we will allow the browser to choose between, and what size each image is. Each set of image information is separated from the previous one by a comma. For each one, we write:
1. An **image filename** (`elva-fairy-480w.jpg`)
2. A space
3. The image's **intrinsic width in pixels** (`480w`) β note that this uses the `w` unit, not `px` as you might expect. An image's intrinsic size is its real size, which can be found by inspecting the image file on your computer (for example, on a Mac you can select the image in Finder and press
`Cmd`
+
`I`
to bring up the info screen).
**`sizes`** defines a set of media conditions (e.g. screen widths) and indicates what image size would be best to choose, when certain media conditions are true β these are the hints we talked about earlier. In this case, before each comma we write:
1. A **media condition** (`(max-width:600px)`) β you'll learn more about these in the CSS topic, but for now let's just say that a media condition describes a possible state that the screen can be in. In this case, we are saying "when the viewport width is 600 pixels or less".
2. A space
3. The **width of the slot** the image will fill when the media condition is true (`480px`)
**Note:** For the slot width, rather than providing an absolute width (for example, `480px`), you can alternatively provide a width relative to the viewport (for example, `50vw`) β but not a percentage. You may have noticed that the last slot width has no media condition (this is the default that is chosen when none of the media conditions are true). The browser ignores everything after the first matching condition, so be careful how you order the media conditions.
So, with these attributes in place, the browser will:
1. Look at screen size, pixel density, zoom level, screen orientation, and network speed.
2. Work out which media condition in the `sizes` list is the first one to be true.
3. Look at the slot size given to that media query.
4. Load the image referenced in the `srcset` list that has the same size as the slot or, if there isn't one, the first image that is bigger than the chosen slot size.
And that's it! At this point, if a supporting browser with a viewport width of 480px loads the page, the `(max-width: 600px)` media condition will be true, and so the browser chooses the `480px` slot. The `elva-fairy-480w.jpg` will be loaded, as its inherent width (`480w`) is closest to the slot size. The 800px picture is 128KB on disk, whereas the 480px version is only 63KB β a saving of 65KB. Now, imagine if this was a page that had many pictures on it. Using this technique could save mobile users a lot of bandwidth.
**Note:** When testing this with a desktop browser, if the browser fails to load the narrower images when you've got its window set to the narrowest width, have a look at what the viewport is (you can approximate it by going into the browser's JavaScript console and typing in `document.querySelector('html').clientWidth`). Different browsers have minimum sizes that they'll let you reduce the window width to, and they might be wider than you'd think. When testing it with a mobile browser, you can use tools like Firefox's `about:debugging` page to inspect the page loaded on the mobile using the desktop developer tools.
To see which images were loaded, you can use Firefox DevTools's Network Monitor tab or Chrome DevTools's Network panel. For Chrome, you may also want to disable cache to prevent it from picking already downloaded images.
Older browsers that don't support these features will just ignore them. Instead, those browsers will go ahead and load the image referenced in the `src` attribute as normal.
**Note:** In the `<head>` of the example linked above, you'll find the line `<meta name="viewport" content="width=device-width">`: this forces mobile browsers to adopt their real viewport width for loading web pages (some mobile browsers lie about their viewport width, and instead load pages at a larger viewport width then shrink the loaded page down, which is not very helpful for responsive images or design).
### Resolution switching: Same size, different resolutions
If you're supporting multiple display resolutions, but everyone sees your image at the same real-world size on the screen, you can allow the browser to choose an appropriate resolution image by using `srcset` with x-descriptors and without `sizes` β a somewhat easier syntax! You can find an example of what this looks like in srcset-resolutions.html (see also the source code):
```html
<img
srcset="elva-fairy-320w.jpg, elva-fairy-480w.jpg 1.5x, elva-fairy-640w.jpg 2x"
src="elva-fairy-640w.jpg"
alt="Elva dressed as a fairy" />
```
![A picture of a little girl dressed up as a fairy, with an old camera film effect applied to the image](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images/resolution-example.png)In this example, the following CSS is applied to the image so that it will have a width of 320 pixels on the screen (also called CSS pixels):
```css
img {
width: 320px;
}
```
In this case, `sizes` is not needed β the browser works out what resolution the display is that it is being shown on, and serves the most appropriate image referenced in the `srcset`. So if the device accessing the page has a standard/low resolution display, with one device pixel representing each CSS pixel, the `elva-fairy-320w.jpg` image will be loaded (the 1x is implied, so you don't need to include it.) If the device has a high resolution of two device pixels per CSS pixel or more, the `elva-fairy-640w.jpg` image will be loaded. The 640px image is 93KB, whereas the 320px image is only 39KB.
### Art direction
To recap, the **art direction problem** involves wanting to change the image displayed to suit different image display sizes. For example, a web page includes a large landscape shot with a person in the middle when viewed on a desktop browser. When viewed on a mobile browser, that same image is shrunk down, making the person in the image very small and hard to see. It would probably be better to show a smaller, portrait image on mobile, which zooms in on the person. The `<picture>` element allows us to implement just this kind of solution.
Returning to our original not-responsive.html example, we have an image that badly needs art direction:
```html
<img src="elva-800w.jpg" alt="Chris standing up holding his daughter Elva" />
```
Let's fix this, with `<picture>`! Like `<video>` and `<audio>`, the `<picture>` element is a wrapper containing several `<source>` elements that provide different sources for the browser to choose from, followed by the all-important `<img>` element. The code in responsive.html looks like so:
```html
<picture>
<source media="(max-width: 799px)" srcset="elva-480w-close-portrait.jpg" />
<source media="(min-width: 800px)" srcset="elva-800w.jpg" />
<img src="elva-800w.jpg" alt="Chris standing up holding his daughter Elva" />
</picture>
```
* The `<source>` elements include a `media` attribute that contains a media condition β as with the first `srcset` example, these conditions are tests that decide which image is shown β the first one that returns true will be displayed. In this case, if the viewport width is 799px wide or less, the first `<source>` element's image will be displayed. If the viewport width is 800px or more, it'll be the second one.
* The `srcset` attributes contain the path to the image to display. Just as we saw with `<img>` above, `<source>` can take a `srcset` attribute with multiple images referenced, as well as a `sizes` attribute. So, you could offer multiple images via a `<picture>` element, but then also offer multiple resolutions of each one. Realistically, you probably won't want to do this kind of thing very often.
* In all cases, you must provide an `<img>` element, with `src` and `alt`, right before `</picture>`, otherwise no images will appear. This provides a default case that will apply when none of the media conditions return true (you could actually remove the second `<source>` element in this example), and a fallback for browsers that don't support the `<picture>` element.
This code allows us to display a suitable image on both wide screen and narrow screen displays, as shown below:
![Our example site as viewed on a wide screen - here the first image works OK, as it is big enough to see the detail in the center.](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images/picture-element-wide.png)
![Our example site as viewed on a narrow screen with the picture element used to switch the first image to a portrait close up of the detail, making it a lot more useful on a narrow screen](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images/picture-element-narrow.png)
**Note:** You should use the `media` attribute only in art direction scenarios; when you do use `media`, don't also offer media conditions within the `sizes` attribute.
### Why can't we just do this using CSS or JavaScript?
When the browser starts to load a page, it starts to download (preload) any images before the main parser has started to load and interpret the page's CSS and JavaScript. That mechanism is useful in general for reducing page load times, but it is not helpful for responsive images β hence the need to implement solutions like `srcset`. For example, you couldn't load the `<img>` element, then detect the viewport width with JavaScript, and then dynamically change the source image to a smaller one if desired. By then, the original image would already have been loaded, and you would load the small image as well, which is even worse in responsive image terms.
Active learning: Implementing your own responsive images
--------------------------------------------------------
For this active learning, we're expecting you to be brave and do it alone, mostly. We want you to implement your own suitable art-directed narrow screen/wide screenshot using `<picture>`, and a resolution switching example that uses `srcset`.
1. Write some simple HTML to contain your code (use `not-responsive.html` as a starting point, if you like).
2. Find a nice wide screen landscape image with some kind of detail contained in it somewhere. Create a web-sized version of it using a graphics editor, then crop it to show a smaller part that zooms in on the detail, and create a second image (about 480px wide is good for this).
3. Use the `<picture>` element to implement an art direction picture switcher!
4. Create multiple image files of different sizes, each showing the same picture.
5. Use `srcset`/`sizes` to create a resolution switcher example, either to serve the same size image at different resolutions depending on the device resolution or to serve different image sizes depending on the viewport widths.
Summary
-------
That's a wrap for responsive images β we hope you enjoyed playing with these new techniques. As a recap, there are two distinct problems we've been discussing here:
* **Art direction**: The problem whereby you want to serve cropped images for different layouts β for example a landscape image showing a full scene for a desktop layout, and a portrait image showing the main subject zoomed in for a mobile layout. You can solve this problem using the `<picture>` element.
* **Resolution switching**: The problem whereby you want to serve smaller image files to narrow-screen devices, as they don't need huge images like desktop displays do β and to serve different resolution images to high density/low density screens. You can solve this problem using vector graphics (SVG images) and the `srcset` with `sizes` attributes.
This also draws to a close the entire Multimedia and embedding module! The only thing to do now before moving on is to try our Multimedia and embedding assessment, and see how you get on. Have fun!
See also
--------
* Jason Grigsby's excellent introduction to responsive images
* Responsive Images: If you're just changing resolutions, use srcset β includes more explanation of how the browser works out which image to use
* `<img>`
* `<picture>`
* `<source>`
* Previous
* Overview: Multimedia and embedding
* Next |
Adding vector graphics to the web - Learn web development | Adding vector graphics to the web
=================================
* Previous
* Overview: Multimedia and embedding
* Next
Vector graphics are very useful in many circumstances β they have small file sizes and are highly scalable, so they don't pixelate when zoomed in or blown up to a large size. In this article we'll show you how to include one in your webpage.
| | |
| --- | --- |
| Prerequisites: |
You should know the
basics of HTML
and how to
insert an image into your document.
|
| Objective: | Learn how to embed an SVG (vector) image into a webpage. |
**Note:** This article doesn't intend to teach you SVG; just what it is, and how to add it to web pages.
What are vector graphics?
-------------------------
On the web, you'll work with two types of images β **raster images**, and **vector images**:
* **Raster images** are defined using a grid of pixels β a raster image file contains information showing exactly where each pixel is to be placed, and exactly what color it should be. Popular web raster formats include Bitmap (`.bmp`), PNG (`.png`), JPEG (`.jpg`), and GIF (`.gif`.)
* **Vector images** are defined using algorithms β a vector image file contains shape and path definitions that the computer can use to work out what the image should look like when rendered on the screen. The SVG format allows us to create powerful vector graphics for use on the Web.
To give you an idea of the difference between the two, let's look at an example. You can find this example live on our GitHub repo as vector-versus-raster.html β it shows two seemingly identical images side by side, of a red star with a black drop shadow. The difference is that the left one is a PNG, and the right one is an SVG image.
The difference becomes apparent when you zoom in the page β the PNG image becomes pixelated as you zoom in because it contains information on where each pixel should be (and what color). When it is zoomed, each pixel is increased in size to fill multiple pixels on screen, so the image starts to look blocky. The vector image however continues to look nice and crisp, because no matter what size it is, the algorithms are used to work out the shapes in the image, with the values being scaled as it gets bigger.
![Two star images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web/raster-vector-default-size.png)
![Two star images zoomed in, one crisp and the other blurry](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web/raster-vector-zoomed.png)
**Note:** The images above are actually all PNGs β with the left-hand star in each case representing a raster image, and the right-hand star representing a vector image. Again, go to the vector-versus-raster.html demo for a real example!
Moreover, vector image files are much lighter than their raster equivalents, because they only need to hold a handful of algorithms, rather than information on every pixel in the image individually.
What is SVG?
------------
SVG is an XML-based language for describing vector images. It's basically markup, like HTML, except that you've got many different elements for defining the shapes you want to appear in your image, and the effects you want to apply to those shapes. SVG is for marking up graphics, not content. SVG defines elements for creating basic shapes, like `<circle>` and `<rect>`, as well as elements for creating more complex shapes, like `<path>` and `<polygon>`. More advanced SVG features include `<feColorMatrix>` (transform colors using a transformation matrix), `<animate>` (animate parts of your vector graphic), and `<mask>` (apply a mask over the top of your image).
As a basic example, the following code creates a circle and a rectangle:
```html
<svg
version="1.1"
baseProfile="full"
width="300"
height="200"
xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="black" />
<circle cx="150" cy="100" r="90" fill="blue" />
</svg>
```
This creates the following output:
From the example above, you may get the impression that SVG is easy to hand code. Yes, you can hand code simple SVG in a text editor, but for a complex image this quickly starts to get very difficult. For creating SVG images, most people use a vector graphics editor like Inkscape or Illustrator. These packages allow you to create a variety of illustrations using various graphics tools, and create approximations of photos (for example Inkscape's Trace Bitmap feature.)
SVG has some additional advantages besides those described so far:
* Text in vector images remains accessible (which also benefits your SEO).
* SVGs lend themselves well to styling/scripting, because each component of the image is an element that can be styled via CSS or scripted via JavaScript.
So why would anyone want to use raster graphics over SVG? Well, SVG does have some disadvantages:
* SVG can get complicated very quickly, meaning that file sizes can grow; complex SVGs can also take significant processing time in the browser.
* SVG can be harder to create than raster images, depending on what kind of image you are trying to create.
Raster graphics are arguably better for complex precision images such as photos, for the reasons described above.
**Note:** In Inkscape, save your files as Plain SVG to save space. Also, please refer to this article describing how to prepare SVGs for the Web.
Adding SVG to your pages
------------------------
In this section we'll go through the different ways in which you can add SVG vector graphics to your web pages.
### The quick way: `img` element
To embed an SVG via an `<img>` element, you just need to reference it in the src attribute as you'd expect. You will need a `height` or a `width` attribute (or both if your SVG has no inherent aspect ratio). If you have not already done so, please read Images in HTML.
```html
<img
src="equilateral.svg"
alt="triangle with all three sides equal"
height="87"
width="100" />
```
#### Pros
* Quick, familiar image syntax with built-in text equivalent available in the `alt` attribute.
* You can make the image into a hyperlink easily by nesting the `<img>` inside an `<a>` element.
* The SVG file can be cached by the browser, resulting in faster loading times for any page that uses the image loaded in the future.
#### Cons
* You cannot manipulate the image with JavaScript.
* If you want to control the SVG content with CSS, you must include inline CSS styles in your SVG code. (External stylesheets invoked from the SVG file take no effect.)
* You cannot restyle the image with CSS pseudoclasses (like `:focus`).
### Troubleshooting and cross-browser support
For browsers that don't support SVG (IE 8 and below, Android 2.3 and below), you could reference a PNG or JPG from your `src` attribute and use a `srcset` attribute (which only recent browsers recognize) to reference the SVG. This being the case, only supporting browsers will load the SVG β older browsers will load the PNG instead:
```html
<img
src="equilateral.png"
alt="triangle with equal sides"
srcset="equilateral.svg" />
```
You can also use SVGs as CSS background images, as shown below. In the below code, older browsers will stick with the PNG that they understand, while newer browsers will load the SVG:
```css
background: url("fallback.png") no-repeat center;
background-image: url("image.svg");
background-size: contain;
```
Like the `<img>` method described above, inserting SVGs using CSS background images means that the SVG can't be manipulated with JavaScript, and is also subject to the same CSS limitations.
If your SVGs aren't showing up at all, it might be because your server isn't set up properly. If that's the problem, this article will point you in the right direction.
### How to include SVG code inside your HTML
You can also open up the SVG file in a text editor, copy the SVG code, and paste it into your HTML document β this is sometimes called putting your **SVG inline**, or **inlining SVG**. Make sure your SVG code snippet begins with an `<svg>` start tag and ends with an `</svg>` end tag. Here's a very simple example of what you might paste into your document:
```html
<svg width="300" height="200">
<rect width="100%" height="100%" fill="green" />
</svg>
```
#### Pros
* Putting your SVG inline saves an HTTP request, and therefore can reduce your loading time a bit.
* You can assign `class`es and `id`s to SVG elements and style them with CSS, either within the SVG or wherever you put the CSS style rules for your HTML document. In fact, you can use any SVG presentation attribute as a CSS property.
* Inlining SVG is the only approach that lets you use CSS interactions (like `:focus`) and CSS animations on your SVG image (even in your regular stylesheet.)
* You can make SVG markup into a hyperlink by wrapping it in an `<a>` element.
#### Cons
* This method is only suitable if you're using the SVG in only one place. Duplication makes for resource-intensive maintenance.
* Extra SVG code increases the size of your HTML file.
* The browser cannot cache inline SVG as it would cache regular image assets, so pages that include the image will not load faster after the first page containing the image is loaded.
* You may include fallback in a `<foreignObject>` element, but browsers that support SVG still download any fallback images. You need to weigh whether the extra overhead is really worthwhile, just to support obsolescent browsers.
### How to embed an SVG with an `iframe`
You can open SVG images in your browser just like webpages. So embedding an SVG document with an `<iframe>` is done just like we studied in From <object> to <iframe> β other embedding technologies.
Here's a quick review:
```html
<iframe src="triangle.svg" width="500" height="500" sandbox>
<img src="triangle.png" alt="Triangle with three unequal sides" />
</iframe>
```
This is definitely not the best method to choose:
#### Cons
* `iframe`s do have a fallback mechanism, as you can see, but browsers only display the fallback if they lack support for `iframe`s altogether.
* Moreover, unless the SVG and your current webpage have the same origin, you cannot use JavaScript on your main webpage to manipulate the SVG.
Active Learning: Playing with SVG
---------------------------------
In this active learning section we'd like you to have a go at playing with some SVG for fun. In the *Input* section below you'll see that we've already provided you with some samples to get you started. You can also go to the SVG Element Reference, find out more details about other toys you can use in SVG, and try those out too. This section is all about practising your research skills, and having some fun.
If you get stuck and can't get your code working, you can always reset it using the *Reset* button.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="width: 95%;min-height: 200px;">
<svg width="100%" height="100%">
<rect width="100%" height="100%" fill="red" />
<circle cx="100%" cy="100%" r="150" fill="blue" stroke="black" />
<polygon points="120,0 240,225 0,225" fill="green"/>
<text x="50" y="100" font-family="Verdana" font-size="55"
fill="white" stroke="black" stroke-width="2">
Hello!
</text>
</svg>
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" disabled />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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 htmlSolution = "";
let solutionEntry = htmlSolution;
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();
};
```
Summary
-------
This article has provided you with a quick tour of what vector graphics and SVG are, why they are useful to know about, and how to include SVG inside your webpages. It was never intended to be a full guide to learning SVG, just a pointer so you know what SVG is if you meet it in your travels around the Web. So don't worry if you don't feel like you are an SVG expert yet. We've included some links below that might help you if you wish to go and find out more about how it works.
In the last article of this module, we'll explore responsive images in detail, looking at the tools HTML has to allow you to make your images work better across different devices.
See also
--------
* SVG tutorial on MDN
* Quick tips for responsive SVGs
* Sara Soueidan's tutorial on responsive SVG images
* Accessibility benefits of SVG
* SVG Properties and CSS
* How to scale SVGs (it's not as simple as raster graphics!)
* Previous
* Overview: Multimedia and embedding
* Next |
Mozilla splash page - Learn web development | Mozilla splash page
===================
* Previous
* Overview: Multimedia and embedding
In this assessment, we'll test your knowledge of some of the techniques discussed in this module's articles, getting you to add some images and video to a funky splash page all about Mozilla!
| | |
| --- | --- |
| Prerequisites: |
Before attempting this assessment you should have already worked through
all the articles in this module.
|
| Objective: |
To test knowledge around embedding images and video in web pages,
frames, and HTML responsive image techniques.
|
Starting point
--------------
To start off this assessment, you need to grab the HTML and all the images available in the mdn-splash-page-start directory on GitHub. Save the contents of index.html in a file called `index.html` on your local drive, in a new directory. Then save pattern.png in the same directory (right click on the image to get an option to save it.)
Access the different images in the originals directory and save them in the same way; you'll want to save them in a different directory for now, as you'll need to manipulate (some of) them using a graphics editor before they're ready to be used.
Alternatively, you could use an online editor such as CodePen, JSFiddle, or Glitch.
**Note:** The example HTML file contains quite a lot of CSS, to style the page. You don't need to touch the CSS, just the HTML inside the `<body>` element β as long as you insert the correct markup, the styling will make it look correct.
If you get stuck, you can reach out to us in one of our communication channels.
Project brief
-------------
In this assessment we are presenting you with a mostly-finished Mozilla splash page, which aims to say something nice and interesting about what Mozilla stands for, and provide some links to further resources. Unfortunately, no images or video have been added yet β this is your job! You need to add some media to make the page look nice and make more sense. The following subsections detail what you need to do:
### Preparing images
Using your favorite image editor, create 400px wide and 120px wide versions of:
* `firefox_logo-only_RGB.png`
* `firefox-addons.jpg`
* `mozilla-dinosaur-head.png`
Call them something sensible, e.g. `firefoxlogo400.png` and `firefoxlogo120.png`.
Along with `mdn.svg`, these images will be your icons to link to further resources, inside the `further-info` area. You'll also link to the Firefox logo in the site header. Save copies of all these inside the same directory as `index.html`.
Next, create a 1200px wide landscape version of `red-panda.jpg`, and a 600px wide portrait version that shows the panda in more of a close up shot. Again, call them something sensible so you can easily identify them. Save a copy of both of these inside the same directory as `index.html`.
**Note:** You should optimize your JPG and PNG images to make them as small as possible, while still looking OK. tinypng.com is a great service for doing this easily.
### Adding a logo to the header
Inside the `<header>` element, add an `<img>` element that will embed the small version of the Firefox logo in the header.
### Adding a video to the main article content
Just inside the `<article>` element (right below the opening tag), embed the YouTube video found at https://www.youtube.com/watch?v=ojcNcvb1olg, using the appropriate YouTube tools to generate the code. The video should be 400px wide.
### Adding responsive images to the further info links
Inside the `<div>` with the class of `further-info` you will find four `<a>` elements β each one linking to an interesting Mozilla-related page. To complete this section you'll need to insert an `<img>` element inside each one containing appropriate `src`, `alt`, `srcset` and `sizes` attributes.
In each case (except one β which one is inherently responsive?) we want the browser to serve the 120px wide version when the viewport width is 500px wide or less, or the 400px wide version otherwise.
Make sure you match the correct images with the correct links!
**Note:** To properly test the `srcset`/`sizes` examples, you'll need to upload your site to a server (using GitHub pages is an easy and free solution), then from there you can test whether they are working properly using browser developer tools such as the Firefox Network Monitor.
### An art directed red panda
Inside the `<div>` with the class of `red-panda`, we want to insert a `<picture>` element that serves the small portrait panda image if the viewport is 600px wide or less, and the large landscape image otherwise.
Hints and tips
--------------
* You can use the W3C Nu HTML Checker to catch mistakes in your HTML.
* You don't need to know any CSS to do this assessment; you just need the provided HTML file. The CSS part is already done for you.
* The provided HTML (including the CSS styling) already does most of the work for you, so you can just focus on the media embedding.
Example
-------
The following screenshots show what the splash page should look like after being correctly marked up, on a wide and narrow screen display.
![A wide shot of our example splash page](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page/wide-shot.png)
![A narrow shot of our example splash page](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page/narrow-shot.png)
* Previous
* Overview: Multimedia and embedding |
From object to iframe β other embedding technologies - Learn web development | From object to iframe β other embedding technologies
====================================================
* Previous
* Overview: Multimedia and embedding
* Next
By now you should really be getting the hang of embedding things into your web pages, including images, video and audio. At this point we'd like to take somewhat of a sideways step, looking at some elements that allow you to embed a wide variety of content types into your webpages: the `<iframe>`, `<embed>` and `<object>` elements. `<iframe>`s are for embedding other web pages, and the other two allow you to embed external resources such as PDF files.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, familiarity with HTML fundamentals (as covered in
Getting started with HTML) and the previous articles in this module.
|
| Objective: |
To learn how to embed items into web pages using
`<object>`, `<embed>`, and
`<iframe>`, like PDF documents and other webpages.
|
A short history of embedding
----------------------------
A long time ago on the Web, it was popular to use **frames** to create websites β small parts of a website stored in individual HTML pages. These were embedded in a master document called a **frameset**, which allowed you to specify the area on the screen that each frame filled, rather like sizing the columns and rows of a table. These were considered the height of coolness in the mid to late 90s, and there was evidence that having a webpage split up into smaller chunks like this was better for download speeds β especially noticeable with network connections being so slow back then. They did however have many problems, which far outweighed any positives as network speeds got faster, so you don't see them being used anymore.
A little while later (late 90s, early 2000s), plugin technologies became very popular, such as Java Applets and Flash β these allowed web developers to embed rich content into webpages such as videos and animations, which just weren't available through HTML alone. Embedding these technologies was achieved through elements like `<object>`, and the lesser-used `<embed>`, and they were very useful at the time. They have since fallen out of fashion due to many problems, including accessibility, security, file size, and more. These days major browsers have stopped supporting plugins such as Flash.
Finally, the `<iframe>` element appeared (along with other ways of embedding content, such as `<canvas>`, `<video>`, etc.) This provides a way to embed an entire web document inside another one, as if it were an `<img>` or other such element, and is used regularly today.
With the history lesson out of the way, let's move on and see how to use some of these.
Active learning: classic embedding uses
---------------------------------------
In this article we are going to jump straight into an active learning section, to immediately give you a real idea of just what embedding technologies are useful for. The online world is very familiar with YouTube, but many people don't know about some of the sharing facilities it has available. Let's look at how YouTube allows us to embed a video in any page we like using an `<iframe>`.
1. First, go to YouTube and find a video you like.
2. Below the video, you'll find a *Share* button β select this to display the sharing options.
3. Select the *Embed* button and you'll be given some `<iframe>` code β copy this.
4. Insert it into the *Input* box below, and see what the result is in the *Output*.
For bonus points, you could also try embedding a Google Map in the example:
1. Go to Google Maps and find a map you like.
2. Click on the "Hamburger Menu" (three horizontal lines) in the top left of the UI.
3. Select the *Share or embed map* option.
4. Select the Embed map option, which will give you some `<iframe>` code β copy this.
5. Insert it into the *Input* box below, and see what the result is in the *Output*.
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 an answer.
```
<h2>Live output</h2>
<div class="output" style="min-height: 250px;"></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="input"
style="width: 95%;min-height: 100px;"></textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
let code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
reset.addEventListener("click", function () {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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 htmlSolution =
'<iframe width="420" height="315" src="https://www.youtube.com/embed/QH2-TGUlwu4" frameborder="0" allowfullscreen>\n</iframe>\n\n<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d37995.65748333395!2d-2.273568166412784!3d53.473310471916975!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x487bae6c05743d3d%3A0xf82fddd1e49fc0a1!2sThe+Lowry!5e0!3m2!1sen!2suk!4v1518171785211" width="600" height="450" frameborder="0" style="border:0" allowfullscreen>\n</iframe>';
let solutionEntry = htmlSolution;
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();
};
```
iframes in detail
-----------------
So, that was easy and fun, right? `<iframe>` elements are designed to allow you to embed other web documents into the current document. This is great for incorporating third-party content into your website that you might not have direct control over and don't want to have to implement your own version of β such as video from online video providers, commenting systems like Disqus, maps from online map providers, advertising banners, etc. Even the live editable examples you've been using through this course are implemented using `<iframe>`s.
Before diving into using `<iframe>` elements, there are some security concerns to be aware of.
Say you wanted to include the MDN glossary on one of your web pages using the `<iframe>` element, you might try something like the next code example.
If you were to add the code below into one of your pages, you might be surprised to see an error message instead of the glossary page:
```html
<head>
<style>
iframe {
border: none;
}
</style>
</head>
<body>
<iframe
src="https://developer.mozilla.org/en-US/docs/Glossary"
width="100%"
height="500"
allowfullscreen
sandbox>
<p>
<a href="/en-US/docs/Glossary">
Fallback link for browsers that don't support iframes
</a>
</p>
</iframe>
</body>
```
If you have a look at your browser's console, you'll see an error message like the following:
```
Refused to display 'https://developer.mozilla.org/' in a frame because it set 'X-Frame-Options' to 'deny'.
```
The Security section below goes into more detail about why you see this error, but first, let's have a look at what our code is doing.
The example includes the bare essentials needed to use an `<iframe>`:
`border: none`
If used, the `<iframe>` is displayed without a surrounding border. Otherwise, by default, browsers display the `<iframe>` with a surrounding border (which is generally undesirable).
`allowfullscreen`
If set, the `<iframe>` is able to be placed in fullscreen mode using the Fullscreen API (somewhat beyond the scope of this article.)
`src`
This attribute, as with `<video>`/`<img>`, contains a path pointing to the URL of the document to be embedded.
`width` and `height`
These attributes specify the width and height you want the iframe to be.
`sandbox`
This attribute, which works in slightly more modern browsers than the rest of the `<iframe>` features (e.g. IE 10 and above) requests heightened security settings; we'll say more about this in the next section.
**Note:** In order to improve speed, it's a good idea to set the iframe's `src` attribute with JavaScript after the main content is done with loading. This makes your page usable sooner and decreases your official page load time (an important SEO metric.)
### Security concerns
Above we mentioned security concerns β let's go into this in a bit more detail now. We are not expecting you to understand all of this content perfectly the first time; we just want to make you aware of this concern, and provide a reference to come back to as you get more experienced and start considering using `<iframe>`s in your experiments and work. Also, there is no need to be scared and not use `<iframe>`s β you just need to be careful. Read onβ¦
Browser makers and Web developers have learned the hard way that iframes are a common target (official term: **attack vector**) for bad people on the Web (often termed **hackers**, or more accurately, **crackers**) to attack if they are trying to maliciously modify your webpage, or trick people into doing something they don't want to do, such as reveal sensitive information like usernames and passwords. Because of this, spec engineers and browser developers have developed various security mechanisms for making `<iframe>`s more secure, and there are also best practices to consider β we'll cover some of these below.
**Note:** Clickjacking is one kind of common iframe attack where hackers embed an invisible iframe into your document (or embed your document into their own malicious website) and use it to capture users' interactions. This is a common way to mislead users or steal sensitive data.
A quick example first though β try loading the previous example we showed above into your browser β you can find it live on GitHub (see the source code too.) Instead of the page you expected, you'll probably see some kind of message to the effect of "I can't open this page", and if you look at the *Console* in the browser developer tools, you'll see a message telling you why. In Firefox, you'll get told something like *The loading of "https://developer.mozilla.org/en-US/docs/Glossary" in a frame is denied by "X-Frame-Options" directive set to "DENY"*. This is because the developers that built MDN have included a setting on the server that serves the website pages to disallow them from being embedded inside `<iframe>`s (see Configure CSP directives, below.) This makes sense β an entire MDN page doesn't really make sense to be embedded in other pages unless you want to do something like embed them on your site and claim them as your own β or attempt to steal data via clickjacking, which are both really bad things to do. Plus if everybody started to do this, all the additional bandwidth would start to cost Mozilla a lot of money.
#### Only embed when necessary
Sometimes it makes sense to embed third-party content β like youtube videos and maps β but you can save yourself a lot of headaches if you only embed third-party content when completely necessary. A good rule for web security is *"You can never be too cautious. If you made it, double-check it anyway. If someone else made it, assume it's dangerous until proven otherwise."*
Besides security, you should also be aware of intellectual property issues. Most content is copyrighted, offline and online, even content you might not expect (for example, most images on Wikimedia Commons). Never display content on your webpage unless you own it or the owners have given you written, unequivocal permission. Penalties for copyright infringement are severe. Again, you can never be too cautious.
If the content is licensed, you must obey the license terms. For example, the content on MDN is licensed under CC-BY-SA. That means, you must credit us properly when you quote our content, even if you make substantial changes.
#### Use HTTPS
HTTPS is the encrypted version of HTTP. You should serve your websites using HTTPS whenever possible:
1. HTTPS reduces the chance that remote content has been tampered with in transit.
2. HTTPS prevents embedded content from accessing content in your parent document, and vice versa.
HTTPS-enabling your site requires a special security certificate to be installed. Many hosting providers offer HTTPS-enabled hosting without you needing to do any setup on your own to put a certificate in place. But if you *do* need to set up HTTPS support for your site on your own, Let's Encrypt provides tools and instructions you can use for automatically creating and installing the necessary certificate β with built-in support for the most widely-used web servers, including the Apache web server, Nginx, and others. The Let's Encrypt tooling is designed to make the process as easy as possible, so there's really no good reason to avoid using it or other available means to HTTPS-enable your site.
**Note:** GitHub pages allow content to be served via HTTPS by default.
If you are using a different hosting provider you should check what support they provide for serving content with HTTPS.
#### Always use the `sandbox` attribute
You want to give attackers as little power as you can to do bad things on your website, therefore you should give embedded content *only the permissions needed for doing its job.* Of course, this applies to your own content, too. A container for code where it can be used appropriately β or for testing β but can't cause any harm to the rest of the codebase (either accidental or malicious) is called a sandbox.
Content that's not sandboxed may be able to execute JavaScript, submit forms, trigger popup windows, etc. By default, you should impose all available restrictions by using the `sandbox` attribute with no parameters, as shown in our previous example.
If absolutely required, you can add permissions back one by one (inside the `sandbox=""` attribute value) β see the `sandbox` reference entry for all the available options. One important note is that you should *never* add both `allow-scripts` and `allow-same-origin` to your `sandbox` attribute β in that case, the embedded content could bypass the Same-origin policy that stops sites from executing scripts, and use JavaScript to turn off sandboxing altogether.
**Note:** Sandboxing provides no protection if attackers can fool people into visiting malicious content directly (outside an `iframe`). If there's any chance that certain content may be malicious (e.g., user-generated content), please serve it from a different domain to your main site.
#### Configure CSP directives
CSP stands for **content security policy** and provides a set of HTTP Headers (metadata sent along with your web pages when they are served from a web server) designed to improve the security of your HTML document. When it comes to securing `<iframe>`s, you can *configure your server to send an appropriate `X-Frame-Options` header.* This can prevent other websites from embedding your content in their web pages (which would enable clickjacking and a host of other attacks), which is exactly what the MDN developers have done, as we saw earlier on.
**Note:** You can read Frederik Braun's post On the X-Frame-Options Security Header for more background information on this topic. Obviously, it's rather out of scope for a full explanation in this article.
The <embed> and <object> elements
---------------------------------
The `<embed>` and `<object>` elements serve a different function to `<iframe>` β these elements are general purpose embedding tools for embedding external content, such as PDFs.
However, you are unlikely to use these elements very much. If you need to display PDFs, it's usually better to link to them, rather than embedding them in the page.
Historically these elements have also been used for embedding content handled by browser plugins such as Adobe Flash, but this technology is now obsolete and is not supported by modern browsers.
If you find yourself needing to embed plugin content, this is the kind of information you'll need, at a minimum:
| | `<embed>` | `<object>` |
| --- | --- | --- |
| URL of the embedded content | `src` | `data` |
| *accurate* media type
of the embedded content
| `type` | `type` |
| height and width (in CSS pixels) of the box controlled by the plugin | `height``width` | `height``width` |
| names and values, to feed the plugin as parameters | ad hoc attributes with those names and values |
single-tag `<param>` elements, contained within
`<object>` |
| independent HTML content as fallback for an unavailable resource | not supported (`<noembed>` is obsolete) |
contained within `<object>`, after
`<param>` elements
|
Let's look at an `<object>` example that embeds a PDF into a page (see the live example and the source code):
```html
<object data="mypdf.pdf" type="application/pdf" width="800" height="1200">
<p>
You don't have a PDF plugin, but you can
<a href="mypdf.pdf">download the PDF file. </a>
</p>
</object>
```
PDFs were a necessary stepping stone between paper and digital, but they pose many accessibility challenges and can be hard to read on small screens. They do still tend to be popular in some circles, but it is much better to link to them so they can be downloaded or read on a separate page, rather than embedding them in a webpage.
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: Multimedia and embedding.
Summary
-------
The topic of embedding other content in web documents can quickly become very complex, so in this article, we've tried to introduce it in a simple, familiar way that will immediately seem relevant, while still hinting at some of the more advanced features of the involved technologies. To start with, you are unlikely to use embedding for much beyond including third-party content like maps and videos on your pages. As you become more experienced, however, you are likely to start finding more uses for them.
There are many other technologies that involve embedding external content besides the ones we discussed here. We saw some in earlier articles, such as `<video>`, `<audio>`, and `<img>`, but there are others to discover, such as `<canvas>` for JavaScript-generated 2D and 3D graphics, and `<svg>` for embedding vector graphics. We'll look at SVG in the next article of the module.
* Previous
* Overview: Multimedia and embedding
* Next |
Test your skills: Multimedia and embedding - Learn web development | Test your skills: Multimedia and embedding
==========================================
The aim of this skill test is to assess whether you understand how to embed video and audio content in HTML, also using object, iframe and other embedding technologies.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, we want you to embed a simple audio file onto the page. You need to:
* Add the path to the audio file to an appropriate attribute to embed it on the page. The audio is called `audio.mp3`, and it is in a folder inside the current folder called `media`.
* Add an attribute to make browsers display some default controls.
* Add some appropriate fallback text for browsers that don't support `<audio>`.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, we want you to mark up a slightly more complex video player, with multiple sources, subtitles, and other features besides. You need to:
* Add an attribute to make browsers display some default controls.
* Add some appropriate fallback text for browsers that don't support `<video>`.
* Add multiple sources, containing the paths to the video files. The files are called `video.mp4` and `video.webm`, and are in a folder inside the current folder called `media`.
* Let the browser know in advance what video formats the sources point to, so it can make an informed choice of which one to download ahead of time.
* Give the `<video>` a width and height equal to its intrinsic size (320 by 240 pixels).
* Make the video muted by default.
* Display the text tracks contained in the `media` folder, in a file called `subtitles_en.vtt`, when the video is playing. You must explicitly set the type as subtitles, and the subtitle language to English.
* Make sure the readers can identify the subtitle language when they use the default controls.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 3
------
In this task, we want you to:
* Embed a PDF into the page. The PDF is called `mypdf.pdf`, and is contained in the `media` folder.
* Go to a sharing site like YouTube or Google Maps, and embed a video or other media item into the page.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Test your skills: HTML images - Learn web development | Test your skills: HTML images
=============================
The aim of this skill test is to assess whether you understand images and how to embed them in HTML.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, we want you to embed a simple image of some Blueberries into the page. You need to:
* Add the path to the image to an appropriate attribute to embed it on the page. The image is called `blueberries.jpg`, and it is in a folder inside the current folder called `images`.
* Add some alternative text to an appropriate attribute to describe the image, for people that cannot see it.
* Give the `<img>` element an appropriate `width` and `height` so that it displays at the correct aspect ratio, and enough space is left on the page to display it. The image's intrinsic size is 615 x 419 pixels.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, you already have a full-featured image, but we'd like you to add a tooltip that appears when the image is moused over. You should put some appropriate information into the tooltip.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 3
------
In this task, you are provided with both a full-featured image and some caption text. What you need to do here is add elements that will associate the image with the caption.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Tips for authoring fast-loading HTML pages - Learn web development | Tips for authoring fast-loading HTML pages
==========================================
These tips are based on common knowledge and experimentation.
An optimized web page not only provides for a more responsive site for your visitors but also reduces the load on your web servers and internet connection. This can be crucial for high volume sites or sites which have a spike in traffic due to unusual circumstances such as breaking news stories.
Optimizing page load performance is not just for content which will be viewed by narrowband dial-up or mobile device visitors. It is just as important for broadband content and can lead to dramatic improvements even for your visitors with the fastest connections.
Tips
----
### Reduce page weight
Page weight is by far the most important factor in page-load performance.
Reducing page weight through the elimination of unnecessary whitespace and comments, commonly known as minimization, and by moving inline script and CSS into external files, can improve download performance with minimal need for other changes in the page structure.
Tools such as HTML Tidy can automatically strip leading whitespace and extra blank lines from valid HTML source. Other tools can "compress" JavaScript by reformatting the source or by obfuscating the source and replacing long identifiers with shorter versions.
### Minimize the number of files
Reducing the number of files referenced in a web page lowers the number of HTTP connections required to download a page, thereby reducing the time for these requests to be sent, and for their responses to be received.
Depending on a browser's cache settings, it may send a request with the `If-Modified-Since` header for each referenced file, asking whether the file has been modified since the last time it was downloaded. Too much time spent querying the last modified time of the referenced files can delay the initial display of the web page, since the browser must check the modification time for each of these files, before rendering the page.
If you use background images a lot in your CSS, you can reduce the number of HTTP lookups needed by combining the images into one, known as an image sprite. Then you just apply the same image each time you need it for a background and adjust the x/y coordinates appropriately. This technique works best with elements that will have limited dimensions, and will not work for every use of a background image. However, the fewer HTTP requests and single image caching can help reduce page-load time.
### Use a Content Delivery Network (CDN)
For the purposes of this article, a CDN is a means to reduce the physical distance between your server and your visitor. As the distance between your server origin and visitor increases, the load times will increase. Suppose your website server is located in the United States and it has a visitor from India; the page load time will be much higher for the Indian visitor compared to a visitor from the US.
A CDN is a geographically distributed network of servers that work together to shorten the distance between the user and your website. CDNs store cached versions of your website and serve them to visitors via the network node closest to the user, thereby reducing latency.
Further reading:
* Understanding CDNs
### Reduce domain lookups
Since each separate domain costs time in a DNS lookup, the page load time will grow along with the number of separate domains appearing in CSS link(s) and JavaScript and image src(es).
This may not always be practical; however, you should always take care to use only the minimum necessary number of different domains in your pages.
### Cache reused content
Make sure that any content that can be cached, is cached, and with appropriate expiration times.
In particular, pay attention to the `Last-Modified` header. It allows for efficient page caching; by means of this header, information is conveyed to the user agent about the file it wants to load, such as when it was last modified. Most web servers automatically append the `Last-Modified` header to static pages (e.g. `.html`, `.css`), based on the last-modified date stored in the file system. With dynamic pages (e.g. `.php`, `.aspx`), this, of course, can't be done, and the header is not sent.
So, in particular, for pages which are generated dynamically, a little research on this subject is beneficial. It can be somewhat involved, but it will save a lot in page requests on pages which would normally not be cacheable.
More information:
1. HTTP Conditional Get for RSS Hackers
2. HTTP 304: Not Modified
3. HTTP ETag on Wikipedia
4. Caching in HTTP
### Optimally order the components of the page
Download page content first, along with any CSS or JavaScript that may be required for its initial display, so that the user gets the quickest apparent response during the page loading. This content is typically text, and can, therefore, benefit from text compression in transit, thus providing an even quicker response to the user.
Any dynamic features that require the page to complete loading before being used, should be initially disabled, and then only enabled after the page has loaded. This will cause the JavaScript to be loaded after the page contents, which will improve the overall appearance of the page load.
### Reduce the number of inline scripts
Inline scripts can be expensive for page loading since the parser must assume that an inline script could modify the page structure while parsing is in progress. Reducing the use of inline scripts in general, and reducing the use of `document.write()` to output content in particular, can improve overall page loading. Use DOM APIs to manipulate page content, rather than `document.write()`.
### Use modern CSS and valid markup
Use of modern CSS reduces the amount of markup, can reduce the need for (spacer) images, in terms of layout, and can very often replace images of stylized text β that "cost" much more than the equivalent text-and-CSS.
Using valid markup has other advantages. First, browsers will have no need to perform error-correction when parsing the HTML (this is aside from the philosophical issue of whether to allow format variation in user input and then programmatically "correct" or normalize it; or whether, instead, to enforce a strict, no-tolerance input format).
Moreover, valid markup allows for the free use of other tools that can *pre-process* your web pages. For example, HTML Tidy can remove whitespace and optional ending tags; however, it will refuse to run on a page with serious markup errors.
### Chunk your content
Tables for layouts are a legacy method that should not be used anymore. Layouts utilizing floats, positioning, flexbox, or grids should be used instead.
Tables are still considered valid markup but should be used for displaying tabular data. To help the browser render your page quicker, you should avoid nesting your tables.
Rather than deeply nesting tables as in:
```html
<table>
<table>
<table>
β¦
</table>
</table>
</table>
```
use non-nested tables or divs as in
```html
<table>
β¦
</table>
<table>
β¦
</table>
<table>
β¦
</table>
```
See also: CSS Flexible Box Layout and CSS Grid Layout specifications.
### Minify and compress SVG assets
SVG produced by most drawing applications often contains unnecessary metadata which can be removed. Configure your servers, apply gzip compression for SVG assets.
### Minify and compress your images
Large images cause your page to take more time to load. Consider compressing your images before adding them to your page, using compression features built into image-manipulation tools such as Photoshop, or using a specialized tool such as Compress Jpeg or Tiny PNG.
### Specify sizes for images and tables
If the browser can immediately determine the height and/or width of your images and tables, it will be able to display a web page without having to reflow the content. This not only speeds the display of the page but prevents annoying changes in a page's layout when the page completes loading. For this reason, `height` and `width` should be specified for images, whenever possible.
Tables should use the CSS selector: property combination:
```css
table-layout: fixed;
```
and should specify widths of columns using the `<col>` and the `<colgroup>` elements.
### Use lazy loading for images
By default, images are loaded **eagerly**; that is, the image is fetched and rendered as soon as it's processed in the HTML. All eagerly loaded images are rendered before the window's `load` event is sent. Switching to lazy loading of images tells the browser to hold off on loading images until they're about to be needed to draw the visual viewport.
To mark an image for lazy loading, specify its `loading` attribute with a value of `lazy`. With this set, the image will only be loaded when it's needed.
```html
<img src="./images/footerlogo.jpg" loading="lazy" alt="MDN logo" />
```
Note that lazily-loaded images may not be available when the `load` event is fired. You can determine if a given image is loaded by checking to see if the value of its Boolean `complete` property is `true`.
### Choose your user-agent requirements wisely
To achieve the greatest improvements in page design, make sure that reasonable user-agent requirements are specified for projects. Do not require your content to appear pixel-perfect in all browsers, especially not in down-version browsers.
Ideally, your basic minimum requirements should be based on the consideration of modern browsers that support the relevant standards. This can include recent versions of Firefox, Google Chrome, Opera, and Safari.
Note, however, that many of the tips listed in this article are common-sense techniques which apply to any user agent, and can be applied to any web page, regardless of browser-support requirements.
### Use async and defer, if possible
Make the JavaScript scripts such that they are compatible with both the async and the defer attributes, and use async whenever possible, especially if you have multiple script elements.
With that, the page can stop rendering while JavaScript is still loading. Otherwise, the browser will not render anything that is after the script elements that do not have these attributes.
Note: Even though these attributes do help a lot the first time a page is loaded, you should use them but not assume they will work in all browsers. If you already follow all JavaScript best practices, there is no need to change your code.
Example page structure
----------------------
* ``<html>``
+ ``<head>``
- ``<link>``
CSS files required for page appearance. Minimize the number of files for performance while keeping unrelated CSS in separate files for maintenance.
- ``<script>``
JavaScript files for functions **required** during the loading of the page, but not any interaction related JavaScript that can only run after page loads.
Minimize the number of files for performance while keeping unrelated JavaScript in separate files for maintenance.
+ ``<body>``
User visible page content in small chunks (``<header>``/ ``<main>`/` ``<table>``) that can be displayed without waiting for the full page to download.
- ``<script>``
Any scripts which will be used to perform interactivity. Interaction scripts typically can only run after the page has completely loaded and all necessary objects have been initialized. There is no need to load these scripts before the page content. That only slows down the initial appearance of the page load.
Minimize the number of files for performance while keeping unrelated JavaScript in separate files for maintenance.
See also
--------
* Book: "Speed Up Your Site" by Andy King
* The excellent and very complete Best Practices for Speeding Up Your Website (Yahoo!)
* Tools for analyzing and optimizing performance: Google PageSpeed Tools |
Add a hitmap on top of an image - Learn web development | Add a hitmap on top of an image
===============================
Here we go over how to set up an image map, and some downsides to consider first.
Here are some things you need to know| Prerequisites: |
You should already know how to
create a basic HTML document
and how to
add accessible images to a webpage. |
| Objective: |
Learn how to make different regions of one image link to different
pages.
|
**Warning:** This article discusses client-side image maps only. Do not use server-side image maps, which require the user to have a mouse.
Image maps, and their drawbacks
-------------------------------
When you nest an image inside `<a>`, the entire image links to one webpage. An image map, on the other hand, contains several active regions (called "hotspots") that each link to a different resource.
Formerly, image maps were a popular navigation device, but it's important to thoroughly consider their performance and accessibility ramifications.
Text links (perhaps styled with CSS) are preferable to image maps for several reasons: text links are lightweight, maintainable, often more SEO-friendly, and support accessibility needs (e.g., screen readers, text-only browsers, translation services).
How to insert an image map, properly
------------------------------------
### Step 1: The image
Not just any image is acceptable.
* The image must make it clear what happens when people follow image links. `alt` text is mandatory, of course, but many people never see it.
* The image must clearly indicate where hotspots begin and end.
* Hotspots must be large enough to tap comfortably, at any viewport size. How large is large enough? 72 Γ 72 CSS pixels is a good minimum, with additional generous gaps between touch targets. The map of the world at 50languages.com (as of time of writing) illustrates the problem perfectly. It's much easier to tap Russia or North America than Albania or Estonia.
You insert your image much the same way as always (with an `<img>` element and `alt` text). If the image is only present as a navigation device, you may write `alt=""`, provided you furnish appropriate `alt` text in the `<area>` elements later on.
You will need a special `usemap` attribute. Come up with a unique name, containing no spaces, for your image map. Then assign that name (preceded by a hash) as the value for the `usemap` attribute:
```html
<img src="image-map.png" alt="" usemap="#example-map-1" />
```
### Step 2: Activate your hotspots
In this step, put all your code inside a `<map>` element. `<map>` only needs one attribute, the same map `name` as you used in your `usemap` attribute above:
```html
<map name="example-map-1"> </map>
```
Inside the `<map>` element, we need `<area>` elements. An `<area>` element corresponds to a single hotspot. To keep keyboard navigation intuitive, make sure the source order of `<area>` elements corresponds to the visual order of hotspots.
`<area>` elements are void elements, but do require four attributes:
`shape`
`coords`
`shape` takes one of four values: `circle`, `rect`, `poly`, and `default`. (An `<area>` whose `shape` is `default` occupies the entire image, minus any other hotspots you've defined.) The shape you choose determines the coordinate information you'll need to provide in `coords`.
* For a circle, provide the center's x and y coordinates, followed by the length of the radius.
* For a rectangle, provide the x/y coordinates of the upper-left and bottom-right corners.
* For a polygon, to provide the x/y coordinates of each corner (so, at least six values).
Coordinates are given in CSS pixels.
In case of overlap, source order carries the day.
`href`
The URL of the resource you're linking to. You may leave this attribute blank if you *don't* want the current area to link anywhere (say, if you're making a hollow circle.)
`alt`
A mandatory attribute, telling people where the link goes or what it does. `alt` text only displays when the image is unavailable. Please refer to our guidelines for writing accessible link text.
You may write `alt=""` if the `href` attribute is blank *and* the entire image already has an `alt` attribute.
```html
<map name="example-map-1">
<area
shape="circle"
coords="200,250,25"
href="page-2.html"
alt="circle example" />
<area
shape="rect"
coords="10, 5, 20, 15"
href="page-3.html"
alt="rectangle example" />
</map>
```
### Step 3: Make sure it works for everybody
You aren't done until you test image maps rigorously on many browsers and devices. Try following links with your keyboard alone. Try turning images off.
If your image map is wider than about 240px, you'll need to make further adjustments to make your website responsive. It's not enough to resize the image for small screens, because the coordinates stay the same and no longer match the image.
If you must use image maps, you may want to look into Matt Stow's jQuery plugin. Alternatively, Dudley Storey demonstrates a way to use SVG for an image map effect, along with a subsequent combined SVG-raster hack for bitmap images.
Learn more
----------
* `<img>`
* `<map>`
* `<area>`
* Online image map editor |
Define terms with HTML - Learn web development | Define terms with HTML
======================
HTML provides several ways to convey description semantics, whether inline or as structured glossaries. In this article, we'll cover how to properly mark up keywords when you're defining them.
| | |
| --- | --- |
| Prerequisites: |
You need to be familiar with how to
create a basic HTML document.
|
| Objective: | Learn how to introduce new keywords and how to build description lists. |
When you need a term defined, you probably go straight to a dictionary or glossary. Dictionaries and glossaries *formally* associate keywords with one or more descriptions, as in this case:
>
>
> Blue (*Adjective*)
>
>
> Of a color like the sky in a sunny day.
> *"The clear blue sky"*
>
>
>
>
>
>
But we're constantly defining keywords informally, as here:
>
> **Firefox** is the web browser created by the Mozilla Foundation.
>
>
>
To deal with these use cases, HTML provides tags to mark descriptions and words described, so that your meaning gets across properly to your readers.
How to mark informal description
--------------------------------
In textbooks, the first time a keyword occurs, it's common to put the keyword in bold and define it right away.
We do that in HTML too, except HTML is not a visual medium and so we don't use bold. We use `<dfn>`, which is a special element just for marking the first occurrence of keywords. Note that `<dfn>` tags go around the *word to be defined,* not the definition (the definition consists of the entire paragraph):
```html
<p><dfn>Firefox</dfn> is the web browser created by the Mozilla Foundation.</p>
```
**Note:** Another use for bold is to emphasize content. Bold itself is a concept foreign to HTML, but there are tags for indicating emphasis.
### Special case: Abbreviations
It's best to mark abbreviations specially with `<abbr>`, so that screen readers read them appropriately and so that you can operate on all abbreviations uniformly. Just as with any new keyword, you should define your abbreviations the first time they occur.
```html
<p>
<dfn><abbr>HTML</abbr> (hypertext markup language)</dfn>
is a description language used to structure documents on the web.
</p>
```
**Note:** The HTML spec does indeed set aside the `title` attribute for expanding the abbreviation. However, this is not an acceptable alternative for providing an inline expansion. The contents of `title` are completely hidden from your users, unless they're using a mouse and they happen to hover over the abbreviation. The spec duly acknowledges this as well.
### Improve accessibility
`<dfn>` marks the keyword defined, and indicates that the current paragraph defines the keyword. In other words, there's an implicit relationship between the `<dfn>` element and its container. If you want a more formal relationship, or your definition consists of only one sentence rather than the whole paragraph, you can use the `aria-describedby` attribute to associate a term more formally with its definition:
```html
<p>
<span id="ff">
<dfn aria-describedby="ff">Firefox</dfn>
is the web browser created by the Mozilla Foundation.
</span>
You can download it at <a href="https://www.mozilla.org">mozilla.org</a>
</p>
```
Assistive technology can often use this attribute to find a text alternative to a given term. You can use `aria-describedby` on any tag enclosing a keyword to be defined (not just the `<dfn>` element). `aria-describedby` references the `id` of the element containing the description.
How to build a description list
-------------------------------
Description lists are just what they claim to be: a list of terms and their matching descriptions (e.g., definition lists, dictionary entries, FAQs, and key-value pairs).
**Note:** Description lists are not suitable for marking up dialog, because conversation does not directly describe the speakers. Here are recommendations for marking up dialog.
The terms described go inside `<dt>` elements. The matching description follows immediately, contained within one or more `<dd>` elements. Enclose the whole description list with a `<dl>` element.
### A simple example
Here's a simple example describing kinds of food and drink:
```html
<dl>
<dt>jambalaya</dt>
<dd>
rice-based entree typically containing chicken, sausage, seafood, and spices
</dd>
<dt>sukiyaki</dt>
<dd>
Japanese specialty consisting of thinly sliced meat, vegetables, and
noodles, cooked in sake and soy sauce
</dd>
<dt>chianti</dt>
<dd>dry Italian red wine originating in Tuscany</dd>
</dl>
```
**Note:** The basic pattern, as you can see, is to alternate `<dt>` terms with `<dd>` descriptions. If two or more terms occur in a row, the following description applies to all of them. If two or more descriptions occur in a row, they all apply to the last given term.
### Improving the visual output
Here's how a graphical browser displays the foregoing list:
If you want the keywords to stand out better, you could try bolding them. Remember, HTML is not a visual medium; we need CSS for all visual effects. The CSS `font-weight` property is what you need here:
```css
dt {
font-weight: bold;
}
```
This produces the slightly more readable result below:
Learn more
----------
* `<dfn>`
* `<dl>`
* `<dt>`
* `<dd>`
* How to use the aria-describedby attribute |
Use JavaScript within a webpage - Learn web development | Use JavaScript within a webpage
===============================
Take your webpages to the next level by harnessing JavaScript. Learn in this article how to trigger JavaScript right from your HTML documents.
| | |
| --- | --- |
| Prerequisites: |
You need to be familiar with how to
create a basic HTML document.
|
| Objective: |
Learn how to trigger JavaScript in your HTML file, and learn the most
important best practices for keeping JavaScript accessible.
|
About JavaScript
----------------
JavaScript is a programming language mostly used client-side to make webpages interactive. You *can* create amazing webpages without JavaScript, but JavaScript opens up a whole new level of possibilities.
**Note:** In this article we're going over the HTML code you need to make JavaScript take effect. If you want to learn JavaScript itself, you can start with our JavaScript basics article. If you already know something about JavaScript or if you have a background with other programming languages, we suggest you jump directly into our JavaScript Guide.
How to trigger JavaScript from HTML
-----------------------------------
Within a browser, JavaScript doesn't do anything by itself. You run JavaScript from inside your HTML webpages. To call JavaScript code from within HTML, you need the `<script>` element. There are two ways to use `script`, depending on whether you're linking to an external script or embedding a script right in your webpage.
### Linking an external script
Usually, you'll be writing scripts in their own .js files. If you want to execute a .js script from your webpage, just use `<script>` with an `src` attribute pointing to the script file, using its URL:
```html
<script src="path/to/my/script.js"></script>
```
### Writing JavaScript within HTML
You may also add JavaScript code between `<script>` tags rather than providing an `src` attribute.
```html
<script>
window.addEventListener("load", () => {
console.log("This function is executed once the page is fully loaded");
});
</script>
```
That's convenient when you just need a small bit of JavaScript, but if you keep JavaScript in separate files you'll find it easier to
* focus on your work
* write self-sufficient HTML
* write structured JavaScript applications
Use scripting accessibly
------------------------
Accessibility is a major issue in any software development. JavaScript can make your website more accessible if you use it wisely, or it can become a disaster if you use scripting without care. To make JavaScript work in your favor, it's worth knowing about certain best practices for adding JavaScript:
* **Make all content available as (structured) text.** Rely on HTML for your content as much as possible. For example, if you've implemented a nice JavaScript progress bar, make sure to supplement it with matching text percentages inside the HTML. Likewise, your drop-down menus should be structured as unordered lists of links.
* **Make all functionality accessible from the keyboard.**
+ Let users Tab through all controls (e.g., links and form input) in a logical order.
+ If you use pointer events (like mouse events or touch events), duplicate the functionality with keyboard events.
+ Test your site using a keyboard only.
* **Don't set nor even guess time limits.** It takes extra time to navigate with the keyboard or hear content read out. You can hardly ever predict just how long it will take for users or browsers to complete a process (especially asynchronous actions such as loading resources).
* **Keep animations subtle and brief with no flashing.** Flashing is annoying and can cause seizures. Additionally, if an animation lasts more than a couple seconds, give the user a way to cancel it.
* **Let users initiate interactions.** That means, don't update content, redirect, or refresh automatically. Don't use carousels or display popups without warning.
* **Have a plan B for users without JavaScript.** People may have JavaScript turned off to improve speed and security, and users often face network issues that prevent loading scripts. Moreover, third-party scripts (ads, tracking scripts, browser extensions) might break your scripts.
+ At a minimum, leave a short message with `<noscript>` like this: `<noscript>To use this site, please enable JavaScript.</noscript>`
+ Ideally, replicate the JavaScript functionality with HTML and server-side scripting when possible.
+ If you're only looking for simple visual effects, CSS can often get the job done even more intuitively.
+ *Since almost everybody **does** have JavaScript enabled, `<noscript>` is no excuse for writing inaccessible scripts.*
Learn more
----------
* `<script>`
* `<noscript>`
* James Edwards' introduction to using JavaScript accessibly
* Accessibility guidelines from W3C |
Using data attributes - Learn web development | Using data attributes
=====================
HTML is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. `data-*` attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.
HTML syntax
-----------
The syntax is simple. Any attribute on any element whose attribute name starts with `data-` is a data attribute. Say you have an article and you want to store some extra information that doesn't have any visual representation. Just use `data` attributes for that:
```html
<article
id="electric-cars"
data-columns="3"
data-index-number="12314"
data-parent="cars">
β¦
</article>
```
JavaScript access
-----------------
Reading the values of these attributes out in JavaScript is also very simple. You could use `getAttribute()` with their full HTML name to read them, but the standard defines a simpler way: a `DOMStringMap` you can read out via a `dataset` property.
To get a `data` attribute through the `dataset` object, get the property by the part of the attribute name after `data-` (note that dashes are converted to camel case).
```js
const article = document.querySelector("#electric-cars");
// The following would also work:
// const article = document.getElementById("electric-cars")
article.dataset.columns; // "3"
article.dataset.indexNumber; // "12314"
article.dataset.parent; // "cars"
```
Each property is a string and can be read and written. In the above case setting `article.dataset.columns = 5` would change that attribute to `"5"`.
CSS access
----------
Note that, as data attributes are plain HTML attributes, you can even access them from CSS. For example to show the parent data on the article you can use generated content in CSS with the `attr()` function:
```css
article::before {
content: attr(data-parent);
}
```
You can also use the attribute selectors in CSS to change styles according to the data:
```css
article[data-columns="3"] {
width: 400px;
}
article[data-columns="4"] {
width: 600px;
}
```
You can see all this working together in this JSBin example.
Data attributes can also be stored to contain information that is constantly changing, like scores in a game. Using the CSS selectors and JavaScript access here this allows you to build some nifty effects without having to write your own display routines. See this screencast for an example using generated content and CSS transitions (JSBin example).
Data values are strings. Number values must be quoted in the selector for the styling to take effect.
Issues
------
Do not store content that should be visible and accessible in data attributes, because assistive technology may not access them. In addition, search crawlers may not index data attributes' values.
See also
--------
* This article is adapted from Using data attributes in JavaScript and CSS on hacks.mozilla.org.
* Custom attributes are also supported in SVG 2; see `HTMLElement.dataset` and `data-\*` for more information.
* How to use HTML data attributes (Sitepoint) |
HTML table basics - Learn web development | HTML table basics
=================
* Overview: Tables
* Next
This article gets you started with HTML tables, covering the very basics such as rows, cells, headings, making cells span multiple columns and rows, and how to group together all the cells in a column for styling purposes.
| | |
| --- | --- |
| Prerequisites: |
The basics of HTML (see
Introduction to HTML).
|
| Objective: | To gain basic familiarity with HTML tables. |
What is a table?
----------------
A table is a structured set of data made up of rows and columns (**tabular data**). A table allows you to quickly and easily look up values that indicate some kind of connection between different types of data, for example a person and their age, or a day of the week, or the timetable for a local swimming pool.
![A sample table showing names and ages of some people - Chris 38, Dennis 45, Sarah 29, Karen 47.](/en-US/docs/Learn/HTML/Tables/Basics/numbers-table.png)
![A swimming timetable showing a sample data table](/en-US/docs/Learn/HTML/Tables/Basics/swimming-timetable.png)
Tables are very commonly used in human society, and have been for a long time, as evidenced by this US Census document from 1800:
![A very old parchment document; the data is not easily readable, but it clearly shows a data table being used.](/en-US/docs/Learn/HTML/Tables/Basics/1800-census.jpg)
It is therefore no wonder that the creators of HTML provided a means by which to structure and present tabular data on the web.
### How does a table work?
The point of a table is that it is rigid. Information is easily interpreted by making visual associations between row and column headers. Look at the table below for example and find a Jovian gas giant with 62 moons. You can find the answer by associating the relevant row and column headers.
```
<table>
<caption>
Data about the planets of our solar system (Source:
<a href="https://nssdc.gsfc.nasa.gov/planetary/factsheet/"
>Nasa's Planetary Fact Sheet - Metric</a
>).
</caption>
<thead>
<tr>
<td colspan="2"></td>
<th scope="col">Name</th>
<th scope="col">Mass (10<sup>24</sup>kg)</th>
<th scope="col">Diameter (km)</th>
<th scope="col">Density (kg/m<sup>3</sup>)</th>
<th scope="col">Gravity (m/s<sup>2</sup>)</th>
<th scope="col">Length of day (hours)</th>
<th scope="col">Distance from Sun (10<sup>6</sup>km)</th>
<th scope="col">Mean temperature (Β°C)</th>
<th scope="col">Number of moons</th>
<th scope="col">Notes</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="2" rowspan="4" scope="rowgroup">Terrestrial planets</th>
<th scope="row">Mercury</th>
<td>0.330</td>
<td>4,879</td>
<td>5427</td>
<td>3.7</td>
<td>4222.6</td>
<td>57.9</td>
<td>167</td>
<td>0</td>
<td>Closest to the Sun</td>
</tr>
<tr>
<th scope="row">Venus</th>
<td>4.87</td>
<td>12,104</td>
<td>5243</td>
<td>8.9</td>
<td>2802.0</td>
<td>108.2</td>
<td>464</td>
<td>0</td>
<td></td>
</tr>
<tr>
<th scope="row">Earth</th>
<td>5.97</td>
<td>12,756</td>
<td>5514</td>
<td>9.8</td>
<td>24.0</td>
<td>149.6</td>
<td>15</td>
<td>1</td>
<td>Our world</td>
</tr>
<tr>
<th scope="row">Mars</th>
<td>0.642</td>
<td>6,792</td>
<td>3933</td>
<td>3.7</td>
<td>24.7</td>
<td>227.9</td>
<td>-65</td>
<td>2</td>
<td>The red planet</td>
</tr>
<tr>
<th rowspan="4" scope="rowgroup">Jovian planets</th>
<th rowspan="2" scope="rowgroup">Gas giants</th>
<th scope="row">Jupiter</th>
<td>1898</td>
<td>142,984</td>
<td>1326</td>
<td>23.1</td>
<td>9.9</td>
<td>778.6</td>
<td>-110</td>
<td>67</td>
<td>The largest planet</td>
</tr>
<tr>
<th scope="row">Saturn</th>
<td>568</td>
<td>120,536</td>
<td>687</td>
<td>9.0</td>
<td>10.7</td>
<td>1433.5</td>
<td>-140</td>
<td>62</td>
<td></td>
</tr>
<tr>
<th rowspan="2" scope="rowgroup">Ice giants</th>
<th scope="row">Uranus</th>
<td>86.8</td>
<td>51,118</td>
<td>1271</td>
<td>8.7</td>
<td>17.2</td>
<td>2872.5</td>
<td>-195</td>
<td>27</td>
<td></td>
</tr>
<tr>
<th scope="row">Neptune</th>
<td>102</td>
<td>49,528</td>
<td>1638</td>
<td>11.0</td>
<td>16.1</td>
<td>4495.1</td>
<td>-200</td>
<td>14</td>
<td></td>
</tr>
<tr>
<th colspan="2" scope="rowgroup">Dwarf planets</th>
<th scope="row">Pluto</th>
<td>0.0146</td>
<td>2,370</td>
<td>2095</td>
<td>0.7</td>
<td>153.3</td>
<td>5906.4</td>
<td>-225</td>
<td>5</td>
<td>
Declassified as a planet in 2006, but this
<a
href="https://www.usatoday.com/story/tech/2014/10/02/pluto-planet-solar-system/16578959/"
>remains controversial</a
>.
</td>
</tr>
</tbody>
</table>
```
```
table {
border-collapse: collapse;
border: 2px solid black;
}
th,
td {
padding: 5px;
border: 1px solid black;
}
```
When implemented correctly, HTML tables are handled well by accessibility tools such as screen readers, so a successful HTML table should enhance the experience of sighted and visually impaired users alike.
### Table styling
You can also have a look at the live example on GitHub! One thing you'll notice is that the table does look a bit more readable there β this is because the table you see above on this page has minimal styling, whereas the GitHub version has more significant CSS applied.
Be under no illusion; for tables to be effective on the web, you need to provide some styling information with CSS, as well as good solid structure with HTML. In this module we are focusing on the HTML part; to find out about the CSS part you should visit our Styling tables article after you've finished here.
We won't focus on CSS in this module, but we have provided a minimal CSS stylesheet for you to use that will make your tables more readable than the default you get without any styling. You can find the stylesheet here, and you can also find an HTML template that applies the stylesheet β these together will give you a good starting point for experimenting with HTML tables.
### When should you NOT use HTML tables?
HTML tables should be used for tabular data β this is what they are designed for. Unfortunately, a lot of people used to use HTML tables to lay out web pages, e.g. one row to contain the header, one row to contain the content columns, one row to contain the footer, etc. You can find more details and an example at Page Layouts in our Accessibility Learning Module. This was commonly used because CSS support across browsers used to be terrible; table layouts are much less common nowadays, but you might still see them in some corners of the web.
In short, using tables for layout rather than CSS layout techniques is a bad idea. The main reasons are as follows:
1. **Layout tables reduce accessibility for visually impaired users**: screen readers, used by blind people, interpret the tags that exist in an HTML page and read out the contents to the user. Because tables are not the right tool for layout, and the markup is more complex than with CSS layout techniques, the screen readers' output will be confusing to their users.
2. **Tables produce tag soup**: As mentioned above, table layouts generally involve more complex markup structures than proper layout techniques. This can result in the code being harder to write, maintain, and debug.
3. **Tables are not automatically responsive**: When you use proper layout containers (such as `<header>`, `<section>`, `<article>`, or `<div>`), their width defaults to 100% of their parent element. Tables on the other hand are sized according to their content by default, so extra measures are needed to get table layout styling to effectively work across a variety of devices.
Active learning: Creating your first table
------------------------------------------
We've talked table theory enough, so, let's dive into a practical example and build up a simple table.
1. First of all, make a local copy of blank-template.html and minimal-table.css in a new directory on your local machine.
2. The content of every table is enclosed by these two tags: **`<table></table>`**. Add these inside the body of your HTML.
3. The smallest container inside a table is a table cell, which is created by a **`<td>`** element ('td' stands for 'table data'). Add the following inside your table tags:
```html
<td>Hi, I'm your first cell.</td>
```
4. If we want a row of four cells, we need to copy these tags three times. Update the contents of your table to look like so:
```html
<td>Hi, I'm your first cell.</td>
<td>I'm your second cell.</td>
<td>I'm your third cell.</td>
<td>I'm your fourth cell.</td>
```
As you will see, the cells are not placed underneath each other, rather they are automatically aligned with each other on the same row. Each `<td>` element creates a single cell and together they make up the first row. Every cell we add makes the row grow longer.
To stop this row from growing and start placing subsequent cells on a second row, we need to use the **`<tr>`** element ('tr' stands for 'table row'). Let's investigate this now.
1. Place the four cells you've already created inside `<tr>` tags, like so:
```html
<tr>
<td>Hi, I'm your first cell.</td>
<td>I'm your second cell.</td>
<td>I'm your third cell.</td>
<td>I'm your fourth cell.</td>
</tr>
```
2. Now you've made one row, have a go at making one or two more β each row needs to be wrapped in an additional `<tr>` element, with each cell contained in a `<td>`.
### Result
This should result in a table that looks something like the following:
```
<table>
<tr>
<td>Hi, I'm your first cell.</td>
<td>I'm your second cell.</td>
<td>I'm your third cell.</td>
<td>I'm your fourth cell.</td>
</tr>
<tr>
<td>Second row, first cell.</td>
<td>Cell 2.</td>
<td>Cell 3.</td>
<td>Cell 4.</td>
</tr>
</table>
```
```
table {
border-collapse: collapse;
}
td,
th {
border: 1px solid black;
padding: 10px 20px;
}
```
**Note:** You can also find this on GitHub as simple-table.html (see it live also).
Adding headers with <th> elements
---------------------------------
Now let's turn our attention to table headers β special cells that go at the start of a row or column and define the type of data that row or column contains (as an example, see the "Person" and "Age" cells in the first example shown in this article). To illustrate why they are useful, have a look at the following table example. First the source code:
```html
<table>
<tr>
<td> </td>
<td>Knocky</td>
<td>Flor</td>
<td>Ella</td>
<td>Juan</td>
</tr>
<tr>
<td>Breed</td>
<td>Jack Russell</td>
<td>Poodle</td>
<td>Streetdog</td>
<td>Cocker Spaniel</td>
</tr>
<tr>
<td>Age</td>
<td>16</td>
<td>9</td>
<td>10</td>
<td>5</td>
</tr>
<tr>
<td>Owner</td>
<td>Mother-in-law</td>
<td>Me</td>
<td>Me</td>
<td>Sister-in-law</td>
</tr>
<tr>
<td>Eating Habits</td>
<td>Eats everyone's leftovers</td>
<td>Nibbles at food</td>
<td>Hearty eater</td>
<td>Will eat till he explodes</td>
</tr>
</table>
```
```
table {
border-collapse: collapse;
}
td,
th {
border: 1px solid black;
padding: 10px 20px;
}
```
Now the actual rendered table:
The problem here is that, while you can kind of make out what's going on, it is not as easy to cross reference data as it could be. If the column and row headings stood out in some way, it would be much better.
### Active learning: table headers
Let's have a go at improving this table.
1. First, make a local copy of our dogs-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same Dogs example as you saw above.
2. To recognize the table headers as headers, both visually and semantically, you can use the **`<th>`** element ('th' stands for 'table header'). This works in exactly the same way as a `<td>`, except that it denotes a header, not a normal cell. Go into your HTML, and change all the `<td>` elements surrounding the table headers into `<th>` elements.
3. Save your HTML and load it in a browser, and you should see that the headers now look like headers.
**Note:** You can find our finished example at dogs-table-fixed.html on GitHub (see it live also).
### Why are headers useful?
We have already partially answered this question β it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better.
**Note:** Table headings come with some default styling β they are bold and centered even if you don't add your own styling to the table, to help them stand out.
Tables headers also have an added benefit β along with the `scope` attribute (which we'll learn about in the next article), they allow you to make tables more accessible by associating each header with all the data in the same row or column. Screen readers are then able to read out a whole row or column of data at once, which is pretty useful.
Allowing cells to span multiple rows and columns
------------------------------------------------
Sometimes we want cells to span multiple rows or columns. Take the following simple example, which shows the names of common animals. In some cases, we want to show the names of the males and females next to the animal name. Sometimes we don't, and in such cases we just want the animal name to span the whole table.
The initial markup looks like this:
```html
<table>
<tr>
<th>Animals</th>
</tr>
<tr>
<th>Hippopotamus</th>
</tr>
<tr>
<th>Horse</th>
<td>Mare</td>
</tr>
<tr>
<td>Stallion</td>
</tr>
<tr>
<th>Crocodile</th>
</tr>
<tr>
<th>Chicken</th>
<td>Hen</td>
</tr>
<tr>
<td>Rooster</td>
</tr>
</table>
```
```
table {
border-collapse: collapse;
}
td,
th {
border: 1px solid black;
padding: 10px 20px;
}
```
But the output doesn't give us quite what we want:
We need a way to get "Animals", "Hippopotamus", and "Crocodile" to span across two columns, and "Horse" and "Chicken" to span downwards over two rows. Fortunately, table headers and cells have the `colspan` and `rowspan` attributes, which allow us to do just those things. Both accept a unitless number value, which equals the number of rows or columns you want spanned. For example, `colspan="2"` makes a cell span two columns.
Let's use `colspan` and `rowspan` to improve this table.
1. First, make a local copy of our animals-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same animals example as you saw above.
2. Next, use `colspan` to make "Animals", "Hippopotamus", and "Crocodile" span across two columns.
3. Finally, use `rowspan` to make "Horse" and "Chicken" span across two rows.
4. Save and open your code in a browser to see the improvement.
**Note:** You can find our finished example at animals-table-fixed.html on GitHub (see it live also).
Providing common styling to columns
-----------------------------------
### Styling without <col>
There is one last feature we'll tell you about in this article before we move on. HTML has a method of defining styling information for an entire column of data all in one place β the **`<col>`** and **`<colgroup>`** elements. These exist because it can be a bit annoying and inefficient having to specify styling on columns β you generally have to specify your styling information on *every* `<td>` or `<th>` in the column, or use a complex selector such as `:nth-child`.
**Note:** Styling columns like this is limited to a few properties: `border`, `background`, `width`, and `visibility`. To set other properties you'll have to either style every `<td>` or `<th>` in the column, or use a complex selector such as `:nth-child`.
Take the following simple example:
```html
<table>
<tr>
<th>Data 1</th>
<th style="background-color: yellow">Data 2</th>
</tr>
<tr>
<td>Calcutta</td>
<td style="background-color: yellow">Orange</td>
</tr>
<tr>
<td>Robots</td>
<td style="background-color: yellow">Jazz</td>
</tr>
</table>
```
```
table {
border-collapse: collapse;
}
td,
th {
border: 1px solid black;
padding: 10px 20px;
}
```
Which gives us the following result:
This isn't ideal, as we have to repeat the styling information across all three cells in the column (we'd probably have a `class` set on all three in a real project and specify the styling in a separate stylesheet).
### Styling with <col>
Instead of doing this, we can specify the information once, on a `<col>` element. `<col>` elements are specified inside a `<colgroup>` container just below the opening `<table>` tag. We could create the same effect as we see above by specifying our table as follows:
```html
<table>
<colgroup>
<col />
<col style="background-color: yellow" />
</colgroup>
<tr>
<th>Data 1</th>
<th>Data 2</th>
</tr>
<tr>
<td>Calcutta</td>
<td>Orange</td>
</tr>
<tr>
<td>Robots</td>
<td>Jazz</td>
</tr>
</table>
```
Effectively we are defining two "style columns", one specifying styling information for each column. We are not styling the first column, but we still have to include a blank `<col>` element β if we didn't, the styling would just be applied to the first column.
If we wanted to apply the styling information to both columns, we could just include one `<col>` element with a span attribute on it, like this:
```html
<colgroup>
<col style="background-color: yellow" span="2" />
</colgroup>
```
Just like `colspan` and `rowspan`, `span` takes a unitless number value that specifies the number of columns you want the styling to apply to.
**Note:** When the table, a column, and table cells in that column are all styled separately then styles applied to the cells are painted on top of column styles which are painted on top of the table. This is because the table layer is rendered first, then the columns' layer is rendered, with the cells' layer rendered on top of all the other table layers.
### Active learning: colgroup and col
Now it's time to have a go yourself.
Below you can see the timetable of a languages teacher. On Friday she has a new class teaching Dutch all day, but she also teaches German for a few periods on Tuesday and Thursdays. She wants to highlight the columns containing the days she is teaching.
Recreate the table by following the steps below.
1. First, make a local copy of our timetable.html file in a new directory on your local machine. The HTML contains the same table you saw above, minus the column styling information.
2. Add a `<colgroup>` element at the top of the table, just underneath the `<table>` tag, in which you can add your `<col>` elements (see the remaining steps below).
3. The first two columns need to be left unstyled.
4. Add a background color to the third column. The value for your `style` attribute is `background-color:#97DB9A;`
5. Set a separate width on the fourth column. The value for your `style` attribute is `width: 42px;`
6. Add a background color to the fifth column. The value for your `style` attribute is `background-color: #97DB9A;`
7. Add a different background color plus a border to the sixth column, to signify that this is a special day and she's teaching a new class. The values for your `style` attribute are `background-color:#DCC48E; border:4px solid #C1437A;`
8. The last two days are free days, so just set them to no background color but a set width; the value for the `style` attribute is `width: 42px;`
See how you get on with the example. If you get stuck, or want to check your work, you can find our version on GitHub as timetable-fixed.html (see it live also).
Summary
-------
That just about wraps up the basics of HTML tables. In the next article, we'll look at some slightly more advanced table features, and start to think how accessible they are for visually impaired people.
* Overview: Tables
* Next |
Structuring planet data - Learn web development | Structuring planet data
=======================
* Previous
* Overview: Tables
In our table assessment, we provide you with some data on the planets in our solar system, and get you to structure it into an HTML table.
| | |
| --- | --- |
| Prerequisites: |
Before attempting this assessment you should have already worked through
all the articles in this module.
|
| Objective: | To test comprehension of HTML tables and associated features. |
Starting point
--------------
To start the assessment, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a new directory in your local computer.
**Note:** You can try solutions in your code editor or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Project brief
-------------
You are working at a school; currently your students are studying the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. An HTML data table would be ideal β you need to take the raw data you have available and turn it into a table, following the steps below.
### Steps to complete
The following steps describe what you need to do to complete the table example. All the data you'll need is contained in the `planets-data.txt` file. If you have trouble visualizing the data, look at the live example below, or try drawing a diagram.
1. Open your copy of `blank-template.html`, and start the table off by giving it an outer container, a table header, and a table body. You don't need a table footer for this example.
2. Add the provided caption to your table.
3. Add a row to the table header containing all the column headers.
4. Create all the content rows inside the table body, remembering to make all the row headings into headings semantically.
5. Ensure all the content is placed into the right cells β in the raw data, each row of planet data is shown next to its associated planet.
6. Add attributes to make the row and column headers unambiguously associated with the rows, columns, or rowgroups that they act as headings for.
7. Add a black border just around the column that contains all the planet name row headers.
Hints and tips
--------------
* The first cell of the header row needs to be blank, and span two columns.
* The group row headings (e.g. *Jovian planets*) that sit to the left of the planet name row headings (e.g. *Saturn*) are a little tricky to sort out β you need to make sure each one spans the correct number of rows and columns.
* One way of associating headers with their rows/columns is a lot easier than the other way.
Example
-------
The finished table should look like this:
![Complex table has a caption above it. The top row cells are column headers. There are three columns of headers. The first two columns have merged cells, with the third column being individual headers for each row. All the text is centered. The headers and every other row have a slight background color.](/en-US/docs/Learn/HTML/Tables/Structuring_planet_data/assessment-table.png)
You can also see the example live here (no looking at the source code β don't cheat!)
* Previous
* Overview: Tables |
HTML table advanced features and accessibility - Learn web development | HTML table advanced features and accessibility
==============================================
* Previous
* Overview: Tables
* Next
In the second article in this module, we look at some more advanced features of HTML tables β such as captions/summaries and grouping your rows into table head, body and footer sections β as well as looking at the accessibility of tables for visually impaired users.
| | |
| --- | --- |
| Prerequisites: |
The basics of HTML (see
Introduction to HTML).
|
| Objective: |
To learn about more advanced HTML table features, and the accessibility
of tables.
|
Adding a caption to your table with <caption>
---------------------------------------------
You can give your table a caption by putting it inside a `<caption>` element and nesting that inside the `<table>` element. You should put it just below the opening `<table>` tag.
```html
<table>
<caption>
Dinosaurs in the Jurassic period
</caption>
β¦
</table>
```
As you can infer from the brief example above, the caption is meant to contain a description of the table contents. This is useful for all readers wishing to get a quick idea of whether the table is useful to them as they scan the page, but particularly for blind users. Rather than have a screen reader read out the contents of many cells just to find out what the table is about, the user can rely on a caption and then decide whether or not to read the table in greater detail.
A caption is placed directly beneath the `<table>` tag.
**Note:** The `summary` attribute can also be used on the `<table>` element to provide a description β this is also read out by screen readers. We'd recommend using the `<caption>` element instead, however, as `summary` is deprecated and can't be read by sighted users (it doesn't appear on the page).
### Active learning: Adding a caption
Let's try this out, revisiting an example we first met in the previous article.
1. Open up your language teacher's school timetable from the end of HTML Table Basics, or make a local copy of our timetable-fixed.html file.
2. Add a suitable caption for the table.
3. Save your code and open it in a browser to see what it looks like.
**Note:** You can find our version on GitHub β see timetable-caption.html (see it live also).
Adding structure with <thead>, <tfoot>, and <tbody>
---------------------------------------------------
As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear way to do this is by using `<thead>`, `<tfoot>`, and `<tbody>`, which allow you to mark up a header, footer, and body section for the table.
These elements don't make the table any more accessible to screen reader users, and don't result in any visual enhancement on their own. They are however very useful for styling and layout β acting as useful hooks for adding CSS to your table. To give you some interesting examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table body display on a single page and have the contents available by scrolling up and down.
To use them:
* The `<thead>` element must wrap the part of the table that is the header β this is usually the first row containing the column headings, but this is not necessarily always the case. If you are using `<col>`/`<colgroup>` element, the table header should come just below those.
* The `<tfoot>` element needs to wrap the part of the table that is the footer β this might be a final row with items in the previous rows summed, for example. You can include the table footer right at the bottom of the table as you'd expect, or just below the table header (the browser will still render it at the bottom of the table).
* The `<tbody>` element needs to wrap the other parts of the table content that aren't in the table header or footer. It will appear below the table header or sometimes footer, depending on how you decided to structure it.
**Note:** `<tbody>` is always included in every table, implicitly if you don't specify it in your code. To check this, open up one of your previous examples that doesn't include `<tbody>` and look at the HTML code in your browser developer tools β you will see that the browser has added this tag for you. You might wonder why you ought to bother including it at all β you should, because it gives you more control over your table structure and styling.
### Active learning: Adding table structure
Let's put these new elements into action.
1. First of all, make a local copy of spending-record.html and minimal-table.css in a new folder.
2. Try opening it in a browser β You'll see that it looks OK, but it could stand to be improved. The "SUM" row that contains a summation of the spent amounts seems to be in the wrong place, and there are some details missing from the code.
3. Put the obvious headers row inside a `<thead>` element, the "SUM" row inside a `<tfoot>` element, and the rest of the content inside a `<tbody>` element.
4. Save and refresh, and you'll see that adding the `<tfoot>` element has caused the "SUM" row to go down to the bottom of the table.
5. Next, add a `colspan` attribute to make the "SUM" cell span across the first four columns, so the actual number appears at the bottom of the "Cost" column.
6. Let's add some simple extra styling to the table, to give you an idea of how useful these elements are for applying CSS. Inside the head of your HTML document, you'll see an empty `<style>` element. Inside this element, add the following lines of CSS code:
```css
tbody {
font-size: 95%;
font-style: italic;
}
tfoot {
font-weight: bold;
}
```
7. Save and refresh, and have a look at the result. If the `<tbody>` and `<tfoot>` elements weren't in place, you'd have to write much more complicated selectors/rules to apply the same styling.
**Note:** We don't expect you to fully understand the CSS right now. You'll learn more about this when you go through our CSS modules (Introduction to CSS is a good place to start; we also have an article specifically on styling tables).
Your finished table should look something like the following:
**Note:** You can also find it on GitHub as spending-record-finished.html.
Nesting Tables
--------------
It is possible to nest a table inside another one, as long as you include the complete structure, including the `<table>` element. This is generally not really advised, as it makes the markup more confusing and less accessible to screen reader users, and in many cases you might as well just insert extra cells/rows/columns into the existing table. It is however sometimes necessary, for example if you want to import content easily from other sources.
The following markup shows a simple nested table:
```html
<table id="table1">
<tr>
<th>title1</th>
<th>title2</th>
<th>title3</th>
</tr>
<tr>
<td id="nested">
<table id="table2">
<tr>
<td>cell1</td>
<td>cell2</td>
<td>cell3</td>
</tr>
</table>
</td>
<td>cell2</td>
<td>cell3</td>
</tr>
<tr>
<td>cell4</td>
<td>cell5</td>
<td>cell6</td>
</tr>
</table>
```
The output of which looks something like this:
```
table {
border-collapse: collapse;
}
td,
th {
border: 1px solid black;
padding: 10px 20px;
}
```
Tables for visually impaired users
----------------------------------
Let's recap briefly on how we use data tables. A table can be a handy tool, for giving us quick access to data and allowing us to look up different values. For example, it takes only a short glance at the table below to find out how many rings were sold in Gent during August 2016. To understand its information we make visual associations between the data in this table and its column and/or row headers.
Items Sold August 2016| | Clothes | Accessories |
| Trousers | Skirts | Dresses | Bracelets | Rings |
| Belgium | Antwerp | 56 | 22 | 43 | 72 | 23 |
| Gent | 46 | 18 | 50 | 61 | 15 |
| Brussels | 51 | 27 | 38 | 69 | 28 |
| The Netherlands | Amsterdam | 89 | 34 | 69 | 85 | 38 |
| Utrecht | 80 | 12 | 43 | 36 | 19 |
But what if you cannot make those visual associations? How then can you read a table like the above? Visually impaired people often use a screen reader that reads out information on web pages to them. This is no problem when you're reading plain text but interpreting a table can be quite a challenge for a blind person. Nevertheless, with the proper markup we can replace visual associations by programmatic ones.
**Note:** There are around 253 Million people living with Visual Impairment according to WHO data in 2017.
This section of the article provides further techniques for making tables as accessible as possible.
### Using column and row headers
Screen readers will identify all headers and use them to make programmatic associations between those headers and the cells they relate to. The combination of column and row headers will identify and interpret the data in each cell so that screen reader users can interpret the table similarly to how a sighted user does.
We already covered headers in our previous article β see Adding headers with <th> elements.
### The scope attribute
A new topic for this article is the `scope` attribute, which can be added to the `<th>` element to tell screen readers exactly what cells the header is a header for β is it a header for the row it is in, or the column, for example? Looking back to our spending record example from earlier on, you could unambiguously define the column headers as column headers like this:
```html
<thead>
<tr>
<th scope="col">Purchase</th>
<th scope="col">Location</th>
<th scope="col">Date</th>
<th scope="col">Evaluation</th>
<th scope="col">Cost (β¬)</th>
</tr>
</thead>
```
And each row could have a header defined like this (if we added row headers as well as column headers):
```html
<tr>
<th scope="row">Haircut</th>
<td>Hairdresser</td>
<td>12/09</td>
<td>Great idea</td>
<td>30</td>
</tr>
```
screen readers will recognize markup structured like this, and allow their users to read out the entire column or row at once, for example.
`scope` has two more possible values β `colgroup` and `rowgroup`. These are used for headings that sit over the top of multiple columns or rows. If you look back at the "Items Sold August 2016" table at the start of this section of the article, you'll see that the "Clothes" cell sits above the "Trousers", "Skirts", and "Dresses" cells. All of these cells should be marked up as headers (`<th>`), but "Clothes" is a heading that sits over the top and defines the other three subheadings. "Clothes" therefore should get an attribute of `scope="colgroup"`, whereas the others would get an attribute of `scope="col"`.
### The id and headers attributes
An alternative to using the `scope` attribute is to use `id` and `headers` attributes to create associations between headers and cells. The way they are used is as follows:
1. You add a unique `id` to each `<th>` element.
2. You add a `headers` attribute to each `<td>` element. Each `headers` attribute has to contain a list of the `id`s of all the `<th>` elements that act as a header for that cell, separated by spaces.
This gives your HTML table an explicit definition of the position of each cell in the table, defined by the header(s) for each column and row it is part of, kind of like a spreadsheet. For it to work well, the table really needs both column and row headers.
Returning to our spending costs example, the previous two snippets could be rewritten like this:
```html
<thead>
<tr>
<th id="purchase">Purchase</th>
<th id="location">Location</th>
<th id="date">Date</th>
<th id="evaluation">Evaluation</th>
<th id="cost">Cost (β¬)</th>
</tr>
</thead>
<tbody>
<tr>
<th id="haircut">Haircut</th>
<td headers="location haircut">Hairdresser</td>
<td headers="date haircut">12/09</td>
<td headers="evaluation haircut">Great idea</td>
<td headers="cost haircut">30</td>
</tr>
β¦
</tbody>
```
**Note:** This method creates very precise associations between headers and data cells but it uses **a lot** more markup and does not leave any room for errors. The `scope` approach is usually enough for most tables.
### Active learning: playing with scope and headers
1. For this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory.
2. Now try adding in the appropriate `scope` attributes to make this table more appropriate.
3. Finally, try making another copy of the starter files, and this time make the table more accessible using `id` and `headers` attributes.
**Note:** You can check your work against our finished examples β see items-sold-scope.html (also see this live) and items-sold-headers.html (see this live too).
Summary
-------
There are a few other things you could learn about tables in HTML, but this is all you need to know for now. Next, you can test yourself with our HTML tables assessment. Have fun!
If you are already learning CSS and have done well on the assessment, you can move on and learn about styling HTML tables β see Styling tables.
If you want to get started with learning CSS, check out the CSS Learning Area!
* Previous
* Overview: Tables
* Next |
Marking up a letter - Learn web development | Marking up a letter
===================
* Previous
* Overview: Introduction to HTML
* Next
We all learn to write a letter sooner or later; it is also a useful example to test our text formatting skills. In this assignment, you'll have a letter to mark up as a test for your HTML text formatting skills, as well as hyperlinks and proper use of the HTML `<head>` element.
| | |
| --- | --- |
| Prerequisites: |
Before attempting this assessment you should have already worked through
Getting started with HTML,
What's in the head? Metadata in HTML,
HTML text fundamentals,
Creating hyperlinks, and
Advanced text formatting.
|
| Objective: |
Test basic and advanced HTML text formatting, use of hyperlinks, and use
of HTML <head>.
|
Starting point
--------------
To begin, get the raw text you need to mark up, and the CSS to style the HTML.
Create a new `.html` file using your text editor or use an online editor such as CodePen, JSFiddle, or Glitch.
**Note:** If you get stuck, you can reach out to us in one of our communication channels.
Project brief
-------------
For this project, your task is to mark up a letter that needs to be hosted on a university intranet. The letter is a response from a research fellow to a prospective PhD student concerning their application to the university.
### Block/structural semantics
* Use appropriate document structure including doctype, and `<html>`, `<head>` and `<body>` elements.
* In general, the letter should be marked up as an organization of headings and paragraphs, with the following exception. There is one top level heading (the "Re:" line) and three second level headings.
* Use an appropriate list type to mark up the semester start dates, study subjects, and exotic dances.
* Put the two addresses inside `<address>` elements. Each line of the address should sit on a new line, but not be in a new paragraph.
### Inline semantics
* The names of the sender and receiver (and *Tel* and *Email*) should be marked up with strong importance.
* The four dates in the document should have appropriate elements containing machine-readable dates.
* The first address and first date in the letter should have a class attribute value of *sender-column*. The CSS you'll add later will cause these to be right aligned, as it should be in the case in a classic letter layout.
* Mark up the following five acronyms/abbreviations in the main text of the letter β "PhD," "HTML," "CSS," "BC," and "Esq." β to provide expansions of each one.
* The six sub/superscripts should be marked up appropriately β in the chemical formulae, and the numbers 103 and 104 (they should be 10 to the power of 3 and 4, respectively).
* Try to mark up at least two appropriate words in the text with strong importance/emphasis.
* There are two places where the letter should have a hyperlink. Add appropriate links with titles. For the location that the links point to, you may use `http://example.com` as the URL.
* Mark up the university motto quote and citation with appropriate elements.
### The head of the document
* The character set of the document should be set as utf-8 using the appropriate meta tag.
* The author of the letter should be specified in an appropriate meta tag.
* The provided CSS should be included inside an appropriate tag.
Hints and tips
--------------
* Use the W3C HTML validator to validate your HTML. Award yourself bonus points if it validates.
* You don't need to know any CSS to do this assignment. You just need to put the provided CSS inside an HTML element.
Example
-------
The following screenshot shows an example of what the letter might look like after being marked up.
![Example](/en-US/docs/Learn/HTML/Introduction_to_HTML/Marking_up_a_letter/letter-update.png)
* Previous
* Overview: Introduction to HTML
* Next |
Debugging HTML - Learn web development | Debugging HTML
==============
* Previous
* Overview: Introduction to HTML
* Next
Writing HTML is fine, but what if something goes wrong, and you can't work out where the error in the code is? This article will introduce you to some tools that can help you find and fix errors in HTML.
| | |
| --- | --- |
| Prerequisites: |
HTML familiarity, as covered in, for example, Getting started with HTML,
HTML text fundamentals, and
Creating hyperlinks.
|
| Objective: | Learn the basics of using debugging tools to find problems in HTML. |
Debugging isn't scary
---------------------
When writing code of some kind, everything is usually fine, until that dreaded moment when an error occurs β you've done something wrong, so your code doesn't work β either not at all, or not quite how you wanted it to. For example, the following shows an error reported when trying to compile a simple program written in the Rust language.
![A console window showing the result of trying to compile a rust program with a missing quote around a string in a print statement. The error message reported is error: unterminated double quote string.](/en-US/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML/error-message.png)Here, the error message is relatively easy to understand β "unterminated double quote string". If you look at the listing, you can probably see how `println!(Hello, world!");` might logically be missing a double quote. However, error messages can quickly get more complicated and less easy to interpret as programs get bigger, and even simple cases can look a little intimidating to someone who doesn't know anything about Rust.
Debugging doesn't have to be scary though β the key to being comfortable with writing and debugging any programming language or code is familiarity with both the language and the tools.
HTML and debugging
------------------
HTML is not as complicated to understand as Rust. HTML is not compiled into a different form before the browser parses it and shows the result (it is *interpreted*, not *compiled*). And HTML's element syntax is arguably a lot easier to understand than a "real programming language" like Rust, JavaScript, or Python. The way that browsers parse HTML is a lot more **permissive** than how programming languages are run, which is both a good and a bad thing.
### Permissive code
So what do we mean by permissive? Well, generally when you do something wrong in code, there are two main types of error that you'll come across:
* **Syntax errors**: These are spelling or punctuation errors in your code that actually cause the program not to run, like the Rust error shown above. These are usually easy to fix as long as you are familiar with the language's syntax 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 the program runs incorrectly. These are often harder to fix than syntax errors, as there isn't an error message to direct you to the source of the error.
HTML itself doesn't suffer from syntax errors because browsers parse it permissively, meaning that the page still displays even if there are syntax errors. Browsers have built-in rules to state how to interpret incorrectly written markup, so you'll get something running, even if it is not what you expected. This, of course, can still be a problem!
**Note:** HTML is parsed permissively because when the web was first created, it was decided that allowing people to get their content published was more important than making sure the syntax was absolutely correct. The web would probably not be as popular as it is today, if it had been more strict from the very beginning.
### Active learning: Studying permissive code
It's time to study the permissive nature of HTML code.
1. First, download our debug-example demo and save it locally. This demo is deliberately written with some built-in errors for us to explore (the HTML markup is said to be **badly-formed**, as opposed to **well-formed**).
2. Next, open it in a browser. You will see something like this:
![A simple HTML document with a title of HTML debugging examples, and some information about common HTML errors, such as unclosed elements, badly nested elements, and unclosed attributes. ](/en-US/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML/badly-formed-html.png)
3. This immediately doesn't look great; let's look at the source code to see if we can work out why (only the body contents are shown):
```html
<h1>HTML debugging examples</h1>
<p>What causes errors in HTML?
<ul>
<li>Unclosed elements: If an element is <strong>not closed properly,
then its effect can spread to areas you didn't intend
<li>Badly nested elements: Nesting elements properly is also very important
for code behaving correctly. <strong>strong <em>strong emphasized?</strong>
what is this?</em>
<li>Unclosed attributes: Another common source of HTML problems. Let's
look at an example: <a href="https://www.mozilla.org/>link to Mozilla
homepage</a>
</ul>
```
4. Let's review the problems:
* The paragraph and list item elements have no closing tags. Looking at the image above, this doesn't seem to have affected the markup rendering too badly, as it is easy to infer where one element should end and another should begin.
* The first `<strong>` element has no closing tag. This is a bit more problematic, as it isn't easy to tell where the element is supposed to end. In fact, the whole of the rest of the text has been strongly emphasized.
* This section is badly nested: `<strong>strong <em>strong emphasized?</strong> what is this?</em>`. It is not easy to tell how this has been interpreted because of the previous problem.
* The `href` attribute value is missing a closing double quote. This seems to have caused the biggest problem β the link has not rendered at all.
5. Now let's look at the markup the browser has rendered, as opposed to the markup in the source code. To do this, we can use the browser developer tools. If you are not familiar with how to use your browser's developer tools, take a few minutes to review Discover browser developer tools.
6. In the DOM inspector, you can see what the rendered markup looks like:
![The HTML inspector in Firefox, with our example's paragraph highlighted, showing the text "What causes errors in HTML?" Here you can see that the paragraph element has been closed by the browser.](/en-US/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML/html-inspector.png)
7. Using the DOM inspector, let's explore our code in detail to see how the browser has tried to fix our HTML errors (we did the review in Firefox; other modern browsers *should* give the same result):
* The paragraphs and list items have been given closing tags.
* It isn't clear where the first `<strong>` element should be closed, so the browser has wrapped each separate block of text with its own strong tag, right down to the bottom of the document!
* The incorrect nesting has been fixed by the browser as shown here:
html
```html
<strong>
strong
<em>strong emphasized?</em>
</strong>
<em> what is this?</em>
```
* The link with the missing double quote has been deleted altogether. The last list item looks like this:
html
```html
<li>
<strong>
Unclosed attributes: Another common source of HTML problems. Let's look
at an example:
</strong>
</li>
```
### HTML validation
So you can see from the above example that you really want to make sure your HTML is well-formed! But how? In a small example like the one seen above, it is easy to search through the lines and find the errors, but what about a huge, complex HTML document?
The best strategy is to start by running your HTML page through the Markup Validation Service β created and maintained by the W3C, the organization that looks after the specifications that define HTML, CSS, and other web technologies. This webpage takes an HTML document as an input, goes through it, and gives you a report to tell you what is wrong with your HTML.
![The HTML validator homepage](/en-US/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML/validator.png)
To specify the HTML to validate, you can provide a web address, upload an HTML file, or directly input some HTML code.
### Active learning: Validating an HTML document
Let's try this with our sample document.
1. First, load the Markup Validation Service in one browser tab, if it isn't already open.
2. Switch to the Validate by Direct Input tab.
3. Copy all of the sample document's code (not just the body) and paste it into the large text area shown in the Markup Validation Service.
4. Press the *Check* button.
This should give you a list of errors and other information.
![A list of HTML validation results from the W3C markup validation service](/en-US/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML/validation-results.png)
#### Interpreting the error messages
The error messages are usually helpful, but sometimes they are not so helpful; with a bit of practice you can work out how to interpret these to fix your code. Let's go through the error messages and see what they mean. You'll see that each message comes with a line and column number to help you to locate the error easily.
* "End tag `li` implied, but there were open elements" (2 instances): These messages indicate that an element is open that should be closed. The ending tag is implied, but not actually there. The line/column information points to the first line after the line where the closing tag should really be, but this is a good enough clue to see what is wrong.
* "Unclosed element `strong`": This is really easy to understand β a `<strong>` element is unclosed, and the line/column information points right to where it is.
* "End tag `strong` violates nesting rules": This points out the incorrectly nested elements, and the line/column information points out where they are.
* "End of file reached when inside an attribute value. Ignoring tag": This one is rather cryptic; it refers to the fact that there is an attribute value not properly formed somewhere, possibly near the end of the file because the end of the file appears inside the attribute value. The fact that the browser doesn't render the link should give us a good clue as to what element is at fault.
* "End of file seen and there were open elements": This is a bit ambiguous, but basically refers to the fact there are open elements that need to be properly closed. The line numbers point to the last few lines of the file, and this error message comes with a line of code that points out an example of an open element:
```
example: <a href="https://www.mozilla.org/>link to Mozilla homepage</a> β© </ul>β© </body>β©</html>
```
**Note:** An attribute missing a closing quote can result in an open element because the rest of the document is interpreted as the attribute's content.
* "Unclosed element `ul`": This is not very helpful, as the `<ul>` element *is* closed correctly. This error comes up because the `<a>` element is not closed, due to the missing closing quote mark.
If you can't work out what every error message means, don't worry about it β a good idea is to try fixing a few errors at a time. Then try revalidating your HTML to show what errors are left. Sometimes fixing an earlier error will also get rid of other error messages β several errors can often be caused by a single problem, in a domino effect.
You will know when all your errors are fixed when you see the following banner in your output:
![Banner that reads "The document validates according to the specified schema(s) and to additional constraints checked by the validator."](/en-US/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML/valid-html-banner.png)
Summary
-------
So there we have it, an introduction to debugging HTML, which should give you some useful skills to count on when you start to debug CSS, JavaScript, and other types of code later on in your career. This also marks the end of the Introduction to HTML module learning articles β now you can go on to testing yourself with our assessments: the first one is linked below.
* Previous
* Overview: Introduction to HTML
* Next |
Document and website structure - Learn web development | Document and website structure
==============================
* Previous
* Overview: Introduction to HTML
* Next
In addition to defining individual parts of your page (such as "a paragraph" or "an image"), HTML also boasts a number of block level elements used to define areas of your website (such as "the header", "the navigation menu", "the main content column"). This article looks into how to plan a basic website structure, and write the HTML to represent this structure.
| | |
| --- | --- |
| Prerequisites: |
Basic HTML familiarity, as covered in
Getting started with HTML. HTML text formatting, as covered in
HTML text fundamentals. How hyperlinks work, as covered in
Creating hyperlinks.
|
| Objective: |
Learn how to structure your document using semantic tags, and how to
work out the structure of a simple website.
|
Basic sections of a document
----------------------------
Webpages can and will look pretty different from one another, but they all tend to share similar standard components, unless the page is displaying a fullscreen video or game, is part of some kind of art project, or is just badly structured:
header:
Usually a big strip across the top with a big heading, logo, and perhaps a tagline. This usually stays the same from one webpage to another.
navigation bar:
Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another β having inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than an individual component, but that's not a requirement; in fact, some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.
main content:
A big area in the center that contains most of the unique content of a given webpage, for example, the video you want to watch, or the main story you're reading, or the map you want to view, or the news headlines, etc. This is the one part of the website that definitely will vary from page to page!
sidebar:
Some peripheral info, links, quotes, ads, etc. Usually, this is contextual to what is contained in the main content (for example on a news article page, the sidebar might contain the author's bio, or links to related articles) but there are also cases where you'll find some recurring elements like a secondary navigation system.
footer:
A strip across the bottom of the page that generally contains fine print, copyright notices, or contact info. It's a place to put common information (like the header) but usually, that information is not critical or secondary to the website itself. The footer is also sometimes used for SEO purposes, by providing links for quick access to popular content.
A "typical website" could be structured something like this:
![a simple website structure example featuring a main heading, navigation menu, main content, side bar, and footer.](/en-US/docs/Learn/HTML/Introduction_to_HTML/Document_and_website_structure/sample-website.png)
**Note:** The image above illustrates the main sections of a document, which you can define with HTML. However, the *appearance* of the page shown here - including the layout, colors, and fonts - is achieved by applying CSS to the HTML.
In this module we're not teaching CSS, but once you have an understanding of the basics of HTML, try diving into our CSS first steps module to start learning how to style your site.
HTML for structuring content
----------------------------
The simple example shown above isn't pretty, but it is perfectly fine for illustrating a typical website layout example. Some websites have more columns, some are a lot more complex, but you get the idea. With the right CSS, you could use pretty much any elements to wrap around the different sections and get it looking how you wanted, but as discussed before, we need to respect semantics and **use the right element for the right job**.
This is because visuals don't tell the whole story. We use color and font size to draw sighted users' attention to the most useful parts of the content, like the navigation menu and related links, but what about visually impaired people for example, who might not find concepts like "pink" and "large font" very useful?
**Note:** Roughly 8% of men and 0.5% of women are colorblind; or, to put it another way, approximately 1 in every 12 men and 1 in every 200 women. Blind and visually impaired people represent roughly 4-5% of the world population (in 2015 there were 940 million people with some degree of vision loss, while the total population was around 7.5 billion).
In your HTML code, you can mark up sections of content based on their *functionality* β you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screen readers can recognize those elements and help with tasks like "find the main navigation", or "find the main content." As we mentioned earlier in the course, there are a number of consequences of not using the right element structure and semantics for the right job.
To implement such semantic mark up, HTML provides dedicated tags that you can use to represent such sections, for example:
* **header:** `<header>`.
* **navigation bar:** `<nav>`.
* **main content:** `<main>`, with various content subsections represented by `<article>`, `<section>`, and `<div>` elements.
* **sidebar:** `<aside>`; often placed inside `<main>`.
* **footer:** `<footer>`.
### Active learning: exploring the code for our example
Our example seen above is represented by the following code (you can also find the example in our GitHub repository). We'd like you to look at the example above, and then look over the listing below to see what parts make up what section of the visual.
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>My page title</title>
<link
href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Sonsie+One"
rel="stylesheet" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- Here is our main header that is used across all the pages of our website -->
<header>
<h1>Header</h1>
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Our team</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">Contact</a></li>
</ul>
<!-- A Search form is another common non-linear way to navigate through a website. -->
<form>
<input type="search" name="q" placeholder="Search query" />
<input type="submit" value="Go!" />
</form>
</nav>
<!-- Here is our page's main content -->
<main>
<!-- It contains an article -->
<article>
<h2>Article heading</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Donec a diam
lectus. Set sit amet ipsum mauris. Maecenas congue ligula as quam
viverra nec consectetur ant hendrerit. Donec et mollis dolor. Praesent
et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt
congue enim, ut porta lorem lacinia consectetur.
</p>
<h3>Subsection</h3>
<p>
Donec ut librero sed accu vehicula ultricies a non tortor. Lorem ipsum
dolor sit amet, consectetur adipisicing elit. Aenean ut gravida lorem.
Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.
</p>
<p>
Pelientesque auctor nisi id magna consequat sagittis. Curabitur
dapibus, enim sit amet elit pharetra tincidunt feugiat nist imperdiet.
Ut convallis libero in urna ultrices accumsan. Donec sed odio eros.
</p>
<h3>Another subsection</h3>
<p>
Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum
soclis natoque penatibus et manis dis parturient montes, nascetur
ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem
facilisis semper ac in est.
</p>
<p>
Vivamus fermentum semper porta. Nunc diam velit, adipscing ut
tristique vitae sagittis vel odio. Maecenas convallis ullamcorper
ultricied. Curabitur ornare, ligula semper consectetur sagittis, nisi
diam iaculis velit, is fringille sem nunc vet mi.
</p>
</article>
<!-- the aside content can also be nested within the main content -->
<aside>
<h2>Related</h2>
<ul>
<li><a href="#">Oh I do like to be beside the seaside</a></li>
<li><a href="#">Oh I do like to be beside the sea</a></li>
<li><a href="#">Although in the North of England</a></li>
<li><a href="#">It never stops raining</a></li>
<li><a href="#">Oh wellβ¦</a></li>
</ul>
</aside>
</main>
<!-- And here is our main footer that is used across all the pages of our website -->
<footer>
<p>Β©Copyright 2050 by nobody. All rights reversed.</p>
</footer>
</body>
</html>
```
Take some time to look over the code and understand it β the comments inside the code should also help you to understand it. We aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound HTML structure, and then laying it out with CSS. We'll wait for this until you start to study CSS layout as part of the CSS topic.
HTML layout elements in more detail
-----------------------------------
It's good to understand the overall meaning of all the HTML sectioning elements in detail β this is something you'll work on gradually as you start to get more experience with web development. You can find a lot of detail by reading our HTML element reference. For now, these are the main definitions that you should try to understand:
* `<main>` is for content *unique to this page.* Use `<main>` only *once* per page, and put it directly inside `<body>`. Ideally this shouldn't be nested within other elements.
* `<article>` encloses a block of related content that makes sense on its own without the rest of the page (e.g., a single blog post).
* `<section>` is similar to `<article>`, but it is more for grouping together a single part of the page that constitutes one single piece of functionality (e.g., a mini map, or a set of article headlines and summaries), or a theme. It's considered best practice to begin each section with a heading; also note that you can break `<article>`s up into different `<section>`s, or `<section>`s up into different `<article>`s, depending on the context.
* `<aside>` contains content that is not directly related to the main content but can provide additional information indirectly related to it (glossary entries, author biography, related links, etc.).
* `<header>` represents a group of introductory content. If it is a child of `<body>` it defines the global header of a webpage, but if it's a child of an `<article>` or `<section>` it defines a specific header for that section (try not to confuse this with titles and headings).
* `<nav>` contains the main navigation functionality for the page. Secondary links, etc., would not go in the navigation.
* `<footer>` represents a group of end content for a page.
Each of the aforementioned elements can be clicked on to read the corresponding article in the "HTML element reference" section, providing more detail about each one.
### Non-semantic wrappers
Sometimes you'll come across a situation where you can't find an ideal semantic element to group some items together or wrap some content. Sometimes you might want to just group a set of elements together to affect them all as a single entity with some CSS or JavaScript. For cases like these, HTML provides the `<div>` and `<span>` elements. You should use these preferably with a suitable `class` attribute, to provide some kind of label for them so they can be easily targeted.
`<span>` is an inline non-semantic element, which you should only use if you can't think of a better semantic text element to wrap your content, or don't want to add any specific meaning. For example:
```html
<p>
The King walked drunkenly back to his room at 01:00, the beer doing nothing to
aid him as he staggered through the door.
<span class="editor-note">
[Editor's note: At this point in the play, the lights should be down low].
</span>
</p>
```
In this case, the editor's note is supposed to merely provide extra direction for the director of the play; it is not supposed to have extra semantic meaning. For sighted users, CSS would perhaps be used to distance the note slightly from the main text.
`<div>` is a block level non-semantic element, which you should only use if you can't think of a better semantic block element to use, or don't want to add any specific meaning. For example, imagine a shopping cart widget that you could choose to pull up at any point during your time on an e-commerce site:
```html
<div class="shopping-cart">
<h2>Shopping cart</h2>
<ul>
<li>
<p>
<a href=""><strong>Silver earrings</strong></a>: $99.95.
</p>
<img src="../products/3333-0985/thumb.png" alt="Silver earrings" />
</li>
<li>β¦</li>
</ul>
<p>Total cost: $237.89</p>
</div>
```
This isn't really an `<aside>`, as it doesn't necessarily relate to the main content of the page (you want it viewable from anywhere). It doesn't even particularly warrant using a `<section>`, as it isn't part of the main content of the page. So a `<div>` is fine in this case. We've included a heading as a signpost to aid screen reader users in finding it.
**Warning:** Divs are so convenient to use that it's easy to use them too much. As they carry no semantic value, they just clutter your HTML code. Take care to use them only when there is no better semantic solution and try to reduce their usage to the minimum otherwise you'll have a hard time updating and maintaining your documents.
### Line breaks and horizontal rules
Two elements that you'll use occasionally and will want to know about are `<br>` and `<hr>`.
#### <br>: the line break element
`<br>` creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem. For example:
```html
<p>
There once was a man named O'Dell<br />
Who loved to write HTML<br />
But his structure was bad, his semantics were sad<br />
and his markup didn't read very well.
</p>
```
Without the `<br>` elements, the paragraph would just be rendered in one long line (as we said earlier in the course, HTML ignores most whitespace); with `<br>` elements in the code, the markup renders like this:
#### <hr>: the thematic break element
`<hr>` elements create a horizontal rule in the document that denotes a thematic change in the text (such as a change in topic or scene). Visually it just looks like a horizontal line. As an example:
```html
<p>
Ron was backed into a corner by the marauding netherbeasts. Scared, but
determined to protect his friends, he raised his wand and prepared to do
battle, hoping that his distress call had made it through.
</p>
<hr />
<p>
Meanwhile, Harry was sitting at home, staring at his royalty statement and
pondering when the next spin off series would come out, when an enchanted
distress letter flew through his window and landed in his lap. He read it
hazily and sighed; "better get back to work then", he mused.
</p>
```
Would render like this:
Planning a simple website
-------------------------
Once you've planned out the structure of a simple webpage, the next logical step is to try to work out what content you want to put on a whole website, what pages you need, and how they should be arranged and link to one another for the best possible user experience. This is called Information architecture. In a large, complex website, a lot of planning can go into this process, but for a simple website of a few pages, this can be fairly simple, and fun!
1. Bear in mind that you'll have a few elements common to most (if not all) pages β such as the navigation menu, and the footer content. If your site is for a business, for example, it's a good idea to have your contact information available in the footer on each page. Note down what you want to have common to every page.
![the common features of the travel site to go on every page: title and logo, contact, copyright, terms and conditions, language chooser, accessibility policy](/en-US/docs/Learn/HTML/Introduction_to_HTML/Document_and_website_structure/common-features.png)
2. Next, draw a rough sketch of what you might want the structure of each page to look like (it might look like our simple website above). Note what each block is going to be.
![A simple diagram of a sample site structure, with a header, main content area, two optional sidebars, and footer](/en-US/docs/Learn/HTML/Introduction_to_HTML/Document_and_website_structure/site-structure.png)
3. Now, brainstorm all the other (not common to every page) content you want to have on your website β write a big list down.
![A long list of all the features that we could put on our travel site, from searching, to special offers and country-specific info](/en-US/docs/Learn/HTML/Introduction_to_HTML/Document_and_website_structure/feature-list.png)
4. Next, try to sort all these content items into groups, to give you an idea of what parts might live together on different pages. This is very similar to a technique called Card sorting.
![The items that should appear on a holiday site sorted into 5 categories: Search, Specials, Country-specific info, Search results, and Buy things](/en-US/docs/Learn/HTML/Introduction_to_HTML/Document_and_website_structure/card-sorting.png)
5. Now try to sketch a rough sitemap β have a bubble for each page on your site, and draw lines to show the typical workflow between pages. The homepage will probably be in the center, and link to most if not all of the others; most of the pages in a small site should be available from the main navigation, although there are exceptions. You might also want to include notes about how things might be presented.
![A map of the site showing the homepage, country page, search results, specials page, checkout, and buy page](/en-US/docs/Learn/HTML/Introduction_to_HTML/Document_and_website_structure/site-map.png)
### Active learning: create your own sitemap
Try carrying out the above exercise for a website of your own creation. What would you like to make a site about?
**Note:** Save your work somewhere; you might need it later on.
Summary
-------
At this point, you should have a better idea about how to structure a web page/site. In the next article of this module, we'll learn how to debug HTML.
* Previous
* Overview: Introduction to HTML
* Next |
What's in the head? Metadata in HTML - Learn web development | What's in the head? Metadata in HTML
====================================
* Previous
* Overview: Introduction to HTML
* Next
The head of an HTML document is the part that is not displayed in the web browser when the page is loaded. It contains information such as the page `<title>`, links to CSS (if you choose to style your HTML content with CSS), links to custom favicons, and other metadata (data about the HTML, such as the author, and important keywords that describe the document). Web browsers use information contained in the head to render the HTML document correctly. In this article we'll cover all of the above and more, in order to give you a good basis for working with markup.
| | |
| --- | --- |
| Prerequisites: |
Basic HTML familiarity, as covered in
Getting started with HTML.
|
| Objective: |
To learn about the HTML head, its purpose, the most important items it
can contain, and what effect it can have on the HTML document.
|
What is the HTML head?
----------------------
Let's revisit the simple HTML document we covered in the previous article:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My test page</title>
</head>
<body>
<p>This is my page</p>
</body>
</html>
```
The HTML head is the contents of the `<head>` element. Unlike the contents of the `<body>` element (which are displayed on the page when loaded in a browser), the head's content is not displayed on the page. Instead, the head's job is to contain metadata about the document. In the above example, the head is quite small:
```html
<head>
<meta charset="utf-8" />
<title>My test page</title>
</head>
```
In larger pages however, the head can get quite large. Try going to some of your favorite websites and use the developer tools to check out their head contents. Our aim here is not to show you how to use everything that can possibly be put in the head, but rather to teach you how to use the major elements that you'll want to include in the head, and give you some familiarity. Let's get started.
Adding a title
--------------
We've already seen the `<title>` element in action β this can be used to add a title to the document. This however can get confused with the h1 element, which is used to add a top level heading to your body content β this is also sometimes referred to as the page title. But they are different things!
* The h1 element appears on the page when loaded in the browser β generally this should be used once per page, to mark up the title of your page content (the story title, or news headline, or whatever is appropriate to your usage.)
* The `<title>` element is metadata that represents the title of the overall HTML document (not the document's content.)
### Active learning: Inspecting a simple example
1. To start off this active learning, we'd like you to go to our GitHub repo and download a copy of our title-example.html page. To do this, either
1. Copy and paste the code out of the page and into a new text file in your code editor, then save it in a sensible place.
2. Press the "Raw" button on the GitHub page, which causes the raw code to appear (possibly in a new browser tab). Next, choose your browser's *Save Page Asβ¦* menu and choose a sensible place to save the file.
2. Now open the file in your browser. You should see something like this:
![A web page with 'title' text in the browser's page tab and 'h1' text as a page heading in the document body.](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML/title-example.png)
It should now be completely obvious where the `<h1>` content appears and where the `<title>` content appears!
3. You should also try opening the code up in your code editor, editing the contents of these elements, then refreshing the page in your browser. Have some fun with it.
The `<title>` element contents are also used in other ways. For example, if you try bookmarking the page (*Bookmarks > Bookmark This Page* or the star icon in the URL bar in Firefox), you will see the `<title>` contents filled in as the suggested bookmark name.
![A webpage being bookmarked in Firefox. The bookmark name has been automatically filled in with the contents of the 'title' element](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML/bookmark-example.png)
The `<title>` contents are also used in search results, as you'll see below.
Metadata: the `<meta>` element
------------------------------
Metadata is data that describes data, and HTML has an "official" way of adding metadata to a document β the `<meta>` element. Of course, the other stuff we are talking about in this article could also be thought of as metadata too. There are a lot of different types of `<meta>` elements that can be included in your page's `<head>`, but we won't try to explain them all at this stage, as it would just get too confusing. Instead, we'll explain a few things that you might commonly see, just to give you an idea.
### Specifying your document's character encoding
In the example we saw above, this line was included:
```html
<meta charset="utf-8" />
```
This element specifies the document's character encoding β the character set that the document is permitted to use. `utf-8` is a universal character set that includes pretty much any character from any human language. This means that your web page will be able to handle displaying any language; it's therefore a good idea to set this on every web page you create! For example, your page could handle English and Japanese just fine:
![a web page containing English and Japanese characters, with the character encoding set to universal, or utf-8. Both languages display fine,](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML/correct-encoding.png)If you set your character encoding to `ISO-8859-1`, for example (the character set for the Latin alphabet), your page rendering may appear all messed up:
![a web page containing English and Japanese characters, with the character encoding set to latin. The Japanese characters don't display correctly](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML/bad-encoding.png)
**Note:** Some browsers (like Chrome) automatically fix incorrect encodings, so depending on what browser you use, you may not see this problem. You should still set an encoding of `utf-8` on your page anyway to avoid any potential problems in other browsers.
### Active learning: Experiment with character encoding
To try this out, revisit the simple HTML template you obtained in the previous section on `<title>` (the title-example.html page), try changing the meta charset value to `ISO-8859-1`, and add the Japanese to your page. This is the code we used:
```html
<p>Japanese example: γι£―γη±γγ</p>
```
### Adding an author and description
Many `<meta>` elements include `name` and `content` attributes:
* `name` specifies the type of meta element it is; what type of information it contains.
* `content` specifies the actual meta content.
Two such meta elements that are useful to include on your page define the author of the page, and provide a concise description of the page. Let's look at an example:
```html
<meta name="author" content="Chris Mills" />
<meta
name="description"
content="The MDN Web Docs Learning Area aims to provide
complete beginners to the Web with all they need to know to get
started with developing websites and applications." />
```
Specifying an author is beneficial in many ways: it is useful to be able to understand who wrote the page, if you have any questions about the content and you would like to contact them. Some content management systems have facilities to automatically extract page author information and make it available for such purposes.
Specifying a description that includes keywords relating to the content of your page is useful as it has the potential to make your page appear higher in relevant searches performed in search engines (such activities are termed Search Engine Optimization, or SEO.)
### Active learning: The description's use in search engines
The description is also used on search engine result pages. Let's go through an exercise to explore this
1. Go to the front page of The Mozilla Developer Network.
2. View the page's source (right-click on the page, choose *View Page Source* from the context menu.)
3. Find the description meta tag. It will look something like this (although it may change over time):
```html
<meta
name="description"
content="The MDN Web Docs site
provides information about Open Web technologies
including HTML, CSS, and APIs for both websites and
progressive web apps." />
```
4. Now search for "MDN Web Docs" in your favorite search engine (We used Google.) You'll notice the description `<meta>` and `<title>` element content used in the search result β definitely worth having!
![A Yahoo search result for "Mozilla Developer Network"](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML/mdn-search-result.png)
**Note:** In Google, you will see some relevant subpages of MDN Web Docs listed below the main homepage link β these are called sitelinks, and are configurable in Google's webmaster tools β a way to make your site's search results better in the Google search engine.
**Note:** Many `<meta>` features just aren't used anymore. For example, the keyword `<meta>` element (`<meta name="keywords" content="fill, in, your, keywords, here">`) β which is supposed to provide keywords for search engines to determine relevance of that page for different search terms β is ignored by search engines, because spammers were just filling the keyword list with hundreds of keywords, biasing results.
### Other types of metadata
As you travel around the web, you'll find other types of metadata, too. A lot of the features you'll see on websites are proprietary creations, designed to provide certain sites (such as social networking sites) with specific pieces of information they can use.
For example, Open Graph Data is a metadata protocol that Facebook invented to provide richer metadata for websites. In the MDN Web Docs sourcecode, you'll find this:
```html
<meta
property="og:image"
content="https://developer.mozilla.org/mdn-social-share.png" />
<meta
property="og:description"
content="The Mozilla Developer Network (MDN) provides
information about Open Web technologies including HTML, CSS, and APIs for both websites
and HTML Apps." />
<meta property="og:title" content="Mozilla Developer Network" />
```
One effect of this is that when you link to MDN Web Docs on Facebook, the link appears along with an image and description: a richer experience for users.
![Open graph protocol data from the MDN homepage as displayed on facebook, showing an image, title, and description.](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML/facebook-output.png)
Twitter also has its own similar proprietary metadata called Twitter Cards, which has a similar effect when the site's URL is displayed on twitter.com. For example:
```html
<meta name="twitter:title" content="Mozilla Developer Network" />
```
Adding custom icons to your site
--------------------------------
To further enrich your site design, you can add references to custom icons in your metadata, and these will be displayed in certain contexts. The most commonly used of these is the **favicon** (short for "favorites icon", referring to its use in the "favorites" or "bookmarks" lists in browsers).
The humble favicon has been around for many years. It is the first icon of this type: a 16-pixel square icon used in multiple places. You may see (depending on the browser) favicons displayed in the browser tab containing each open page, and next to bookmarked pages in the bookmarks panel.
A favicon can be added to your page by:
1. Saving it in the same directory as the site's index page, saved in `.ico` format (most also support favicons in more common formats like `.gif` or `.png`)
2. Adding the following line into your HTML's `<head>` block to reference it:
```html
<link rel="icon" href="favicon.ico" type="image/x-icon" />
```
Here is an example of a favicon in a bookmarks panel:
![The Firefox bookmarks panel, showing a bookmarked example with a favicon displayed next to it.](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML/bookmark-favicon.png)
There are lots of other icon types to consider these days as well. For example, you'll find this in the source code of the MDN Web Docs homepage:
```html
<!-- third-generation iPad with high-resolution Retina display: -->
<link
rel="apple-touch-icon"
sizes="144x144"
href="https://developer.mozilla.org/static/img/favicon144.png" />
<!-- iPhone with high-resolution Retina display: -->
<link
rel="apple-touch-icon"
sizes="114x114"
href="https://developer.mozilla.org/static/img/favicon114.png" />
<!-- first- and second-generation iPad: -->
<link
rel="apple-touch-icon"
sizes="72x72"
href="https://developer.mozilla.org/static/img/favicon72.png" />
<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
<link
rel="apple-touch-icon"
href="https://developer.mozilla.org/static/img/favicon57.png" />
<!-- basic favicon -->
<link
rel="icon"
href="https://developer.mozilla.org/static/img/favicon32.png" />
```
The comments explain what each icon is used for β these elements cover things like providing a nice high resolution icon to use when the website is saved to an iPad's home screen.
Don't worry too much about implementing all these types of icon right now β this is a fairly advanced feature, and you won't be expected to have knowledge of this to progress through the course. The main purpose here is to let you know what such things are, in case you come across them while browsing other websites' source code.
**Note:** If your site uses a Content Security Policy (CSP) to enhance its security, the policy applies to the favicon. If you encounter problems with the favicon not loading, verify that the `Content-Security-Policy` header's `img-src` directive is not preventing access to it.
Applying CSS and JavaScript to HTML
-----------------------------------
Just about all websites you'll use in the modern day will employ CSS to make them look cool, and JavaScript to power interactive functionality, such as video players, maps, games, and more. These are most commonly applied to a web page using the `<link>` element and the `<script>` element, respectively.
* The `<link>` element should always go inside the head of your document. This takes two attributes, `rel="stylesheet"`, which indicates that it is the document's stylesheet, and `href`, which contains the path to the stylesheet file:
```html
<link rel="stylesheet" href="my-css-file.css" />
```
* The `<script>` element should also go into the head, and should include a `src` attribute containing the path to the JavaScript you want to load, and `defer`, which basically instructs the browser to load the JavaScript after the page has finished parsing the HTML. This is useful as it makes sure that the HTML is all loaded before the JavaScript runs, so that you don't get errors resulting from JavaScript trying to access an HTML element that doesn't exist on the page yet. There are actually a number of ways to handle loading JavaScript on your page, but this is the most reliable one to use for modern browsers (for others, read Script loading strategies).
```html
<script src="my-js-file.js" defer></script>
```
**Note:** The `<script>` element may look like a void element, but it's not, and so needs a closing tag. Instead of pointing to an external script file, you can also choose to put your script inside the `<script>` element.
### Active learning: applying CSS and JavaScript to a page
1. To start this active learning, grab a copy of our meta-example.html, script.js and style.css files, and save them on your local computer in the same directory. Make sure they are saved with the correct names and file extensions.
2. Open the HTML file in both your browser, and your text editor.
3. By following the information given above, add `<link>` and `<script>` elements to your HTML, so that your CSS and JavaScript are applied to your HTML.
If done correctly, when you save your HTML and refresh your browser you should be able to see that things have changed:
![Example showing a page with CSS and JavaScript applied to it. The CSS has made the page go green, whereas the JavaScript has added a dynamic list to the page.](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML/js-and-css.png)
* The JavaScript has added an empty list to the page. Now when you click anywhere outside the list, a dialog box will pop up asking you to enter some text for a new list item. When you press the OK button, a new list item will be added to the list containing the text. When you click on an existing list item, a dialog box will pop up allowing you to change the item's text.
* The CSS has caused the background to go green, and the text to become bigger. It has also styled some of the content that the JavaScript has added to the page (the red bar with the black border is the styling the CSS has added to the JS-generated list.)
**Note:** If you get stuck in this exercise and can't get the CSS/JS to apply, try checking out our css-and-js.html example page.
Setting the primary language of the document
--------------------------------------------
Finally, it's worth mentioning that you can (and really should) set the language of your page. This can be done by adding the lang attribute to the opening HTML tag (as seen in the meta-example.html and shown below.)
```html
<html lang="en-US">
β¦
</html>
```
This is useful in many ways. Your HTML document will be indexed more effectively by search engines if its language is set (allowing it to appear correctly in language-specific results, for example), and it is useful to people with visual impairments using screen readers (for example, the word "six" exists in both French and English, but is pronounced differently.)
You can also set subsections of your document to be recognized as different languages. For example, we could set our Japanese language section to be recognized as Japanese, like so:
```html
<p>Japanese example: <span lang="ja">γι£―γη±γγ</span>.</p>
```
These codes are defined by the ISO 639-1 standard. You can find more about them in Language tags in HTML and XML.
Summary
-------
That marks the end of our quickfire tour of the HTML head β there's a lot more you can do in here, but an exhaustive tour would be boring and confusing at this stage, and we just wanted to give you an idea of the most common things you'll find in there for now! In the next article, we'll be looking at HTML text fundamentals.
* Previous
* Overview: Introduction to HTML
* Next |
Test your skills: HTML text basics - Learn web development | Test your skills: HTML text basics
==================================
The aim of this skill test is to assess whether you understand how to mark up text in HTML to give it structure and meaning.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, we want you to mark up the provided HTML using semantic heading and paragraph elements.
The finished example should look like this:
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, we want you to turn the first un-marked up list into an unordered list, and the second one into an ordered list.
The finished example should look like this:
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 3
------
In this task, you are provided with a paragraph, and your aim is to use some inline elements to mark up a couple of appropriate words with strong importance, and a couple with emphasis.
The finished example should look like this:
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Getting started with HTML - Learn web development | Getting started with HTML
=========================
* Overview: Introduction to HTML
* Next
In this article, we cover the absolute basics of HTML. To get you started, this article defines elements, attributes, and all the other important terms you may have heard. It also explains where these fit into HTML. You will learn how HTML elements are structured, how a typical HTML page is structured, and other important basic language features. Along the way, there will be an opportunity to play with HTML too!
| | |
| --- | --- |
| Prerequisites: | Basic software installed, and basic knowledge of
working with files.
|
| Objective: |
To gain basic familiarity with HTML, and practice writing a few HTML
elements.
|
What is HTML?
-------------
HTML (HyperText Markup Language) is a *markup language* that tells web browsers how to structure the web pages you visit. It can be as complicated or as simple as the web developer wants it to be. HTML consists of a series of elements, which you use to enclose, wrap, or *mark up* different parts of content to make it appear or act in a certain way. The enclosing tags can make content into a hyperlink to connect to another page, italicize words, and so on. For example, consider the following line of text:
```
My cat is very grumpy
```
If we wanted the text to stand by itself, we could specify that it is a paragraph by enclosing it in a paragraph (`<p>`) element:
```html
<p>My cat is very grumpy</p>
```
**Note:** Tags in HTML are not case-sensitive. This means they can be written in uppercase or lowercase. For example, a `<title>` tag could be written as `<title>`, `<TITLE>`, `<Title>`, `<TiTlE>`, etc., and it will work. However, it is best practice to write all tags in lowercase for consistency and readability.
Anatomy of an HTML element
--------------------------
Let's further explore our paragraph element from the previous section:
![A sample code snippet demonstrating the structure of an html element.<p> My cat is very grumpy </p>.](/en-US/docs/Learn/HTML/Introduction_to_HTML/Getting_started/grumpy-cat-small.png)
The anatomy of our element is:
* **The opening tag:** This consists of the name of the element (in this example, *p* for paragraph), wrapped in opening and closing angle brackets. This opening tag marks where the element begins or starts to take effect. In this example, it precedes the start of the paragraph text.
* **The content:** This is the content of the element. In this example, it is the paragraph text.
* **The closing tag:** This is the same as the opening tag, except that it includes a forward slash before the element name. This marks where the element ends. Failing to include a closing tag is a common beginner error that can produce peculiar results.
The element is the opening tag, followed by content, followed by the closing tag.
### Active learning: creating your first HTML element
Edit the line below in the "Editable code" area by wrapping it with the tags `<em>` and `</em>.` To *open the element*, put the opening tag `<em>` at the start of the line. To *close the element*, put the closing tag `</em>` at the end of the line. Doing this should give the line italic text formatting! See your changes update live in the *Output* area.
If you make a mistake, you can clear your work using the *Reset* button. If you get really stuck, press the *Show solution* button to see the answer.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="min-height: 100px;width: 95%">
This is my text.
</textarea>
<div class="controls">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
html {
font-family: "Open Sans Light", Helvetica, Arial, sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution = "<em>This is my text.</em>";
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
### Nesting elements
Elements can be placed within other elements. This is called *nesting*. If we wanted to state that our cat is **very** grumpy, we could wrap the word *very* in a `<strong>` element, which means that the word is to have strong(er) text formatting:
```html
<p>My cat is <strong>very</strong> grumpy.</p>
```
There is a right and wrong way to do nesting. In the example above, we opened the `p` element first, then opened the `strong` element. For proper nesting, we should close the `strong` element first, before closing the `p`.
The following is an example of the *wrong* way to do nesting:
```html
<p>My cat is <strong>very grumpy.</p></strong>
```
The **tags have to open and close in a way that they are inside or outside one another**. With the kind of overlap in the example above, the browser has to guess at your intent. This kind of guessing can result in unexpected results.
### Void elements
Not all elements follow the pattern of an opening tag, content, and a closing tag. Some elements consist of a single tag, which is typically used to insert/embed something in the document. Such elements are called void elements. For example, the `<img>` element embeds an image file onto a page:
```html
<img
src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png"
alt="Firefox icon" />
```
This would output the following:
**Note:** In HTML, there is no requirement to add a `/` at the end of a void element's tag, for example: `<img src="images/cat.jpg" alt="cat" />`. However, it is also a valid syntax, and you may do this when you want your HTML to be valid XML.
Attributes
----------
Elements can also have attributes. Attributes look like this:
![paragraph tag with 'class="editor-note"' attribute emphasized](/en-US/docs/Learn/HTML/Introduction_to_HTML/Getting_started/grumpy-cat-attribute-small.png)
Attributes contain extra information about the element that won't appear in the content. In this example, the **`class`** attribute is an identifying name used to target the element with style information.
An attribute should have:
* A space between it and the element name. (For an element with more than one attribute, the attributes should be separated by spaces too.)
* The attribute name, followed by an equal sign.
* An attribute value, wrapped with opening and closing quote marks.
### Active learning: Adding attributes to an element
The `<img>` element can take a number of attributes, including:
`src`
The `src` attribute is a **required** attribute that specifies the location of the image. For example: `src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png"`.
`alt`
The `alt` attribute specifies a text description of the image. For example: `alt="The Firefox icon"`.
`width`
The `width` attribute specifies the width of the image with the unit being pixels. For example: `width="300"`.
`height`
The `height` attribute specifies the height of the image with the unit being pixels. For example: `height="300"`.
Edit the line below in the *Input* area to turn it into an image.
1. Find your favorite image online, right click it, and press *Copy Image Link/Address*.
2. Back in the area below, add the `src` attribute and fill it with the link from step 1.
3. Set the `alt` attribute.
4. Add the `width` and `height` attributes.
You will be able to see your changes live in the *Output* area.
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 the answer.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 100px;width: 95%">
<img alt="I should be an image" >
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
'<img src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png" alt="Firefox icon" width="100" height="100" />';
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
### Boolean attributes
Sometimes you will see attributes written without values. This is entirely acceptable. These are called Boolean attributes. Boolean attributes can only have one value, which is generally the same as the attribute name. For example, consider the `disabled` attribute, which you can assign to form input elements. (You use this to *disable* the form input elements so the user can't make entries. The disabled elements typically have a grayed-out appearance.) For example:
```html
<input type="text" disabled="disabled" />
```
As shorthand, it is acceptable to write this as follows:
```html
<!-- using the disabled attribute prevents the end user from entering text into the input box -->
<input type="text" disabled />
<!-- text input is allowed, as it doesn't contain the disabled attribute -->
<input type="text" />
```
For reference, the example above also includes a non-disabled form input element. The HTML from the example above produces this result:
### Omitting quotes around attribute values
If you look at code for a lot of other sites, you might come across a number of strange markup styles, including attribute values without quotes. This is permitted in certain circumstances, but it can also break your markup in other circumstances. The element in the code snippet below, `<a>`, is called an anchor. Anchors enclose text and turn them into links. The `href` attribute specifies the web address the link points to. You can write this basic version below with *only* the `href` attribute, like this:
```html
<a href=https://www.mozilla.org/>favorite website</a>
```
Anchors can also have a `title` attribute, a description of the linked page. However, as soon as we add the `title` in the same fashion as the `href` attribute there are problems:
```html
<a href=https://www.mozilla.org/ title=The Mozilla homepage>favorite website</a>
```
As written above, the browser misinterprets the markup, mistaking the `title` attribute for three attributes: a title attribute with the value `The`, and two Boolean attributes, `Mozilla` and `homepage`. Obviously, this is not intended! It will cause errors or unexpected behavior, as you can see in the live example below. Try hovering over the link to view the title text!
Always include the attribute quotes. It avoids such problems, and results in more readable code.
### Single or double quotes?
In this article, you will also notice that the attributes are wrapped in double quotes. However, you might see single quotes in some HTML code. This is a matter of style. You can feel free to choose which one you prefer. Both of these lines are equivalent:
```html
<a href='https://www.example.com'>A link to my example.</a>
<a href="https://www.example.com">A link to my example.</a>
```
Make sure you don't mix single quotes and double quotes. This example (below) shows a kind of mixing of quotes that will go wrong:
```html
<a href="https://www.example.com'>A link to my example.</a>
```
However, if you use one type of quote, you can include the other type of quote *inside* your attribute values:
```html
<a href="https://www.example.com" title="Isn't this fun?">
A link to my example.
</a>
```
To use quote marks inside other quote marks of the same type (single quote or double quote), use HTML entities. For example, this will break:
```html
<a href="https://www.example.com" title="An "interesting" reference">A link to my example.</a>
```
Instead, you need to do this:
```html
<a href="https://www.example.com" title="An "interesting" reference">A link to my example.</a>
```
Anatomy of an HTML document
---------------------------
Individual HTML elements aren't very useful on their own. Next, let's examine how individual elements combine to form an entire HTML page:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My test page</title>
</head>
<body>
<p>This is my page</p>
</body>
</html>
```
Here we have:
1. `<!DOCTYPE html>`: The doctype. When HTML was young (1991-1992), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML. Doctypes used to look something like this:
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
```
More recently, the doctype is a historical artifact that needs to be included for everything else to work right. `<!DOCTYPE html>` is the shortest string of characters that counts as a valid doctype. That is all you need to know!
2. `<html></html>`: The `<html>` element. This element wraps all the content on the page. It is sometimes known as the root element.
3. `<head></head>`: The `<head>` element. This element acts as a container for everything you want to include on the HTML page, **that isn't the content** the page will show to viewers. This includes keywords and a page description that would appear in search results, CSS to style content, character set declarations, and more. You will learn more about this in the next article of the series.
4. `<meta charset="utf-8">`: The `<meta>` element. This element represents metadata that cannot be represented by other HTML meta-related elements, like `<base>`, `<link>`, `<script>`, `<style>` or `<title>`. The `charset` attribute specifies the character encoding for your document as UTF-8, which includes most characters from the vast majority of human written languages. With this setting, the page can now handle any textual content it might contain. There is no reason not to set this, and it can help avoid some problems later.
5. `<title></title>`: The `<title>` element. This sets the title of the page, which is the title that appears in the browser tab the page is loaded in. The page title is also used to describe the page when it is bookmarked.
6. `<body></body>`: The `<body>` element. This contains *all* the content that displays on the page, including text, images, videos, games, playable audio tracks, or whatever else.
### Active learning: Adding some features to an HTML document
If you want to experiment with writing some HTML on your local computer, you can:
1. Copy the HTML page example listed above.
2. Create a new file in your text editor.
3. Paste the code into the new text file.
4. Save the file as `index.html`.
**Note:** You can also find this basic HTML template on the MDN Learning Area GitHub repo.
You can now open this file in a web browser to see what the rendered code looks like. Edit the code and refresh the browser to see what the result is. Initially, the page looks like this:
![A simple HTML page that says This is my page](/en-US/docs/Learn/HTML/Introduction_to_HTML/Getting_started/template-screenshot.png)In this exercise, you can edit the code locally on your computer, as described previously, or you can edit it in the sample window below (the editable sample window represents just the contents of the `<body>` element, in this case). Sharpen your skills by implementing the following tasks:
* Just below the opening tag of the `<body>` element, add a main title for the document. This should be wrapped inside an `<h1>` opening tag and `</h1>` closing tag.
* Edit the paragraph content to include text about a topic that you find interesting.
* Make important words stand out in bold by wrapping them inside a `<strong>` opening tag and `</strong>` closing tag.
* Add a link to your paragraph, as explained earlier in the article.
* Add an image to your document. Place it below the paragraph, as explained earlier in the article. Earn bonus points if you manage to link to a different image (either locally on your computer or somewhere else on the web).
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 the answer.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 100px;width: 95%">
<p>This is my page</p>
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
html {
font-family: sans-serif;
}
h1 {
color: blue;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
img {
max-width: 100%;
}
body {
margin: 10px;
background: #f5f9fa;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
'<h1>Some music</h1><p>I really enjoy <strong>playing the drums</strong>. One of my favorite drummers is Neal Peart, who plays in the band <a href="https://en.wikipedia.org/wiki/Rush\_%28band%29" title="Rush Wikipedia article">Rush</a>. My favorite Rush album is currently <a href="http://www.deezer.com/album/942295">Moving Pictures</a>.</p> <img src="http://www.cygnus-x1.net/links/rush/images/albums/sectors/sector2-movingpictures-cover-s.jpg" alt="Rush Moving Pictures album cover">';
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
### Whitespace in HTML
In the examples above, you may have noticed that a lot of whitespace is included in the code. This is optional. These two code snippets are equivalent:
```html
<p id="noWhitespace">Dogs are silly.</p>
<p id="whitespace">Dogs
are
silly.</p>
```
No matter how much whitespace you use inside HTML element content (which can include one or more space characters, but also line breaks), the HTML parser reduces each sequence of whitespace to a single space when rendering the code. So why use so much whitespace? The answer is readability.
It can be easier to understand what is going on in your code if you have it nicely formatted. In our HTML we've got each nested element indented by two spaces more than the one it is sitting inside. It is up to you to choose the style of formatting (how many spaces for each level of indentation, for example), but you should consider formatting it.
Let's have a look at how the browser renders the two paragraphs above with and without whitespace:
**Note:** Accessing the innerHTML of elements from JavaScript will keep all the whitespace intact.
This may return unexpected results if the whitespace is trimmed by the browser.
```js
const noWhitespace = document.getElementById("noWhitespace").innerHTML;
console.log(noWhitespace);
// "Dogs are silly."
const whitespace = document.getElementById("whitespace").innerHTML;
console.log(whitespace);
// "Dogs
// are
// silly."
```
Entity references: Including special characters in HTML
-------------------------------------------------------
In HTML, the characters `<`, `>`,`"`,`'`, and `&` are special characters. They are parts of the HTML syntax itself. So how do you include one of these special characters in your text? For example, if you want to use an ampersand or less-than sign, and not have it interpreted as code.
You do this with character references. These are special codes that represent characters, to be used in these exact circumstances. Each character reference starts with an ampersand (&), and ends with a semicolon (;).
| Literal character | Character reference equivalent |
| --- | --- |
| < | `<` |
| > | `>` |
| " | `"` |
| ' | `'` |
| & | `&` |
The character reference equivalent could be easily remembered because the text it uses can be seen as less than for `<`, quotation for `"` and similarly for others. To find more about entity references, see List of XML and HTML character entity references (Wikipedia).
In the example below, there are two paragraphs:
```html
<p>In HTML, you define a paragraph using the <p> element.</p>
<p>In HTML, you define a paragraph using the <p> element.</p>
```
In the live output below, you can see that the first paragraph has gone wrong. The browser interprets the second instance of `<p>` as starting a new paragraph. The second paragraph looks fine because it has angle brackets with character references.
**Note:** You don't need to use entity references for any other symbols, as modern browsers will handle the actual symbols just fine as long as your HTML's character encoding is set to UTF-8.
HTML comments
-------------
HTML has a mechanism to write comments in the code. Browsers ignore comments, effectively making comments invisible to the user. The purpose of comments is to allow you to include notes in the code to explain your logic or coding. This is very useful if you return to a code base after being away for long enough that you don't completely remember it. Likewise, comments are invaluable as different people are making changes and updates.
To write an HTML comment, wrap it in the special markers `<!--` and `-->`. For example:
```html
<p>I'm not inside a comment</p>
<!-- <p>I am!</p> -->
```
As you can see below, only the first paragraph is displayed in the live output.
Summary
-------
You made it to the end of the article! We hope you enjoyed your tour of the basics of HTML.
At this point, you should understand what HTML looks like, and how it works at a basic level. You should also be able to write a few elements and attributes. The subsequent articles of this module go further on some of the topics introduced here, as well as presenting other concepts of the language.
* As you start to learn more about HTML, consider learning the basics of CSS (Cascading Style Sheets). CSS is the language used to style web pages, such as changing fonts or colors or altering the page layout. HTML and CSS work well together, as you will soon discover.
See also
--------
* Applying color to HTML elements using CSS
* Overview: Introduction to HTML
* Next |
Test your skills: Links - Learn web development | Test your skills: Links
=======================
The aim of this skill test is to assess whether you understand how to implement hyperlinks in HTML.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, we want you to help fill in the links on our Whales information page:
* The first link should be linked to a page called `whales.html`, which is in the same directory as the current page.
* We'd also like you to give it a tooltip when moused over that tells the user that the page includes information on Blue Whales and Sperm Whales.
* The second link should be turned into a link you can click to open up an email in the user's default mail application, with the recipient set as "[email protected]".
* You'll get a bonus point if you also set it so that the subject line of the email is automatically filled in as "Question about Whales".
**Note:** The two links in the example have the `target="_blank"` attribute set on them. This is not strictly best practice, but we've done it here so that the links don't open in the embedded `<iframe>`, getting rid of your example code in the process!
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, we want you to fill in the four links so that they link to the appropriate places:
* The first link should link to an image called `blue-whale.jpg`, which is located in a directory called `blue` inside the current directory.
* The second link should link to an image called `narwhal.jpg`, which is located in a directory called `narwhal`, which is located one directory level above the current directory.
* The third link should link to the UK Google Image search. The base URL is `https://www.google.co.uk`, and the image search is located in a subdirectory called `imghp`.
* The fourth link should link to the paragraph at the very bottom of the current page. It has an ID of `bottom`.
**Note:** The first three links in the example have the `target="_blank"` attribute set on them, so that when you click on them, they open the linked page in a new tab. This is not strictly best practice, but we've done it here so that the pages don't open in the embedded `<iframe>`, getting rid of your example code in the process!
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 3
------
The following links link to an info page about Narwhals, a support email address, and a PDF factfile that is 4MB in size. In this task, we want you to:
* Take the existing paragraphs with poorly-written link text, and rewrite them so that they have good link text.
* Add a warning to any links that need a warning added.
**Note:** The first and third links in the example have the `target="_blank"` attribute set on them, so that when you click on them, they open the linked page in a new tab. This is not strictly best practice, but we've done it here so that the pages don't open in the embedded `<iframe>`, getting rid of your example code in the process!
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
HTML text fundamentals - Learn web development | HTML text fundamentals
======================
* Previous
* Overview: Introduction to HTML
* Next
One of HTML's main jobs is to give text structure so that a browser can display an HTML document the way its developer intends. This article explains the way HTML can be used to structure a page of text by adding headings and paragraphs, emphasizing words, creating lists, and more.
| | |
| --- | --- |
| Prerequisites: |
Basic HTML familiarity, as covered in
Getting started with HTML.
|
| Objective: |
Learn how to mark up a basic page of text to give it structure and
meaning β including paragraphs, headings, lists, emphasis, and quotations.
|
The basics: headings and paragraphs
-----------------------------------
Most structured text consists of headings and paragraphs, whether you are reading a story, a newspaper, a college textbook, a magazine, etc.
![An example of a newspaper front cover, showing use of a top level heading, subheadings and paragraphs.](/en-US/docs/Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals/newspaper_small.jpg)
Structured content makes the reading experience easier and more enjoyable.
In HTML, each paragraph has to be wrapped in a `<p>` element, like so:
```html
<p>I am a paragraph, oh yes I am.</p>
```
Each heading has to be wrapped in a heading element:
```html
<h1>I am the title of the story.</h1>
```
There are six heading elements: h1, h2, h3, h4, h5, and h6. Each element represents a different level of content in the document; `<h1>` represents the main heading, `<h2>` represents subheadings, `<h3>` represents sub-subheadings, and so on.
### Implementing structural hierarchy
For example, in this story, the `<h1>` element represents the title of the story, the `<h2>` elements represent the title of each chapter, and the `<h3>` elements represent subsections of each chapter:
```html
<h1>The Crushing Bore</h1>
<p>By Chris Mills</p>
<h2>Chapter 1: The dark night</h2>
<p>
It was a dark night. Somewhere, an owl hooted. The rain lashed down on theβ¦
</p>
<h2>Chapter 2: The eternal silence</h2>
<p>Our protagonist could not so much as a whisper out of the shadowy figureβ¦</p>
<h3>The specter speaks</h3>
<p>
Several more hours had passed, when all of a sudden the specter sat bolt
upright and exclaimed, "Please have mercy on my soul!"
</p>
```
It's really up to you what the elements involved represent, as long as the hierarchy makes sense. You just need to bear in mind a few best practices as you create such structures:
* Preferably, you should use a single `<h1>` per pageβthis is the top level heading, and all others sit below this in the hierarchy.
* Make sure you use the headings in the correct order in the hierarchy. Don't use `<h3>` elements to represent subheadings, followed by `<h2>` elements to represent sub-subheadingsβthat doesn't make sense and will lead to weird results.
* Of the six heading levels available, you should aim to use no more than three per page, unless you feel it is necessary. Documents with many levels (for example, a deep heading hierarchy) become unwieldy and difficult to navigate. On such occasions, it is advisable to spread the content over multiple pages if possible.
### Why do we need structure?
To answer this question, let's take a look at text-start.htmlβthe starting point of our running example for this article (a nice hummus recipe). You should save a copy of this file on your local machine, as you'll need it for the exercises later on. This document's body currently contains multiple pieces of content. They aren't marked up in any way, but they are separated with line breaks (Enter/Return pressed to go onto the next line).
However, when you open the document in your browser, you'll see that the text appears as a big chunk!
![A webpage that shows a wall of unformatted text, because there are no elements on the page to structure it.](/en-US/docs/Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals/screen_shot_2017-03-29_at_09.20.35.png)
This is because there are no elements to give the content structure, so the browser does not know what is a heading and what is a paragraph. Furthermore:
* Users looking at a web page tend to scan quickly to find relevant content, often just reading the headings, to begin with. (We usually spend a very short time on a web page.) If they can't see anything useful within a few seconds, they'll likely get frustrated and go somewhere else.
* Search engines indexing your page consider the contents of headings as important keywords for influencing the page's search rankings. Without headings, your page will perform poorly in terms of SEO (Search Engine Optimization).
* Severely visually impaired people often don't read web pages; they listen to them instead. This is done with software called a screen reader. This software provides ways to get fast access to given text content. Among the various techniques used, they provide an outline of the document by reading out the headings, allowing their users to find the information they need quickly. If headings are not available, they will be forced to listen to the whole document read out loud.
* To style content with CSS, or make it do interesting things with JavaScript, you need to have elements wrapping the relevant content, so CSS/JavaScript can effectively target it.
Therefore, we need to give our content structural markup.
### Active learning: Giving our content structure
Let's jump straight in with a live example. In the example below, add elements to the raw text in the *Input* field so that it appears as a heading and two paragraphs in the *Output* field.
If you make a mistake, you can always reset it using the *Reset* button. If you get stuck, press the *Show solution* button to see the answer.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 100px; width: 95%">
My short story I am a statistician and my name is Trish.
My legs are made of cardboard and I am married to a fish.
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution = `<h1>My short story</h1>
<p>
I am a statistician and my name is Trish.
</p>
<p>
My legs are made of cardboard and I am married to a fish.
</p>`;
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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 = 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();
};
```
### Why do we need semantics?
Semantics are relied on everywhere around usβwe rely on previous experience to tell us what the function of an everyday object is; when we see something, we know what its function will be. So, for example, we expect a red traffic light to mean "stop," and a green traffic light to mean "go." Things can get tricky very quickly if the wrong semantics are applied. (Do any countries use red to mean "go"? We hope not.)
In a similar way, we need to make sure we are using the correct elements, giving our content the correct meaning, function, or appearance. In this context, the h1 element is also a semantic element, which gives the text it wraps around the role (or meaning) of "a top level heading on your page."
```html
<h1>This is a top level heading</h1>
```
By default, the browser will give it a large font size to make it look like a heading (although you could style it to look like anything you wanted using CSS). More importantly, its semantic value will be used in multiple ways, for example by search engines and screen readers (as mentioned above).
On the other hand, you could make any element *look* like a top level heading. Consider the following:
```html
<span style="font-size: 32px; margin: 21px 0; display: block;">
Is this a top level heading?
</span>
```
This is a `<span>` element. It has no semantics. You use it to wrap content when you want to apply CSS to it (or do something to it with JavaScript) without giving it any extra meaning. (You'll find out more about these later on in the course.) We've applied some CSS to it to make it look like a top level heading, but since it has no semantic value, it will not get any of the extra benefits described above. It is a good idea to use the relevant HTML element for the job.
Lists
-----
Now let's turn our attention to lists. Lists are everywhere in lifeβfrom your shopping list to the list of directions you subconsciously follow to get to your house every day, to the lists of instructions you are following in these tutorials! Lists are everywhere on the web, too, and we've got three different types to worry about.
### Unordered
Unordered lists are used to mark up lists of items for which the order of the items doesn't matter. Let's take a shopping list as an example:
```
milk
eggs
bread
hummus
```
Every unordered list starts off with a `<ul>` elementβthis wraps around all the list items:
```html
<ul>
milk
eggs
bread
hummus
</ul>
```
The last step is to wrap each list item in a `<li>` (list item) element:
```html
<ul>
<li>milk</li>
<li>eggs</li>
<li>bread</li>
<li>hummus</li>
</ul>
```
#### Active learning: Marking up an unordered list
Try editing the live sample below to create your very own HTML unordered list.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 100px; width: 95%">
milk
eggs
bread
hummus
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
"<ul>\n<li>milk</li>\n<li>eggs</li>\n<li>bread</li>\n<li>hummus</li>\n</ul>";
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
### Ordered
Ordered lists are lists in which the order of the items *does* matter. Let's take a set of directions as an example:
```
Drive to the end of the road
Turn right
Go straight across the first two roundabouts
Turn left at the third roundabout
The school is on your right, 300 meters up the road
```
The markup structure is the same as for unordered lists, except that you have to wrap the list items in an `<ol>` element, rather than `<ul>`:
```html
<ol>
<li>Drive to the end of the road</li>
<li>Turn right</li>
<li>Go straight across the first two roundabouts</li>
<li>Turn left at the third roundabout</li>
<li>The school is on your right, 300 meters up the road</li>
</ol>
```
#### Active learning: Marking up an ordered list
Try editing the live sample below to create your very own HTML ordered list.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 200px; width: 95%">
Drive to the end of the road
Turn right
Go straight across the first two roundabouts
Turn left at the third roundabout
The school is on your right, 300 meters up the road
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
"<ol>\n<li>Drive to the end of the road</li>\n<li>Turn right</li>\n<li>Go straight across the first two roundabouts</li>\n<li>Turn left at the third roundabout</li>\n<li>The school is on your right, 300 meters up the road</li>\n</ol>";
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
### Description
Description lists enclose groups of terms and descriptions. Common uses for this element are implementing a glossary or displaying metadata (a list of key-value pairs). Let's consider some fishes with their interesting characteristics:
```
Albacore Tuna
The albacore is a very fast swimmer.
Asian Carp
Asian carp can consume 40% of their body weight in food a day!
Barracuda
Can grow to nearly 2 meters long!
```
The list is enclosed in a `<dl>` element, terms are enclosed in `<dt>` elements, and descriptions are enclosed in `<dd>` elements:
```html
<dl>
<dt>Albacore Tuna</dt>
<dd>The albacore is a very fast swimmer.</dd>
<dt>Asian Carp</dt>
<dd>Asian carp can consume 40% of their body weight in food a day!</dd>
<dt>Barracuda</dt>
<dd>Can grow to nearly 2 meters long!</dd>
</dl>
```
#### Active learning: Marking up a description list
Try editing the live sample below to create your very own HTML description list.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 200px; width: 95%">
Albacore Tuna
The albacore is a very fast swimmer.
Asian Carp
Asian carp can consume 40% of their body weight in food a day!
Barracuda
Can grow to nearly 2 meters long!
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
"<dl>\n <dt>Albacore Tuna</dt>\n <dd>The albacore is a very fast swimmer.</dd>\n <dt>Asian Carp</dt>\n <dd>Asian carp can consume 40% of their body weight in food a day!</dd>\n <dt>Barracuda</dt>\n <dd>Can grow to nearly 2 meters long!</dd>\n</dl>";
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
### Active learning: Marking up our recipe page
So at this point in the article, you have all the information you need to mark up our recipe page example. You can choose to either save a local copy of our text-start.html starting file and do the work there or do it in the editable example below. Doing it locally will probably be better, as then you'll get to save the work you are doing, whereas if you fill it in to the editable example, it will be lost the next time you open the page. Both have pros and cons.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 200px; width: 95%">
Quick hummus recipe
This recipe makes quick, tasty hummus, with no messing. It has been adapted from a number of different recipes that I have read over the years.
Hummus is a delicious thick paste used heavily in Greek and Middle Eastern dishes. It is very tasty with salad, grilled meats and pitta breads.
Ingredients
1 can (400g) of chick peas (garbanzo beans)
175g of tahini
6 sundried tomatoes
Half a red pepper
A pinch of cayenne pepper
1 clove of garlic
A dash of olive oil
Instructions
Remove the skin from the garlic, and chop coarsely
Remove all the seeds and stalk from the pepper, and chop coarsely
Add all the ingredients into a food processor
Process all the ingredients into a paste
If you want a coarse "chunky" hummus, process it for a short time
If you want a smooth hummus, process it for a longer time
For a different flavor, you could try blending in a small measure of lemon and coriander, chili pepper, lime and chipotle, harissa and mint, or spinach and feta cheese. Experiment and see what works for you.
Storage
Refrigerate the finished hummus in a sealed container. You should be able to use it for about a week after you've made it. If it starts to become fizzy, you should definitely discard it.
Hummus is suitable for freezing; you should thaw it and use it within a couple of months.
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
'<h1>Quick hummus recipe</h1>\n\n<p>This recipe makes quick, tasty hummus, with no messing. It has been adapted from a number of different recipes that I have read over the years.</p>\n\n<p>Hummus is a delicious thick paste used heavily in Greek and Middle Eastern dishes. It is very tasty with salad, grilled meats and pitta breads.</p>\n\n<h2>Ingredients</h2>\n\n<ul>\n<li>1 can (400g) of chick peas (garbanzo beans)</li>\n<li>175g of tahini</li>\n<li>6 sundried tomatoes</li>\n<li>Half a red pepper</li>\n<li>A pinch of cayenne pepper</li>\n<li>1 clove of garlic</li>\n<li>A dash of olive oil</li>\n</ul>\n\n<h2>Instructions</h2>\n\n<ol>\n<li>Remove the skin from the garlic, and chop coarsely.</li>\n<li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>\n<li>Add all the ingredients into a food processor.</li>\n<li>Process all the ingredients into a paste.</li>\n<li>If you want a coarse "chunky" hummus, process it for a short time.</li>\n<li>If you want a smooth hummus, process it for a longer time.</li>\n</ol>\n\n<p>For a different flavor, you could try blending in a small measure of lemon and coriander, chili pepper, lime and chipotle, harissa and mint, or spinach and feta cheese. Experiment and see what works for you.</p>\n\n<h2>Storage</h2>\n\n<p>Refrigerate the finished hummus in a sealed container. You should be able to use it for about a week after you\'ve made it. If it starts to become fizzy, you should definitely discard it.</p>\n\n<p>Hummus is suitable for freezing; you should thaw it and use it within a couple of months.</p>';
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
If you get stuck, you can always press the *Show solution* button, or check out our text-complete.html example on our GitHub repo.
### Nesting lists
It is perfectly OK to nest one list inside another one. You might want to have some sub-bullets sitting below a top-level bullet. Let's take the second list from our recipe example:
```html
<ol>
<li>Remove the skin from the garlic, and chop coarsely.</li>
<li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>
<li>Add all the ingredients into a food processor.</li>
<li>Process all the ingredients into a paste.</li>
<li>If you want a coarse "chunky" hummus, process it for a short time.</li>
<li>If you want a smooth hummus, process it for a longer time.</li>
</ol>
```
Since the last two bullets are very closely related to the one before them (they read like sub-instructions or choices that fit below that bullet), it might make sense to nest them inside their own unordered list and put that list inside the current fourth bullet. This would look like so:
```html
<ol>
<li>Remove the skin from the garlic, and chop coarsely.</li>
<li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>
<li>Add all the ingredients into a food processor.</li>
<li>
Process all the ingredients into a paste.
<ul>
<li>
If you want a coarse "chunky" hummus, process it for a short time.
</li>
<li>If you want a smooth hummus, process it for a longer time.</li>
</ul>
</li>
</ol>
```
Try going back to the previous active learning example and updating the second list like this.
Emphasis and importance
-----------------------
In human language, we often emphasize certain words to alter the meaning of a sentence, and we often want to mark certain words as important or different in some way. HTML provides various semantic elements to allow us to mark up textual content with such effects, and in this section, we'll look at a few of the most common ones.
### Emphasis
When we want to add emphasis in spoken language, we *stress* certain words, subtly altering the meaning of what we are saying. Similarly, in written language we tend to stress words by putting them in italics. For example, the following two sentences have different meanings.
>
> I am glad you weren't late.
>
>
> I am *glad* you weren't *late*.
>
>
>
The first sentence sounds genuinely relieved that the person wasn't late. In contrast, the second one, with both the words "glad" and "late" in italics, sounds sarcastic or passive-aggressive, expressing annoyance that the person arrived a bit late.
In HTML we use the `<em>` (emphasis) element to mark up such instances. As well as making the document more interesting to read, these are recognized by screen readers, which can be configured to speak them in a different tone of voice. Browsers style this as italic by default, but you shouldn't use this tag purely to get italic styling. To do that, you'd use a `<span>` element and some CSS, or perhaps an `<i>` element (see below).
```html
<p>I am <em>glad</em> you weren't <em>late</em>.</p>
```
### Strong importance
To emphasize important words, we tend to stress them in spoken language and **bold** them in written language. For example:
>
> This liquid is **highly toxic**.
>
>
> I am counting on you. **Do not** be late!
>
>
>
In HTML we use the `<strong>` (strong importance) element to mark up such instances. As well as making the document more useful, again these are recognized by screen readers, which can be configured to speak them in a different tone of voice. Browsers style this as bold text by default, but you shouldn't use this tag purely to get bold styling. To do that, you'd use a `<span>` element and some CSS, or perhaps a `<b>` element (see below).
```html
<p>This liquid is <strong>highly toxic</strong>.</p>
<p>I am counting on you. <strong>Do not</strong> be late!</p>
```
You can nest strong and emphasis inside one another if desired:
```html
<p>This liquid is <strong>highly toxic</strong> β if you drink it, <strong>you may <em>die</em></strong>.</p>
```
### Active learning: Let's be important
In this active learning section, we've provided an editable example. Inside it, we'd like you to try adding emphasis and strong importance to the words you think need them, just to have some practice.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 200px; width: 95%">
<h1>Important notice</h1>
<p>On Sunday January 9th 2010, a gang of goths were
spotted stealing several garden gnomes from a
shopping center in downtown Milwaukee. They were
all wearing green jumpsuits and silly hats, and
seemed to be having a whale of a time. If anyone
has any information about this incident, please
contact the police now.</p>
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
"<h1>Important notice</h1>\n<p>On <strong>Sunday January 9th 2010</strong>, a gang of <em>goths</em> were spotted stealing <strong><em>several</em> garden gnomes</strong> from a shopping center in downtown <strong>Milwaukee</strong>. They were all wearing <em>green jumpsuits</em> and <em>silly hats</em>, and seemed to be having a whale of a time. If anyone has <strong>any</strong> information about this incident, please contact the police <strong>now</strong>.</p>";
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
### Italic, bold, underlineβ¦
The elements we've discussed so far have clear-cut associated semantics. The situation with `<b>`, `<i>`, and `<u>` is somewhat more complicated. They came about so people could write bold, italics, or underlined text in an era when CSS was still supported poorly or not at all. Elements like this, which only affect presentation and not semantics, are known as **presentational elements** and should no longer be used because, as we've seen before, semantics is so important to accessibility, SEO, etc.
HTML5 redefined `<b>`, `<i>`, and `<u>` with new, somewhat confusing, semantic roles.
Here's the best rule you can remember: It's only appropriate to use `<b>`, `<i>`, or `<u>` to convey a meaning traditionally conveyed with bold, italics, or underline when there isn't a more suitable element; and there usually is. Consider whether `<strong>`, `<em>`, `<mark>`, or `<span>` might be more appropriate.
Always keep an accessibility mindset. The concept of italics isn't very helpful to people using screen readers, or to people using a writing system other than the Latin alphabet.
* `<i>` is used to convey a meaning traditionally conveyed by italic: foreign words, taxonomic designation, technical terms, a thoughtβ¦
* `<b>` is used to convey a meaning traditionally conveyed by bold: keywords, product names, lead sentenceβ¦
* `<u>` is used to convey a meaning traditionally conveyed by underline: proper name, misspellingβ¦
**Note:** People strongly associate underlining with hyperlinks. Therefore, on the web, it's best to only underline links. Use the `<u>` element when it's semantically appropriate, but consider using CSS to change the default underline to something more appropriate on the web. The example below illustrates how it can be done.
```html
<!-- scientific names -->
<p>
The Ruby-throated Hummingbird (<i>Archilochus colubris</i>) is the most common
hummingbird in Eastern North America.
</p>
<!-- foreign words -->
<p>
The menu was a sea of exotic words like <i lang="uk-latn">vatrushka</i>,
<i lang="id">nasi goreng</i> and <i lang="fr">soupe Γ l'oignon</i>.
</p>
<!-- a known misspelling -->
<p>Someday I'll learn how to <u class="spelling-error">spel</u> better.</p>
<!-- term being defined when used in a definition -->
<dl>
<dt>Semantic HTML</dt>
<dd>
Use the elements based on their <b>semantic</b> meaning, not their
appearance.
</dd>
</dl>
```
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: HTML text basics.
Summary
-------
That's it for now! This article should have given you a good idea of how to start marking up text in HTML and introduced you to some of the most important elements in this area. There are a lot more semantic elements to cover in this area, and we'll look at a lot more in our Advanced text formatting article later on in the course. In the next article, we'll be looking in detail at how to create hyperlinks, possibly the most important element on the web.
* Previous
* Overview: Introduction to HTML
* Next |
Structuring a page of content - Learn web development | Structuring a page of content
=============================
* Previous
* Overview: Introduction to HTML
Structuring a page of content ready for laying it out using CSS is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of.
| | |
| --- | --- |
| Prerequisites: |
Before attempting this assessment you should have already worked through
the rest of the course, with a particular emphasis on
Document and website structure.
|
| Objective: |
To test knowledge of web page structures, and how to represent a
prospective layout design in markup.
|
Starting point
--------------
To get this assessment started, you should go and grab the zip file containing all the starting assets.
The zip file contains:
* The HTML you need to add structural markup to.
* CSS to style your markup.
* Images that are used on the page.
Create the example on your local computer, or alternatively use an online editor such as CodePen, JSFiddle, or Glitch.
**Note:** If you get stuck, you can reach out to us in one of our communication channels.
Project brief
-------------
For this project, your task is to take the content for the homepage of a bird watching website and add structural elements to it so it can have a page layout applied to it. It needs to have:
* A header spanning the full width of the site containing the main title for the page, the site logo, and the navigation menu. The title and logo appear side by side once styling is applied, and the navigation appears below those two items.
* A main content area containing two columns β a main block to contain the welcome text, and a sidebar to contain image thumbnails.
* A footer containing copyright information and credits.
You need to add a suitable wrapper for:
* The header
* The navigation menu
* The main content
* The welcome text
* The image sidebar
* The footer
You should also:
* Apply the provided CSS to the page by adding another `<link>` element just below the existing one provided at the start.
Hints and tips
--------------
* Use the W3C Nu HTML Checker to catch unintended mistakes in your HTML, CSS, and SVG β mistakes you might have otherwise missed β so that you can fix them.
* You don't need to know any CSS to do this assessment; you just need to put the provided CSS inside an HTML element.
* The provided CSS is designed so that when the correct structural elements are added to the markup, they will appear green in the rendered page.
* If you are getting stuck and can't envisage what elements to put where, draw out a simple block diagram of the page layout, and write on the elements you think should wrap each block. This is extremely helpful.
Example
-------
The following screenshot shows an example of what the homepage might look like after being marked up.
![The finished example for the assessment; a simple webpage about birdwatching, including a heading of "Birdwatching", bird photos, and a welcome message](/en-US/docs/Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content/example-page.png)
* Previous
* Overview: Introduction to HTML |
Test your skills: Advanced HTML text - Learn web development | Test your skills: Advanced HTML text
====================================
The aim of this skill test is to assess whether you understand how to use lesser-known HTML elements to mark up advanced semantic features.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, we want you to turn the provided animals and their definitions into a description list.
The finished example should look like this:
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, we want you to add some semantics to the provided HTML as follows:
* Turn the second paragraph into a block-level quote, and semantically indicate that the quote is taken from Accessibility.
* Semantically mark up "HTML" and "CSS" as acronyms, providing expansions as tooltips.
* Use subscript and superscript to provide correct semantics for the chemical formulae and dates, and make them display correctly.
* Semantically associate machine-readable dates with the dates in the text.
The finished example should look like this:
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Advanced text formatting - Learn web development | Advanced text formatting
========================
* Previous
* Overview: Introduction to HTML
* Next
There are many other elements in HTML for formatting text, which we didn't get to in the HTML text fundamentals article. The elements described in this article are less known, but still useful to know about (and this is still not a complete list by any means). Here you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.
| | |
| --- | --- |
| Prerequisites: |
Basic HTML familiarity, as covered in
Getting started with HTML. HTML text formatting, as covered in
HTML text fundamentals.
|
| Objective: |
To learn how to use lesser-known HTML elements to mark up advanced
semantic features.
|
Description lists
-----------------
In HTML text fundamentals, we walked through how to mark up basic lists in HTML, but we didn't mention the third type of list you'll occasionally come across β **description lists**. The purpose of these lists is to mark up a set of items and their associated descriptions, such as terms and definitions, or questions and answers. Let's look at an example of a set of terms and definitions:
```
soliloquy
In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
monologue
In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
aside
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information
```
Description lists use a different wrapper than the other list types β `<dl>`; in addition each term is wrapped in a `<dt>` (description term) element, and each description is wrapped in a `<dd>` (description definition) element.
### Description list example
Let's finish marking up our example:
```html
<dl>
<dt>soliloquy</dt>
<dd>
In drama, where a character speaks to themselves, representing their inner
thoughts or feelings and in the process relaying them to the audience (but
not to other characters.)
</dd>
<dt>monologue</dt>
<dd>
In drama, where a character speaks their thoughts out loud to share them
with the audience and any other characters present.
</dd>
<dt>aside</dt>
<dd>
In drama, where a character shares a comment only with the audience for
humorous or dramatic effect. This is usually a feeling, thought, or piece of
additional background information.
</dd>
</dl>
```
The browser default styles will display description lists with the descriptions indented somewhat from the terms.
### Multiple descriptions for one term
Note that it is permitted to have a single term with multiple descriptions, for example:
```html
<dl>
<dt>aside</dt>
<dd>
In drama, where a character shares a comment only with the audience for
humorous or dramatic effect. This is usually a feeling, thought, or piece of
additional background information.
</dd>
<dd>
In writing, a section of content that is related to the current topic, but
doesn't fit directly into the main flow of content so is presented nearby
(often in a box off to the side.)
</dd>
</dl>
```
### Active learning: Marking up a set of definitions
It's time to try your hand at description lists; add elements to the raw text in the *Input* field so that it appears as a description list in the *Output* field. You could try using your own terms and descriptions if you like.
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 the answer.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 100px; width: 95%">
Bacon
The glue that binds the world together.
Eggs
The glue that binds the cake together.
Coffee
The drink that gets the world running in the morning.
A light brown color.
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
"<dl>\n <dt>Bacon</dt>\n <dd>The glue that binds the world together.</dd>\n <dt>Eggs</dt>\n <dd>The glue that binds the cake together.</dd>\n <dt>Coffee</dt>\n <dd>The drink that gets the world running in the morning.</dd>\n <dd>A light brown color.</dd>\n</dl>";
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
Quotations
----------
HTML also has features available for marking up quotations; which element you use depends on whether you are marking up a block or inline quotation.
### Blockquotes
If a section of block level content (be it a paragraph, multiple paragraphs, a list, etc.) is quoted from somewhere else, you should wrap it inside a `<blockquote>` element to signify this, and include a URL pointing to the source of the quote inside a `cite` attribute. For example, the following markup is taken from the MDN `<blockquote>` element page:
```html
<p>
The <strong>HTML <code><blockquote></code> Element</strong> (or
<em>HTML Block Quotation Element</em>) indicates that the enclosed text is an
extended quotation.
</p>
```
To turn this into a block quote, we would just do this:
```html
<p>Here is a blockquote:</p>
<blockquote
cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
<p>
The <strong>HTML <code><blockquote></code> Element</strong> (or
<em>HTML Block Quotation Element</em>) indicates that the enclosed text is
an extended quotation.
</p>
</blockquote>
```
Browser default styling will render this as an indented paragraph, as an indicator that it is a quote; the paragraph above the quotation is there to demonstrate that.
### Inline quotations
Inline quotations work in exactly the same way, except that they use the `<q>` element. For example, the below bit of markup contains a quotation from the MDN `<q>` page:
```html
<p>
The quote element β <code><q></code> β is
<q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">
intended for short quotations that don't require paragraph breaks.
</q>
</p>
```
Browser default styling will render this as normal text put in quotes to indicate a quotation, like so:
### Citations
The content of the `cite` attribute sounds useful, but unfortunately browsers, screen readers, etc. don't really do much with it. There is no way to get the browser to display the contents of `cite`, without writing your own solution using JavaScript or CSS. If you want to make the source of the quotation available on the page you need to make it available in the text via a link or some other appropriate way.
There is a `<cite>` element, but this is meant to contain the title of the resource being quoted, e.g. the name of the book. There is no reason, however, why you couldn't link the text inside `<cite>` to the quote source in some way:
```html
<p>
According to the
<a href="/en-US/docs/Web/HTML/Element/blockquote">
<cite>MDN blockquote page</cite></a>:
</p>
<blockquote
cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
<p>
The <strong>HTML <code><blockquote></code> Element</strong> (or
<em>HTML Block Quotation Element</em>) indicates that the enclosed text is
an extended quotation.
</p>
</blockquote>
<p>
The quote element β <code><q></code> β is
<q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">
intended for short quotations that don't require paragraph breaks.
</q>
β <a href="/en-US/docs/Web/HTML/Element/q"><cite>MDN q page</cite></a>.
</p>
```
Citations are styled in italic font by default.
### Active learning: Who said that?
Time for another active learning example! In this example we'd like you to:
1. Turn the middle paragraph into a blockquote, which includes a `cite` attribute.
2. Turn "The Need To Eliminate Negative Self Talk" in the third paragraph into an inline quote, and include a `cite` attribute.
3. Wrap the title of each source in `<cite>` tags and turn each one into a link to that source.
The citation sources you need are:
* `http://www.brainyquote.com/quotes/authors/c/confucius.html` for the Confucius quote
* `http://example.com/affirmationsforpositivethinking` for "The Need To Eliminate Negative Self Talk".
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 the answer.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 150px; width: 95%">
<p>Hello and welcome to my motivation page. As Confucius' quotes site says:</p>
<p>It does not matter how slowly you go as long as you do not stop.</p>
<p>I also love the concept of positive thinking, and The Need To Eliminate Negative Self Talk (as mentioned in Affirmations for Positive Thinking.)</p>
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
'<p>Hello and welcome to my motivation page. As <a href="http://www.brainyquote.com/quotes/authors/c/confucius.html"><cite>Confucius\' quotes site</cite></a> says:</p>\n\n<blockquote cite="http://www.brainyquote.com/quotes/authors/c/confucius.html">\n <p>It does not matter how slowly you go as long as you do not stop.</p>\n</blockquote>\n\n<p>I also love the concept of positive thinking, and <q cite="http://example.com/affirmationsforpositivethinking">The Need To Eliminate Negative Self Talk</q> (as mentioned in <a href="http://example.com/affirmationsforpositivethinking"><cite>Affirmations for Positive Thinking</cite></a>.)</p>';
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
Abbreviations
-------------
Another fairly common element you'll meet when looking around the Web is `<abbr>` β this is used to wrap around an abbreviation or acronym. When including either, provide a full expansion of the term in plain text on first use, along with the `<abbr>` to mark up the abbreviation. This provides a hint to user agents on how to announce/display the content while informing all users what the abbreviation means.
If providing the expansion in addition to the abbreviation makes little sense, and the abbreviation or acronym is a fairly shortened term, provide the full expansion of the term as the value of `title` attribute:
### Abbreviation example
Let's look at an example.
```html
<p>
We use <abbr>HTML</abbr>, Hypertext Markup Language, to structure our web
documents.
</p>
<p>
I think <abbr title="Reverend">Rev.</abbr> Green did it in the kitchen with
the chainsaw.
</p>
```
These will come out looking something like this:
**Note:** Earlier versions of html also included support for the `<acronym>` element, but it was removed from the HTML spec in favor of using `<abbr>` to represent both abbreviations and acronyms. `<acronym>` should not be used.
### Active learning: marking up an abbreviation
For this simple active learning assignment, we'd like you to mark up an abbreviation. You can use our sample below, or replace it with one of your own.
```
<h2>Live output</h2>
<div class="output" style="min-height: 50px;"></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="input" style="min-height: 50px; width: 95%">
<p>NASA, the National Aeronautics and Space Administration, sure does some exciting work.</p>
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```
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;
}
```
```
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;
function updateCode() {
output.innerHTML = textarea.value;
}
const htmlSolution =
"<p><abbr>NASA</abbr>, the National Aeronautics and Space Administration, sure does some exciting work.</p>";
let solutionEntry = htmlSolution;
reset.addEventListener("click", () => {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = htmlSolution;
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();
});
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();
};
```
Marking up contact details
--------------------------
HTML has an element for marking up contact details β `<address>`. This wraps around your contact details, for example:
```html
<address>Chris Mills, Manchester, The Grim North, UK</address>
```
It could also include more complex markup, and other forms of contact information, for example:
```html
<address>
<p>
Chris Mills<br />
Manchester<br />
The Grim North<br />
UK
</p>
<ul>
<li>Tel: 01234 567 890</li>
<li>Email: [email protected]</li>
</ul>
</address>
```
Note that something like this would also be OK, if the linked page contained the contact information:
```html
<address>
Page written by <a href="../authors/chris-mills/">Chris Mills</a>.
</address>
```
**Note:** The `<address>` element should only be used to provide contact information for the document contained with the nearest `<article>` or `<body>` element. It would be correct to use it in the footer of a site to include the contact information of the entire site, or inside an article for the contact details of the author, but not to mark up a list of addresses unrelated to the content of that page.
Superscript and subscript
-------------------------
You will occasionally need to use superscript and subscript when marking up items like dates, chemical formulae, and mathematical equations so they have the correct meaning. The `<sup>` and `<sub>` elements handle this job. For example:
```html
<p>My birthday is on the 25<sup>th</sup> of May 2001.</p>
<p>
Caffeine's chemical formula is
C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub>.
</p>
<p>If x<sup>2</sup> is 9, x must equal 3 or -3.</p>
```
The output of this code looks like so:
Representing computer code
--------------------------
There are a number of elements available for marking up computer code using HTML:
* `<code>`: For marking up generic pieces of computer code.
* `<pre>`: For retaining whitespace (generally code blocks) β if you use indentation or excess whitespace inside your text, browsers will ignore it and you will not see it on your rendered page. If you wrap the text in `<pre></pre>` tags however, your whitespace will be rendered identically to how you see it in your text editor.
* `<var>`: For specifically marking up variable names.
* `<kbd>`: For marking up keyboard (and other types of) input entered into the computer.
* `<samp>`: For marking up the output of a computer program.
Let's look at examples of these elements and how they're used to represent computer code.
If you want to see the full file, take a look at the other-semantics.html sample file.
You can download the file and open it in your browser to see for yourself, but here is a snippet of the code:
```html
<pre><code>const para = document.querySelector('p');
para.onclick = function() {
alert('Owww, stop poking me!');
}</code></pre>
<p>
You shouldn't use presentational elements like <code><font></code> and
<code><center></code>.
</p>
<p>
In the above JavaScript example, <var>para</var> represents a paragraph
element.
</p>
<p>Select all the text with <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>A</kbd>.</p>
<pre>$ <kbd>ping mozilla.org</kbd>
<samp>PING mozilla.org (63.245.215.20): 56 data bytes
64 bytes from 63.245.215.20: icmp_seq=0 ttl=40 time=158.233 ms</samp></pre>
```
The above code will look like so:
Marking up times and dates
--------------------------
HTML also provides the `<time>` element for marking up times and dates in a machine-readable format. For example:
```html
<time datetime="2016-01-20">20 January 2016</time>
```
Why is this useful? Well, there are many different ways that humans write down dates. The above date could be written as:
* 20 January 2016
* 20th January 2016
* Jan 20 2016
* 20/01/16
* 01/20/16
* The 20th of next month
* 20e Janvier 2016
* 2016 εΉ΄ 1 ζ 20 ζ₯
* And so on
But these different forms cannot be easily recognized by computers β what if you wanted to automatically grab the dates of all events in a page and insert them into a calendar? The `<time>` element allows you to attach an unambiguous, machine-readable time/date for this purpose.
The basic example above just provides a simple machine readable date, but there are many other options that are possible, for example:
```html
<!-- Standard simple date -->
<time datetime="2016-01-20">20 January 2016</time>
<!-- Just year and month -->
<time datetime="2016-01">January 2016</time>
<!-- Just month and day -->
<time datetime="01-20">20 January</time>
<!-- Just time, hours and minutes -->
<time datetime="19:30">19:30</time>
<!-- You can do seconds and milliseconds too! -->
<time datetime="19:30:01.856">19:30:01.856</time>
<!-- Date and time -->
<time datetime="2016-01-20T19:30">7.30pm, 20 January 2016</time>
<!-- Date and time with timezone offset -->
<time datetime="2016-01-20T19:30+01:00">
7.30pm, 20 January 2016 is 8.30pm in France
</time>
<!-- Calling out a specific week number -->
<time datetime="2016-W04">The fourth week of 2016</time>
```
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Advanced HTML text.
Summary
-------
That marks the end of our study of HTML text semantics. Bear in mind that what you have seen during this course is not an exhaustive list of HTML text elements β we wanted to try to cover the essentials, and some of the more common ones you will see in the wild, or at least might find interesting. To find way more HTML elements, you can take a look at our HTML element reference (the Inline text semantics section would be a great place to start). In the next article, we'll look at the HTML elements you'd use to structure the different parts of an HTML document.
* Previous
* Overview: Introduction to HTML
* Next |
Creating hyperlinks - Learn web development | Creating hyperlinks
===================
* Previous
* Overview: Introduction to HTML
* Next
Hyperlinks are really important β they are what makes the Web *a web*.
This article shows the syntax required to make a link, and discusses link best practices.
| | |
| --- | --- |
| Prerequisites: |
Basic HTML familiarity, as covered in
Getting started with HTML. HTML text formatting, as covered in
HTML text fundamentals.
|
| Objective: |
To learn how to implement a hyperlink effectively, and link multiple
files together.
|
What is a hyperlink?
--------------------
Hyperlinks are one of the most exciting innovations the Web has to offer.
They've been a feature of the Web since the beginning, and are what makes the Web *a web.*
Hyperlinks allow us to link documents to other documents or resources, link to specific parts of documents, or make apps available at a web address.
Almost any web content can be converted to a link so that when clicked or otherwise activated the web browser goes to another web address (URL).
**Note:** A URL can point to HTML files, text files, images, text documents, video and audio files, or anything else that lives on the Web.
If the web browser doesn't know how to display or handle the file, it will ask you if you want to open the file (in which case the duty of opening or handling the file is passed to a suitable native app on the device) or download the file (in which case you can try to deal with it later on).
For example, the BBC homepage contains many links that point not only to multiple news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools), and more.
![front page of bbc.co.uk, showing many news items, and navigation menu functionality](/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks/updated-bbc-website.png)
Anatomy of a link
-----------------
A basic link is created by wrapping the text or other content inside an `<a>` element and using the `href` attribute, also known as a **Hypertext Reference**, or **target**, that contains the web address.
```html
<p>
I'm creating a link to
<a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
</p>
```
This gives us the following result:
I'm creating a link to the Mozilla homepage.
### Block level links
As mentioned before, almost any content can be made into a link, even block-level elements.
If you want to make a heading element a link then wrap it in an anchor (`<a>`) element as shown in the following code snippet:
```html
<a href="https://developer.mozilla.org/en-US/">
<h1>MDN Web Docs</h1>
</a>
<p>
Documenting web technologies, including CSS, HTML, and JavaScript, since 2005.
</p>
```
This turns the heading into a link:
### Image links
If you have an image you want to make into a link, use the `<a>` element to wrap the image file referenced with the `<img>` element. The example below uses a relative path to reference a locally stored SVG image file.
```
img {
height: 100px;
width: 150px;
border: 1px solid gray;
}
```
```html
<a href="https://developer.mozilla.org/en-US/">
<img src="mdn\_logo.svg" alt="MDN Web Docs" />
</a>
```
This makes the MDN logo a link:
**Note:** You'll find out more about using images on the Web in a future article.
### Adding supporting information with the title attribute
Another attribute you may want to add to your links is `title`.
The title contains additional information about the link, such as which kind of information the page contains, or things to be aware of on the website.
```html
<p>
I'm creating a link to
<a
href="https://www.mozilla.org/en-US/"
title="The best place to find more information about Mozilla's
mission and how to contribute">
the Mozilla homepage</a>.
</p>
```
This gives us the following result and hovering over the link displays the title as a tooltip:
**Note:** A link title is only revealed on mouse hover, which means that people relying on keyboard controls or touchscreens to navigate web pages will have difficulty accessing title information.
If a title's information is truly important to the usability of the page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.
### Active learning: creating your own example link
Create an HTML document using your local code editor and our getting started template.
* Inside the HTML body, add one or more paragraphs or other types of content you already know about.
* Change some of the content into links.
* Include title attributes.
A quick primer on URLs and paths
--------------------------------
To fully understand link targets, you need to understand URLs and file paths. This section gives you the information you need to achieve this.
A URL, or Uniform Resource Locator is a string of text that defines where something is located on the Web. For example, Mozilla's English homepage is located at `https://www.mozilla.org/en-US/`.
URLs use paths to find files. Paths specify where the file you're interested in is located in the filesystem. Let's look at an example of a directory structure, see the creating-hyperlinks directory.
![A simple directory structure. The parent directory is called creating-hyperlinks and contains two files called index.html and contacts.html, and two directories called projects and pdfs, which contain an index.html and a project-brief.pdf file, respectively](/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks/simple-directory.png)
The **root** of this directory structure is called `creating-hyperlinks`. When working locally with a website, you'll have one directory that contains the entire site. Inside the **root**, we have an `index.html` file and a `contacts.html`. In a real website, `index.html` would be our home page or landing page (a web page that serves as the entry point for a website or a particular section of a website.).
There are also two directories inside our root β `pdfs` and `projects`. These each have a single file inside them β a PDF (`project-brief.pdf`) and an `index.html` file, respectively. Note that you can have two `index.html` files in one project, as long as they're in different filesystem locations. The second `index.html` would perhaps be the main landing page for project-related information.
* **Same directory**: If you wanted to include a hyperlink inside `index.html` (the top level `index.html`) pointing to `contacts.html`, you would specify the filename that you want to link to, because it's in the same directory as the current file. The URL you would use is `contacts.html`:
```html
<p>
Want to contact a specific staff member? Find details on our
<a href="contacts.html">contacts page</a>.
</p>
```
* **Moving down into subdirectories**: If you wanted to include a hyperlink inside `index.html` (the top level `index.html`) pointing to `projects/index.html`, you would need to go down into the `projects` directory before indicating the file you want to link to.
This is done by specifying the directory's name, then a forward slash, then the name of the file. The URL you would use is `projects/index.html`:
```html
<p>Visit my <a href="projects/index.html">project homepage</a>.</p>
```
* **Moving back up into parent directories**: If you wanted to include a hyperlink inside `projects/index.html` pointing to `pdfs/project-brief.pdf`, you'd have to go up a directory level, then back down into the `pdfs` directory.
To go up a directory, use two dots β `..` β so the URL you would use is `../pdfs/project-brief.pdf`:
```html
<p>A link to my <a href="../pdfs/project-brief.pdf">project brief</a>.</p>
```
**Note:** You can combine multiple instances of these features into complex URLs, if needed, for example: `../../../complex/path/to/my/file.html`.
### Document fragments
It's possible to link to a specific part of an HTML document, known as a **document fragment**, rather than just to the top of the document.
To do this you first have to assign an `id` attribute to the element you want to link to.
It normally makes sense to link to a specific heading, so this would look something like the following:
```html
<h2 id="Mailing\_address">Mailing address</h2>
```
Then to link to that specific `id`, you'd include it at the end of the URL, preceded by a hash/pound symbol (`#`), for example:
```html
<p>
Want to write us a letter? Use our
<a href="contacts.html#Mailing\_address">mailing address</a>.
</p>
```
You can even use the document fragment reference on its own to link to *another part of the current document*:
```html
<p>
The <a href="#Mailing\_address">company mailing address</a> can be found at the
bottom of this page.
</p>
```
### Absolute versus relative URLs
Two terms you'll come across on the Web are **absolute URL** and **relative URL:**
**absolute URL**: Points to a location defined by its absolute location on the web, including protocol and domain name.
For example, if an `index.html` page is uploaded to a directory called `projects` that sits inside the **root** of a web server, and the website's domain is `https://www.example.com`, the page would be available at `https://www.example.com/projects/index.html` (or even just `https://www.example.com/projects/`, as most web servers just look for a landing page such as `index.html` to load if it isn't specified in the URL.)
An absolute URL will always point to the same location, no matter where it's used.
**relative URL**: Points to a location that is *relative* to the file you are linking from, more like what we looked at in the previous section.
For example, if we wanted to link from our example file at `https://www.example.com/projects/index.html` to a PDF file in the same directory, the URL would just be the filename β `project-brief.pdf` β no extra information needed. If the PDF was available in a subdirectory inside `projects` called `pdfs`, the relative link would be `pdfs/project-brief.pdf` (the equivalent absolute URL would be `https://www.example.com/projects/pdfs/project-brief.pdf`.)
A relative URL will point to different places depending on the actual location of the file you refer from β for example if we moved our `index.html` file out of the `projects` directory and into the **root** of the website (the top level, not in any directories), the `pdfs/project-brief.pdf` relative URL link inside it would now point to a file located at `https://www.example.com/pdfs/project-brief.pdf`, not a file located at `https://www.example.com/projects/pdfs/project-brief.pdf`.
Of course, the location of the `project-brief.pdf` file and `pdfs` folder won't suddenly change because you moved the `index.html` file β this would make your link point to the wrong place, so it wouldn't work if clicked on. You need to be careful!
Link best practices
-------------------
There are some best practices to follow when writing links. Let's look at these now.
### Use clear link wording
It's easy to throw links up on your page. That's not enough. We need to make our links *accessible* to all readers, regardless of their current context and which tools they prefer. For example:
* Screen reader users like jumping around from link to link on the page, and reading links out of context.
* Search engines use link text to index target files, so it is a good idea to include keywords in your link text to effectively describe what is being linked to.
* Visual readers skim over the page rather than reading every word, and their eyes will be drawn to page features that stand out, like links. They will find descriptive link text useful.
Let's look at a specific example:
**Good** link text: Download Firefox
```html
<p><a href="https://www.mozilla.org/firefox/">Download Firefox</a></p>
```
**Bad** link text: Click here to download Firefox
```html
<p>
<a href="https://www.mozilla.org/firefox/">Click here</a> to download Firefox
</p>
```
Other tips:
* Don't repeat the URL as part of the link text β URLs look ugly, and sound even uglier when a screen reader reads them out letter by letter.
* Don't say "link" or "links to" in the link text β it's just noise. Screen readers tell people there's a link.
Visual users will also know there's a link, because links are generally styled in a different color and underlined (this convention generally shouldn't be broken, as users are used to it).
* Keep your link text as short as possible β this is helpful because screen readers need to interpret the entire link text.
* Minimize instances where multiple copies of the same text are linked to different places.
This can cause problems for screen reader users, if there's a list of links out of context that are labeled "click here", "click here", "click here".
### Linking to non-HTML resources β leave clear signposts
When linking to a resource that will be downloaded (like a PDF or Word document), streamed (like video or audio), or has another potentially unexpected effect (opens a popup window), you should add clear wording to reduce any confusion.
For example:
* If you're on a low bandwidth connection, click a link, and then a multiple megabyte download starts unexpectedly.
Let's look at some examples, to see what kind of text can be used here:
```html
<p>
<a href="https://www.example.com/large-report.pdf">
Download the sales report (PDF, 10MB)
</a>
</p>
<p>
<a href="https://www.example.com/video-stream/" target="\_blank">
Watch the video (stream opens in separate tab, HD quality)
</a>
</p>
```
### Use the download attribute when linking to a download
When you are linking to a resource that's to be downloaded rather than opened in the browser, you can use the `download` attribute to provide a default save filename. Here's an example with a download link to the latest Windows version of Firefox:
```html
<a
href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-US"
download="firefox-latest-64bit-installer.exe">
Download Latest Firefox for Windows (64-bit) (English, US)
</a>
```
Active learning: creating a navigation menu
-------------------------------------------
For this exercise, we'd like you to link some pages together with a navigation menu to create a multipage website. This is one common way in which a website is created β the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up.
You'll need to make local copies of the following four pages, all in the same directory. For a complete file list, see the navigation-menu-start directory:
* index.html
* projects.html
* pictures.html
* social.html
You should:
1. Add an unordered list in the indicated place on one page that includes the names of the pages to link to.
A navigation menu is usually just a list of links, so this is semantically OK.
2. Change each page name into a link to that page.
3. Copy the navigation menu across to each page.
4. On each page, remove just the link to that same page β it's confusing and unnecessary for a page to include a link to itself.
And, the lack of a link acts a good visual reminder of which page you are currently on.
The finished example should look similar to the following page:
![An example of a simple HTML navigation menu, with home, pictures, projects, and social menu items](/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks/navigation-example.png)
**Note:** If you get stuck, or aren't sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer.
Email links
-----------
It's possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page.
This is done using the `<a>` element and the `mailto:` URL scheme.
In its most basic and commonly used form, a `mailto:` link indicates the email address of the intended recipient. For example:
```html
<a href="mailto:[email protected]">Send email to nowhere</a>
```
This results in a link that looks like this: Send email to nowhere.
In fact, the email address is optional. If you omit it and your `href` is "mailto:", a new outgoing email window will be opened by the user's email client with no destination address.
This is often useful as "Share" links that users can click to send an email to an address of their choosing.
### Specifying details
In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the `mailto` URL you provide.
The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email).
Each field and its value is specified as a query term.
Here's an example that includes a cc, bcc, subject and body:
```html
<a
href="mailto:[email protected][email protected]&[email protected]&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email">
Send mail with cc, bcc, subject and body
</a>
```
**Note:** The values of each field must be URL-encoded with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped.
Also, note the use of the question mark (`?`) to separate the main URL from the field values, and ampersands (&) to separate each field in the `mailto:` URL.
This is standard URL query notation.
Read The GET method to understand what URL query notation is more commonly used for.
Here are a few other sample `mailto` URLs:
* mailto:
* mailto:[email protected]
* mailto:[email protected],[email protected]
* mailto:[email protected][email protected]
* mailto:[email protected][email protected]&subject=This%20is%20the%20subject
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: Links.
Summary
-------
That's it for links, for now anyway! You'll return to links later on in the course when you start to look at styling them. Next up for HTML, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful β Advanced text formatting is your next stop.
* Previous
* Overview: Introduction to HTML
* Next |
JavaScript performance optimization - Learn web development | JavaScript performance optimization
===================================
* Previous
* Overview: Performance
* Next
It is very important to consider how you are using JavaScript on your websites and think about how to mitigate any performance issues that it might be causing. While images and video account for over 70% of the bytes downloaded for the average website, byte per byte, JavaScript has a greater potential for negative performance impact β it can significantly impact download times, rendering performance, and CPU and battery usage. This article introduces tips and techniques for optimizing JavaScript to enhance the performance of your website.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, and basic knowledge of
client-side web technologies.
|
| Objectives: |
To learn about the effects of JavaScript on web performance
and how to mitigate or fix related issues.
|
To optimize or not to optimize
------------------------------
The first question you should answer before starting to optimize your code is "what do I need to optimize?". Some of the tips and techniques discussed below are good practices that will benefit just about any web project, whereas some are only needed in certain situations. Trying to apply all these techniques everywhere is probably unnecessary, and may be a waste of your time. You should figure out what performance optimizations are actually needed in each project.
To do this, you need to measure the performance of your site. As the previous link shows, there are several different ways to measure performance, some involving sophisticated performance APIs. The best way to get started however, is to learn how to use tools such as built-in browser network and performance tools, to see what parts of the page load are taking a long time and need optimizing.
Optimizing JavaScript downloads
-------------------------------
The most performant, least blocking JavaScript you can use is JavaScript that you don't use at all. You should use as little JavaScript as possible. Some tips to bear in mind:
* **You don't always need a framework**: You might be familiar with using a JavaScript framework. If you are experienced and confident with using this framework, and like all of the tooling it provides, then it might be your go-to tool for building most projects. However, frameworks are JavaScript-heavy. If you are creating a fairly static experience with few JavaScript requirements, you probably don't need that framework. You might be able to implement what you need using a few lines of standard JavaScript.
* **Consider a simpler solution**: You might have a flashy, interesting solution to implement, but consider whether your users will appreciate it. Would they prefer something simpler?
* **Remove unused code:** This may sound obvious, but it is surprising how many developers forget to clean up unused functionality that was added during the development process. You need to be careful and deliberate about what is added and removed. All script gets parsed, whether it is used or not; therefore, a quick win to speed up downloads would be to get rid of any functionality not being used. Consider also that often you will only use a small amount of the functionality available in a framework. Is it possible to create a custom build of the framework that only contains the part that you need?
* **Consider built-in browser features**: It might be that you can use a feature the browser already has, rather than creating your own via JavaScript. For example:
+ Use built-in client-side form validation.
+ Use the browser's own `<video>` player.
+ Use CSS animations instead of a JavaScript animation library (see also Handling animations).
You should also split your JavaScript into multiple files representing critical and non-critical parts. JavaScript modules allow you to do this more efficiently than just using separate external JavaScript files.
Then you can optimize these smaller files. Minification reduces the number of characters in your file, thereby reducing the number of bytes or weight of your JavaScript. Gzipping compresses the file further and should be used even if you don't minify your code. Brotli is similar to Gzip, but generally outperforms Gzip compression.
You can split and optimize your code manually, but often a module bundler like Webpack will do a better job of this.
Handling parsing and execution
------------------------------
Before looking at the tips contained in this section, it is important to talk about *where* in the process of browser page rendering JavaScript is handled. When a web page is loaded:
1. The HTML is generally parsed first, in the order in which it appears on the page.
2. Whenever CSS is encountered, it is parsed to understand the styles that need to be applied to the page. During this time, linked assets such as images and web fonts start to be fetched.
3. Whenever JavaScript is encountered, the browser parses, evaluates, and runs it against the page.
4. Slightly later on, the browser works out how each HTML element should be styled, given the CSS applied to it.
5. The styled result is then painted to the screen.
**Note:** This is a very simplified account of what happens, but it does give you an idea.
The key step here is Step 3. By default, JavaScript parsing and execution are render-blocking. This means that the browser blocks the parsing of any HTML that appears after the JavaScript is encountered, until the script has been handled. As a result, styling and painting are blocked too. This means that you need to think carefully not only about what you are downloading, but also about when and how that code is being executed.
The next few sections provide useful techniques for optimizing the parsing and execution of your JavaScript.
Loading critical assets as soon as possible
-------------------------------------------
If a script is really important and you are concerned that it is affecting performance by not being loaded quickly enough, you can load it inside the `<head>` of the document:
```html
<head>
...
<script src="main.js"></script>
...
</head>
```
This works OK, but is render-blocking. A better strategy is to use `rel="preload"` to create a preloader for critical JavaScript:
```html
<head>
...
<!-- Preload a JavaScript file -->
<link rel="preload" href="important-js.js" as="script" />
<!-- Preload a JavaScript module -->
<link rel="modulepreload" href="important-module.js" />
...
</head>
```
The preload `<link>` fetches the JavaScript as soon as possible, without blocking rendering. You can then use it wherever you want in your page:
```html
<!-- Include this wherever makes sense -->
<script src="important-js.js"></script>
```
or inside your script, in the case of a JavaScript module:
```js
import { function } from "important-module.js";
```
**Note:** Preloading does not guarantee that the script will be loaded by the time you include it, but it does mean that it will start being downloaded sooner. Render-blocking time will still be shortened, even if it is not completely removed.
Deferring execution of non-critical JavaScript
----------------------------------------------
On the other hand, you should aim to defer parsing and execution of non-critical JavaScript to later on, when it is needed. Loading it all up-front blocks rendering unnecessarily.
First of all, you can add the `async` attribute to your `<script>` elements:
```html
<head>
...
<script async src="main.js"></script>
...
</head>
```
This causes the script to be fetched in parallel with the DOM parsing, so it will be ready at the same time and won't block rendering.
**Note:** There is another attribute, `defer`, which causes the script to be executed after the document has been parsed, but before firing the `DOMContentLoaded` event. This has a similar effect to `async`.
You could also just not load the JavaScript at all until an event occurs when it is needed. This could be done via DOM scripting, for example:
```js
const scriptElem = document.createElement("script");
scriptElem.src = "index.js";
scriptElem.addEventListener("load", () => {
// Run a function contained within index.js once it has definitely loaded
init();
});
document.head.append(scriptElem);
```
JavaScript modules can be dynamically loaded using the `import()` function:
```js
import("./modules/myModule.js").then((module) => {
// Do something with the module
});
```
Breaking down long tasks
------------------------
When the browser runs your JavaScript, it will organize the script into tasks that are run sequentially, such as making fetch requests, driving user interactions and input through event handlers, running JavaScript-driven animation, and so on.
Most of this happens on the main thread, with exceptions including JavaScript that runs in Web Workers. The main thread can run only one task at a time.
When a single task takes longer than 50 ms to run, it is classified as a long task. If the user attempts to interact with the page or an important UI update is requested while a long task is running, their experience will be affected. An expected response or visual update will be delayed, resulting in the UI appearing sluggish or unresponsive.
To mitigate this issue, you need to break down long tasks into smaller tasks. This gives the browser more chances to perform vital user interaction handling or UI rendering updates β the browser can potentially do them between each smaller task, rather than only before or after the long task. In your JavaScript, you might do this by breaking your code into separate functions. This also makes sense for several other reasons, such as easier maintenance, debugging, and writing tests.
For example:
```js
function main() {
a();
b();
c();
d();
e();
}
```
However, this kind of structure doesn't help with main thread blocking. Since all the five functions are being run inside one main function, the browser runs them all as a single long task.
To handle this, we tend to run a "yield" function periodically to get the code to *yield to the main thread*. This means that our code is split into multiple tasks, between the execution of which the browser is given the opportunity to handle high-priority tasks such as updating the UI. A common pattern for this function uses `setTimeout()` to postpone execution into a separate task:
```js
function yield() {
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
```
This can be used inside a task runner pattern like so, to yield to the main thread after each task has been run:
```js
async function main() {
// Create an array of functions to run
const tasks = [a, b, c, d, e];
// Loop over the tasks
while (tasks.length > 0) {
// Shift the first task off the tasks array
const task = tasks.shift();
// Run the task
task();
// Yield to the main thread
await yield();
}
}
```
To improve this further, we can use `navigator.scheduling.isInputPending()` to run the `yield()` function only when the user is attempting to interact with the page:
```js
async function main() {
// Create an array of functions to run
const tasks = [a, b, c, d, e];
while (tasks.length > 0) {
// Yield to a pending user input
if (navigator.scheduling.isInputPending()) {
await yield();
} else {
// Shift the first task off the tasks array
const task = tasks.shift();
// Run the task
task();
}
}
}
```
This allows you to avoid blocking the main thread when the user is actively interacting with the page, potentially providing a smoother user experience. However, by only yielding when necessary, we can continue running the current task when there are no user inputs to process. This also avoids tasks being placed at the back of the queue behind other non-essential browser-initiated tasks that were scheduled after the current one.
Handling JavaScript animations
------------------------------
Animations can improve perceived performance, making interfaces feel snappier and making users feel like progress is being made when they are waiting for a page to load (loading spinners, for example). However, larger animations and a higher number of animations will naturally require more processing power to handle, which can degrade performance.
The most obvious piece of animation advice is to use less animations β cut out any non-essential animations, or consider giving your users a preference they can set to turn off animations, for example if they are using a low-powered device or a mobile device with limited battery power.
For essential DOM animations, you are advised to use CSS animations where possible, rather than JavaScript animations (the Web Animations API provides a way to directly hook into CSS animations using JavaScript). Using the browser to directly perform DOM animations rather than manipulating inline styles using JavaScript is much faster and more efficient. See also CSS performance optimization > Handling animations.
For animations that can't be handled in JavaScript, for example, animating an HTML `<canvas>`, you are advised to use `Window.requestAnimationFrame()` rather than older options such as `setInterval()`. The `requestAnimationFrame()` method is specially designed for handling animation frames efficiently and consistently, for a smooth user experience. The basic pattern looks like this:
```js
function loop() {
// Clear the canvas before drawing the next frame of the animation
ctx.fillStyle = "rgb(0 0 0 / 25%)";
ctx.fillRect(0, 0, width, height);
// Draw objects on the canvas and update their positioning data
// ready for the next frame
for (const ball of balls) {
ball.draw();
ball.update();
}
// Call requestAnimationFrame to run the loop() function again
// at the right time to keep the animation smooth
requestAnimationFrame(loop);
}
// Call the loop() function once to set the animation running
loop();
```
You can find a nice introduction to canvas animations at Drawing graphics > Animations, and a more in-depth example at Object building practice. You can also find a full set of canvas tutorials at Canvas tutorial.
Optimizing event performance
----------------------------
Events can be expensive for the browser to track and handle, especially when you are running an event continuously. For example, you might be tracking the position of the mouse using the `mousemove` event to check whether it is still inside a certain area of the page:
```js
function handleMouseMove() {
// Do stuff while mouse pointer is inside elem
}
elem.addEventListener("mousemove", handleMouseMove);
```
You might be running a `<canvas>` game in your page. While the mouse is inside the canvas, you will want to constantly check for mouse movement and cursor position and update the game state β including the score, the time, the position of all the sprites, collision detection information, etc. Once the game is over, you will no longer need to do all that, and in fact, it will be a waste of processing power to keeping listening for that event.
It is, therefore, a good idea to remove event listeners that are no longer needed. This can be done using `removeEventListener()`:
```js
elem.removeEventListener("mousemove", handleMouseMove);
```
Another tip is to use event delegation wherever possible. When you have some code to run in response to a user interacting with any one of a large number of child elements, you can set an event listener on their parent. Events fired on any child element will bubble up to their parent, so you don't need to set the event listener on each child individually. Less event listeners to keep track of means better performance.
See Event delegation for more details and a useful example.
Tips for writing more efficient code
------------------------------------
There are several general best practices that will make your code run more efficiently.
* **Reduce DOM manipulation**: Accessing and updating the DOM is computationally expensive, so you should minimize the amount that your JavaScript does, especially when performing constant DOM animation (see Handling JavaScript animations above).
* **Batch DOM changes**: For essential DOM changes, you should batch them into groups that get done together, rather than just firing off each individual change as it occurs. This can reduce the amount of work the browser is doing in real terms, but also improve perceived performance. It can make the UI look smoother to get several updates out of the way in one go, rather than constantly making small updates. A useful tip here is β when you have a large chunk of HTML to add to the page, build the entire fragment first (typically inside a `DocumentFragment`) and then append it all to the DOM in one go, rather than appending each item separately.
* **Simplify your HTML**: The simpler your DOM tree is, the faster it can be accessed and manipulated with JavaScript. Think carefully about what your UI needs, and remove unnecessary cruft.
* **Reduce the amount of looped code**: Loops are expensive, so reduce the amount of loop usage in your code wherever possible. In cases where loops are unavoidable:
+ Avoid running the full loop when it is unnecessary, using `break` or `continue` statements as appropriate. For example, if you are searching arrays for a specific name, you should break out of the loop once the name is found; there is no need to run further loop iterations:
js
```js
function processGroup(array) {
const toFind = "Bob";
for (let i = 0; i < array.length - 1; i++) {
if (array[i] === toFind) {
processMatchingArray(array);
break;
}
}
}
```
+ Do work that is only needed once outside the loop. This may sound a bit obvious, but it is easy to overlook. Take the following snippet, which fetches a JSON object containing data to be processed in some way. In this case the `fetch()` operation is being done on every iteration of the loop, which is a waste of computing power. Lines 3 and 4 could be moved outside the loop, so the network fetch is only being done once.
js
```js
async function returnResults(number) {
for (let i = 0; i < number; i++) {
const response = await fetch(`/results?number=${number}`);
const results = await response.json();
processResult(results[i]);
}
}
```
* **Run computation off the main thread**: Earlier on we talked about how JavaScript generally runs tasks on the main thread, and how long operations can block the main thread, potentially leading to bad UI performance. We also showed how to break long tasks up into smaller tasks, mitigating this problem. Another way to handle such problems is to move tasks off the main thread altogether. There are a few ways to achieve this:
+ Use asynchronous code: Asynchronous JavaScript is basically JavaScript that does not block the main thread. Asynchronous APIs tend to handle operations such as fetching resources from the network, accessing a file on the local file system, or opening a stream to a user's web cam. Because those operations could take a long time, it would be bad to just block the main thread while we wait for them to complete. Instead, the browser executes those functions, keeps the main thread running subsequent code, and those functions will return results once they are available *at some point in the future*. Modern asynchronous APIs are `Promise`-based, which is a JavaScript language feature designed for handling asynchronous operations. It is possible to write your own Promise-based functions if you have functionality that would benefit from being run asynchronously.
+ Run computation in web workers: Web Workers are a mechanism allowing you to open a separate thread to run a chunk of JavaScript in, so that it won't block the main thread. Workers do have some major restrictions, the biggest being that you can't do any DOM scripting inside a worker. You can do most other things, and workers can send and receive messages to and from the main thread. The main use case for workers is if you have a lot of computation to do, and you don't want it to block the main thread. Do that computation in a worker, wait for the result, and send it back to the main thread when it is ready.
+ **Use WebGPU**: WebGPU is a browser API that allows web developers to use the underlying system's GPU (Graphics Processing Unit) to carry out high-performance computations and draw complex images that can be rendered in the browser. It is fairly complex, but it can provide even better performance benefits than web workers.
See also
--------
* Optimize long tasks on web.dev (2022)
* Canvas tutorial
* Previous
* Overview: Performance
* Next |
The "why" of web performance - Learn web development | The "why" of web performance
============================
* Overview: Performance
* Next
Web performance is all about making websites fast, including making slow processes *seem* fast. This article provides an introduction into why web performance is important to site visitors and for your business goals.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, and basic knowledge of
client-side web technologies.
|
| Objective: |
To gain basic familiarity of why web performance is important for good
user experience.
|
Web performance refers to how quickly site content **loads** and **renders** in a web browser, and how well it responds to user interaction. Bad performing sites are slow to display and slow to respond to input. Bad performing sites increase site abandonment. At its worst, bad performance causes content to be completely inaccessible. A good goal for web performance is for users to not notice performance. While an individual's perception of site performance is subjective, loading and rendering can be measured. Good performance may not be obvious to most site visitors, but most will immediately recognize a sluggish site. That is why we care.
Why care about performance?
---------------------------
Web performance β and its associated best practicesβare vital for your website visitors to have a good experience. In a sense, web performance can be considered a subset of web accessibility. With performance as with accessibility, you consider what device a site visitor is using to access the site and the device connection speed.
As an example, consider the loading experience of CNN.com, which at the time of this writing had over 400 HTTP requests with a file size of over 22.6MB.
* Imagine loading this on a desktop computer connected to a fibre optic network. This would seem relatively fast, and the file size would be largely irrelevant.
* Imagine loading that same site using tethered mobile data on a nine-year-old iPad while commuting home on public transportation. The same site will be slow to load, possibly verging on unusable depending on cell coverage. You might give up before it finishes loading.
* Imagine loading that same site on a $35 Huawei device in a rural India with limited coverage or no coverage. The site will be very slow to loadβif it loads at allβwith blocking scripts possibly timing out, and adverse CPU impact causing browser crashes if it does load.
A 22.6 MB site could take up to 83 seconds to load on a 3G network, with `DOMContentLoaded` (meaning the site's base HTML structure) at 31.86 seconds.
And it isn't just the time taken to download that is a major problem. A lot of countries still have internet connections that bill per megabyte. Our example 22.6 MB CNN.com experience would cost about 11% of the average Indian's daily wage to download. From a mobile device in Northwest Africa, it might cost two days of an average salary. And if this site were loaded on a US carrier's international roaming plan? The costs would make anyone cry. (See how much your site costs to download.)
### Improve conversion rates
Reducing the download and render time of a site improves conversion rates and user retention.
A **conversion rate** is the rate at which site visitors perform a measured or desired action. For example, this might be making a purchase, reading an article, or subscribing to a newsletter. The action being measured as the conversion rate depends on the website's business goals.
Performance impacts conversion; improving web performance improves conversion. Site visitors expect a site to load in two seconds or less; sometimes even less on mobile (where it generally takes longer). These same site visitors begin abandoning slow sites at 3 seconds.
The speed at which a site loads is one factor. If the site is slow to react to user interaction, or appears janky, this causes site visitors to lose interest and trust.
Here's some real-world examples of performance improvements:
* Tokopedia reduced render time from 14s to 2s for 3G connections and saw a 19% increase in visitors, 35% increase in total sessions, 7% increase in new users, 17% increase in active users and 16% increase in sessions per user.
* Rebuilding Pinterest pages for performance resulted in a 40% decrease in wait time, a 15% increase in SEO traffic and a 15% increase in conversion rate to signup.
To build websites and applications people want to use; to attract and retain site visitors, you need to create an accessible site that provides a good user experience. Building websites requires HTML, CSS, and JavaScript, typically including binary file types such as images and video. The decisions you make and the tools you choose as you build your site can greatly affect the performance of the finished work.
Good performance is an asset. Bad performance is a liability. Site speed directly affects bounce rates, conversion, revenue, user satisfaction, and search engine ranking. Performant sites have been shown to increase visitor retention and user satisfaction. Slow content has been shown to lead to site abandonment, with some visitors leaving to never return. Reducing the amount of data that passes between the client and the server lowers the costs to all parties. Reducing HTML/CSS/JavaScript and media file sizes reduces both the time to load and a site's power consumption (see performance budgets).
Tracking performance is important. Multiple factors, including network speed and device capabilities affect performance. There is no single performance metric; and differing business objectives may mean different metrics are more relevant to the goals of the site or the organization that it supports. How the performance of your site is perceived is user experience!
Conclusion
----------
Web performance is important for accessibility and also for other website metrics that serve the goals of an organization or business. Good or bad website performance correlates powerfully to user experience, as well as the overall effectiveness of most sites. This is why you should care about web performance.
* Overview: Performance
* Next |
The business case for web performance - Learn web development | The business case for web performance
=====================================
* Previous
* Overview: Performance
* Next
We've discussed the importance of web performance. You've learned what you need to do to optimize for web performance. But how do you convince your clients and/or management to prioritize and invest in performance? In this section, we discuss creating a clear business case to convince decision-makers to make the investment.
| | |
| --- | --- |
| Prerequisites: |
Basic knowledge of
client-side web technologies, and a basic understanding of
web performance optimization.
|
| Objective: |
To gain confidence in working with clients and management to get them to
make web performance a priority.
|
Making performance a business priority
--------------------------------------
We've discussed how prioritizing performance can improve user experience and therefore revenue. We know that not prioritizing web performance can result in a loss of business revenue. This article discusses how certain business metrics directly relate to a user's web performance experience and how to apply service design to boost the user's experiences of web performance. It highlights the importance of understanding how cumulative experiences impact conversion and retention rates.
### Performance budgets
Setting a web performance budget can help you make sure the team stays on track in keeping the site and help prevent regressions. A performance budget is a set of limits that are set to specify limits, such as the maximum number of HTTP requests allowed, the maximum total size of all the assets combined, the minimum allowable FPS on a specific device, etc., that must be maintained. The budget can be applied to a single file, a file type, all files loaded on a page, a specific metric, or a threshold over a period of time. The budget reflects reachable goals; whether they are time, quantity, or rule-based.
Defining and promoting a budget helps performance proponents advocate for good user experience against competing interests, such as marketing, sales, or even other developers that may want to add videos, 3rd party scripts, or even frameworks. Performance budgets help developer teams protect optimal performance for users while enabling the business to tap into new markets and deliver custom experiences.
### Key Performance Indicators
Setting key performance indicators (KPI) as objectives can highlight performance objectives that are also business objectives. KPIs can be both a set of important business metrics in measuring the impact of user experience and performance on the business's top line, and a way of demonstrating the benefits of prioritizing performance. Here are some KPIs to consider:
**Conversion Rate**
The percent of your traffic that takes an intended action, such as completing a purchase or signing up for a newsletter. When a business site is slow, it can prevent users from completing their intended task. This can lead to low conversion rates.
**Time on Site**
The average time that your users in aggregate spend on your site. When a site performs slowly, users are more likely to abandon the site prematurely which can lead to low time on site metrics.
**Net Promotion Score**
The net promoter score (NPS) is a metric for assessing customer-loyalty for a company's brand, product, or service. Poor user performance experiences can equate to poor brand reputation.
Setting conversion rate, time on site, and/or net promotion scores as KPIs give financial and other business goal value to the web performance efforts, and get help boost buy-in, with metrics to prove the efforts worth.
* Previous
* Overview: Performance |
What is web performance? - Learn web development | What is web performance?
========================
* Previous
* Overview: Performance
* Next
Web performance is all about making websites fast, including making slow processes *seem* fast. Does the site load quickly, allow the user to start interacting with it quickly, and offer reassuring feedback if something is taking time to load (e.g. a loading spinner)? Are scrolling and animations smooth? This article provides a brief introduction to objective, measurable web performance\*, looking at what technologies, techniques, and tools are involved in web optimization.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, and basic knowledge of
client-side web technologies.
|
| Objective: | To gain basic familiarity of what is involved with web performance. |
*\* versus subjective, perceived performance, covered in the next article*
What is web performance?
------------------------
Web performance is the objective measurement and perceived user experience of a website or application. This includes the following major areas:
* **Reducing overall load time**: How long does it take the files required to render the website to download on to the user's computer? This tends to be affected by latency, how big your files are, how many files there are, and other factors besides. A general strategy is to make your files as small as possible, reduce the number of HTTP requests made as much as possible, and employ clever loading techniques (such as preload) to make files available sooner.
* **Making the site usable as soon as possible**: This basically means loading your website assets in a sensible order so that the user can start to actually use it really quickly. Any other assets can continue to load in the background while the user gets on with primary tasks, and sometimes we only load assets when they are actually needed (this is called lazy loading). The measurement of how long it takes the site to get to a usable start after it has started loading is called time to interactive.
* **Smoothness and interactivity**: Does the application feel reliable and pleasurable to use? Is the scrolling smooth? Are buttons clickable? Are pop-ups quick to open up, and do they animate smoothly as they do so? There are a lot of best practices to consider in making apps feel smooth, for example using CSS animations rather than JavaScript for animation, and minimizing the number of repaints the UI requires due to changes in the DOM.
* **Perceived performance**: How fast a website seems to the user has a greater impact on user experience than how fast the website actually is. How a user perceives your performance is as important, or perhaps more important, than any objective statistic, but it's subjective, and not as readily measurable. Perceived performance is user perspective, not a metric. Even if an operation is going to take a long time (because of latency or whatever), it is possible to keep the user engaged while they wait by showing a loading spinner, or a series of useful hints and tips (or jokes, or whatever else you think might be appropriate). Such an approach is much better than just showing nothing, which will make it feel like it is taking a lot longer and possibly lead to your users thinking it is broken and giving up.
* **Performance measurements**: Web performance involves measuring the actual and perceived speeds of an application, optimizing where possible, and then monitoring the performance, to ensure that what you've optimized stays optimized. This involves a number of metrics (measurable indicators that can indicate success or failure) and tools to measure those metrics, which we will discuss throughout this module.
To summarize, many features impact performance including latency, application size, the number of DOM nodes, the number of resource requests made, JavaScript performance, CPU load, and more. It is important to minimize the loading and response times, and add additional features to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience.
**Note:** Web performance includes both objective measurements like time to load, frames per second, and time to interactive, and subjective experiences of how long it felt like it took the content to load.
How content is rendered
-----------------------
To effectively understand web performance, the issues behind it, and the major topic areas we mentioned above, you really should understand some specifics about how browsers work. This includes:
* **How the browser works**. When you request a URL and hit
`Enter`
/
`Return`
, the browser finds out where the server is that holds that website's files, establishes a connection to it, and requests the files. See Populating the page: how the browser works for a detailed overview.
* **Source order**. Your HTML index file's source order can significantly affect performance. The download of additional assets linked to from the index file is generally sequential, based on source order, but this can be manipulated and should definitely be optimized, realizing that some resources block additional downloads until their content is parsed and executed.
* **The critical path**. This is the process that the browser uses to construct the web document once the files have been downloaded from the server. The browser follows a well-defined set of steps, and optimizing the critical rendering path to prioritize the display of content that relates to the current user action will lead to significant improvements in content rendering time. See Critical rendering path for more information.
* The **document object model**. The document object model, or DOM, is a tree structure that represents the content and elements of your HTML as a tree of nodes. This includes all the HTML attributes and the relationships between the nodes. Extensive DOM manipulation after the pages has loaded (e.g., adding, deleting, or moving of nodes) can affect performance, so it is worth understanding how the DOM works, and how such issues can be mitigated. Find out more at Document Object Model.
* **Latency**. We mention this briefly earlier on, but in brief, latency is the time it takes for your website assets to travel from the server to a user's computer. There is overhead involved in establishing TCP and HTTP connections, and some unavoidable latency in pushing the request and response bytes back and forth across the network, but there are certain ways to reduce latency (e.g. reducing the number of HTTP request you make by downloading fewer files, using a CDN to make your site more universally performant across the world, and using HTTP/2 to serve files more efficiently from the server). You can read all about this topic at Understanding Latency.
Conclusion
----------
That's it for now; we hope our brief overview of the web performance topic helped you to get an idea of what it is all about, and made you excited to learn more. Next up we'll look at perceived performance, and how you can use some clever techniques to make some unavoidable performance hits appear less severe to the user, or disguise them completely.
* Previous
* Overview: Performance
* Next |
Multimedia: video - Learn web development | Multimedia: video
=================
* Previous
* Overview: Performance
* Next
As we learned in the previous section, media, namely images and video, account for over 70% of the bytes downloaded for the average website. We have already taken a look at optimizing images. This article looks at optimizing video to improve web performance.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, and basic knowledge of
client-side web technologies.
|
| Objective: |
To learn about the various video formats, their impact on performance,
and how to reduce video impact on overall page load time while serving
the smallest video file size based on each browser's file type support.
|
Why optimize your multimedia?
-----------------------------
For the average website, 25% of bandwidth comes from video. Optimizing video has the potential for very large bandwidth savings that translate into better website performance.
Optimizing video delivery
-------------------------
The sections below describe the following optimization techniques:
* compress all video
* optimize `<source>` order
* set autoplay
* remove audio from muted video
* optimize video preload
* consider streaming
### Compress all videos
Most video compression work compares adjacent frames within a video, with the intent of removing detail that is identical in both frames. Compress the video and export to multiple video formats, including WebM, MPEG-4/H.264, and Ogg/Theora.
Your video editing software probably has a feature to reduce file size. If not, there are online tools, such as FFmpeg (discussed in section below), that encode, decode, convert, and perform other optimization functions.
### Optimize `<source>` order
Order video source from smallest to largest. For example, given video compressions in three different formats at 10MB, 12MB, and 13MB, declare the smallest first and the largest last:
```html
<video width="400" height="300" controls="controls">
<!-- WebM: 10 MB -->
<source src="video.webm" type="video/webm" />
<!-- MPEG-4/H.264: 12 MB -->
<source src="video.mp4" type="video/mp4" />
<!-- Ogg/Theora: 13 MB -->
<source src="video.ogv" type="video/ogv" />
</video>
```
The browser downloads the first format it understands. The goal is to offer smaller versions ahead of larger versions. With the smallest version, make sure that the most compressed video still looks good. There are some compression algorithms that can make video look (bad) like an animated GIF. While a 128 Kb video may seem like it could provide a better user experience than a 10 MB download, a grainy GIF-like video may reflect poorly on the brand or project.
See CanIUse.com for current browser support of video and other media types.
### Video autoplay
To ensure that a looping background video autoplays, you must add several attributes to the video tag: `autoplay`, `muted`, and `playsinline`.
```html
<video
autoplay=""
loop=""
muted
playsinline=""
src="backgroundvideo.mp4"></video>
```
While the `loop` and `autoplay` make sense for a looping and autoplaying video, the `muted` attribute is required for autoplay in mobile browsers.
`Playsinline` is required for mobile Safari, allowing videos to play without forcing fullscreen mode.
### Remove audio from muted hero videos
For hero-video or other video without audio, removing audio is smart.
```html
<video autoplay="" loop="" muted playsinline="" id="hero-video">
<source src="banner\_video.webm" type='video/webm; codecs="vp8, vorbis"' />
<source src="web\_banner.mp4" type="video/mp4" />
</video>
```
This hero-video code (above) is common to conference websites and corporate home pages. It includes a video that is autoplaying, looping, and muted. There are no controls, so there is no way to hear audio. The audio is often empty, but still present, and still using bandwidth. There is no reason to serve audio with video that is always muted. **Removing audio can save 20% of the bandwidth.**
Depending on your choice of software, you might be able to remove audio during export and compression. If not, a free utility called FFmpeg can do it for you. This is the FFmpeg command string to remove audio:
```bash
ffmpeg -i original.mp4 -an -c:v copy audioFreeVersion.mp4
```
### Video preload
The preload attribute has three available options: `auto`|`metadata`|`none`. The default setting is `metadata`. These settings control how much of a video file downloads with page load. You can save data by deferring download for less popular videos.
Setting `preload="none"` results in none of the video being downloaded until playback. It delays startup, but offers significant data savings for videos with a low probability of playback.
Offering more modest bandwidth savings, setting `preload="metadata"` may download up to 3% of the video on page load. This is a useful option for some small or moderately sized files.
Changing the setting to `auto` tells the browser to automatically download the entire video. Do this only when playback is very likely. Otherwise, it wastes a lot of bandwidth.
### Consider streaming
Video streaming allows the proper video size and bandwidth (based on network speed) to be delivered to the end user. Similar to responsive images, the correct size video is delivered to the browser, ensuring fast video startup, low buffering, and optimized playback.
Conclusion
----------
Optimizing video has the potential to significantly improve website performance. Video files are relatively large compared to other website files, and always worthy of attention. This article explains how to optimize website video through reducing file size, with (HTML) download settings, and with streaming.
* Previous
* Overview: Performance
* Next |
Measuring performance - Learn web development | Measuring performance
=====================
* Previous
* Overview: Performance
* Next
Measuring performance provides an important metric to help you assess the success of your app, site, or web service.
For example, you can use performance metrics to determine how your app performs compared to a competitor or compare your app's performance across releases. Your metrics should be relevant to your users, site, and business goals. They should be collected, measured consistently, and analyzed in a format that non-technical stakeholders can consume and understand.
This article introduces tools you can use to access web performance metrics, which can be used to measure and optimize your site's performance.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, and basic knowledge of
client-side web technologies.
|
| Objective: |
To provide information about web performance metrics that you can
collect through various web performance APIs and tools that you can
use to visualize that data.
|
Performance tools
-----------------
There are several different tools available to help you measure and improve performance. These can generally be classified into two categories:
* Tools that indicate or measure performance, such as PageSpeed Insights or the Firefox Network Monitor and Performance Monitor. These tools show you how fast or slow your website is loading. They also indicate areas that can be improved to optimize your web app.
* Performance APIs that you can use to build custom performance tools.
General performance reporting tools
-----------------------------------
Tools like PageSpeed Insights can provide quick performance measurements. You can enter a URL and get a performance report in seconds. The report contains scores indicating how your website performs for mobile and desktop. This is a good start for understanding what you are doing well and what could be improved.
At the time of writing, MDN's performance report summary looks similar to the following:
![A screenshot of PageSpeed Insights report for the Mozilla homepage.](/en-US/docs/Learn/Performance/Measuring_performance/pagespeed-insight-mozilla-homepage.png)
A performance report contains information about things like how long a user has to wait before *anything* is displayed on the page, how many bytes need to be downloaded to display a page, and much more. It also lets you know if the measured values are considered good or bad.
webpagetest.org is another example of a tool that automatically tests your site and returns valuable metrics.
You can try running your favorite website through these tools and see the scores.
Network monitor tools
---------------------
Modern browsers have tools available that you can use to run against loaded pages and determine how they are performing; most of them work similarly. For example, the Firefox Network Monitor returns detailed information on all the assets downloaded from the network, along with a waterfall time graph that shows how long each one took to download.
![Firefox network monitor showing a list of assets that has loaded as well as load time per asset](/en-US/docs/Learn/Performance/Measuring_performance/network-monitor.png)
You should also check out Chrome's Network Monitor documentation.
Performance monitor tools
-------------------------
You can also use browser performance tools such as the Firefox Performance Monitor to measure the performance of a web app or site's user interface as you perform different actions. This indicates the features that might slow down your web app or site.
![Developer tools performance panel showing the waterfall of recording #1.](/en-US/docs/Learn/Performance/Measuring_performance/perf-monitor.png)
See also Chrome's Performance tool documentation.
Performance APIs
----------------
When writing code for the Web, many Web APIs are available to create your own performance-measuring tools.
You can use the Navigation Timing API to measure client-side web performance, including the amount of time needed to unload the previous page, how long domain lookups take, the total time spent executing the window's load handler, and more. You can use the API for metrics related to all the navigation events in the diagram below.
![The various handlers that the navigation timing API can handle including Navigation timing API metrics Prompt for unload redirect unload App cache DNS TCP Request Response Processing onLoad navigationStart redirectStart redirectEnd fetchStart domainLookupEnd domainLookupStart connectStart (secureConnectionStart) connectEnd requestStart responseStart responseEnd unloadStart unloadEnd domLoading domInteractive domContentLoaded domComplete loadEventStart loadEventEnd](/en-US/docs/Learn/Performance/Measuring_performance/navigationtimingapi.jpg)
The Performance API, which provides access to performance-related information for the current page, includes several APIs including the Navigation Timing API, the User Timing API, and the Resource Timing API. These interfaces allow the accurate measurement of the time it takes for JavaScript tasks to complete.
The PerformanceEntry object is part of the *performance timeline*. A *performance entry* can be directly created by making a performance *`mark`* or *`measure`* (for example by calling the `mark()` method) at an explicit point in an application. Performance entries are also created in indirect ways, such as loading a resource like an image.
The PerformanceObserver API can be used to observe performance measurement events and to notify you of new performance entries as they are recorded in the browser's performance timeline.
While this article does not dive into using these APIs, it is helpful to know they exist. Refer to the Navigation and timings article for further examples of using performance Web APIs.
Conclusion
----------
This article briefly overviews some tools that can help you measure performance on a web app or site. In the following article, we'll see how you can optimize images on your site to improve its performance.
* Previous
* Overview: Performance
* Next |
Web performance resources - Learn web development | Web performance resources
=========================
* Previous
* Overview: Performance
There are many reasons why your website should perform as well as possible.
Below is a quick review of best practices, tools, APIs with links to provide more information about each topic.
Best practices
--------------
* Start with learning the critical rendering path of the browser. Knowing this will help you understand how to improve the performance of the site.
* Using *resource hints* such as `rel=preconnect`, `rel=dns-prefetch`, `rel=prefetch`, `rel=preload`.
* Keep the size of JavaScript to a minimum. Only use as much JavaScript as needed for the current page.
* CSS performance factors
* Use HTTP/2 on your server (or CDN).
* Use a CDN for resources which can reduce load times significantly.
* Compress your resources using gzip, Brotli, and Zopfli.
* Image optimization (use CSS animation, or SVG if possible).
* Lazy loading parts of your application outside the viewport. If you do, have a backup plan for SEO (e.g., render full page for bot traffic); for example, by using the `loading` attribute on the `<img>` element
* It is also crucial to realize what is really important to your users. It might not be absolute timing, but user perception.
Quick Wins
----------
### CSS
Web performance is all about user experience and perceived performance. As we learned in the critical rendering path document, linking CSS with a traditional link tag with rel="stylesheet" is synchronous and blocks rendering. Optimize the rendering of your page by removing blocking CSS.
To load CSS asynchronously one can set the media type to print and then change to all once loaded. The following snippet includes an onload attribute, requiring JavaScript, so it is important to include a noscript tag with a traditional fallback.
```html
<link
rel="stylesheet"
href="/path/to/my.css"
media="print"
onload="this.media='all'" />
<noscript><link rel="stylesheet" href="/path/to/my.css" /></noscript>
```
The downside with this approach is the flash of unstyled text (FOUT.) The simplest way to address this is by inlining CSS that is required for any content that is rendered above the fold, or what you see in the browser viewport before scrolling. These styles will improve perceived performance as the CSS does not require a file request.
```html
<style>
/\* Insert your CSS here \*/
</style>
```
### JavaScript
Avoid JavaScript blocking by using the async or defer attributes, or link JavaScript assets after the page's DOM elements. JavaScript only block rendering for elements that appear after the script tag in the DOM tree.
### Web Fonts
EOT and TTF formats are not compressed by default. Apply compression such as GZIP or Brotli for these file types. Use WOFF and WOFF2. These formats have compression built in.
Within @font-face use font-display: swap. By using font display swap the browser will not block rendering and will use the backup system fonts that are defined. Optimize font weight to match the web font as closely as possible.
#### Icon web fonts
If possible avoid icon web fonts and use compressed SVGs. To further optimize inline your SVG data within HTML markup to avoid HTTP requests.
Tools
-----
* Learn to use the Firefox Dev Tools to profile your site.
* PageSpeed Insights can analyze your page and give some general hints to improve performance.
* Lighthouse can give you a detailed breakdown of many aspects of your site including performance, SEO and accessibility.
* Test your page's speed using WebPageTest.org, where you can use different real device types and locations.
* Try the Chrome User Experience Report which quantifies real user metrics.
* Define a performance budget.
### APIs
* Gather user metrics using the boomerang library.
* Or directly gather with window.performance.timing
### Things not to do (bad practices)
* Download everything
* Use uncompressed media files
See also
--------
* https://github.com/filamentgroup/loadCSS |
Perceived performance - Learn web development | Perceived performance
=====================
* Previous
* Overview: Performance
* Next
**Perceived performance** is a subjective measure of website performance, responsiveness, and reliability. In other words, how fast a website seems to the user. It is harder to quantify and measure than the actual speed of operation, but perhaps even more important.
This article provides a brief introduction to the factors that affect perceived performance, along with a number of tools for assessing and improving the perception.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, and basic knowledge of
client-side web technologies.
|
| Objective: | To gain basic familiarity of user perception of web performance. |
Overview
--------
The perception of how quickly (and smoothly) pages load and respond to user interaction is even more important than the actual time required to fetch the resources. While you may not be able to physically make your site run faster, you may well be able to improve how fast it *feels* for your users.
A good general rule for improving perceived performance is that it is usually better to provide a quick response and regular status updates than make the user wait until an operation fully completes (before providing any information). For example, when loading a page it is better to display the text when it arrives rather than wait for all the images and other resources. Even though the content has not fully downloaded the user can see something is happening and they can start interacting with the content.
**Note:** Time appears to pass more quickly for users who are actively engaged, distracted, or entertained, than for those who are waiting passively for something to happen. Where possible, actively engage and inform users who are waiting for a task to complete.
Similarly, it is better to display a "loading animation" as soon as a user clicks a link to perform a long-running operation. While this doesn't change the time taken to complete the operation, the site feels more responsive, and the user knows that it is working on something useful.
Performance metrics
-------------------
There is no single metric or test that can be run on a site to evaluate how a user "feels". However, there are a number of metrics that can be "helpful indicators":
First paint
The time to start of first paint operation. Note that this change may not be visible; it can be a simple background color update or something even less noticeable.
First Contentful Paint (FCP)
The time until first significant rendering (e.g. of text, foreground or background image, canvas or SVG, etc.). Note that this content is not necessarily useful or meaningful.
First Meaningful Paint (FMP)
The time at which useful content is rendered to the screen.
Largest Contentful Paint (LCP)
The render time of the largest content element visible in the viewport.
Speed index
Measures the average time for pixels on the visible screen to be painted.
Time to interactive
Time until the UI is available for user interaction (i.e. the last long task of the load process finishes).
Improving performance
---------------------
Here are a few tips and tricks to help improve perceived performance:
### Minimize initial load
To improve perceived performance, minimize the original page load. In other words, download the content the user is going to interact with immediately first, and download the rest after "in the background". The total amount of content downloaded may actually increase, but the user only *waits* on a very small amount, so the download feels faster.
Separate interactive functionality from content, and load text, styles, and images visible at initial load. Delay, or lazy load, images or scripts that aren't used or visible on the initial page load. Additionally, you should optimize the assets you do load. Images and video should be served in the most optimal format, compressed, and in the correct size.
### Prevent jumping content and other reflows
Images or other assets causing content to be pushed down or jump to a different location, like the loading of third party advertisements, can make the page feel like it is still loading and is bad for perceived performance. Content reflowing is especially bad for user experience when not initiated by user interaction. If some assets are going to be slower to load than others, with elements loading after other content has already been painted to the screen, plan ahead and leave space in the layout for them so that content doesn't jump or resize, especially after the site has become interactive.
### Avoid font file delays
Font choice is important. Selecting an appropriate font can greatly improve the user experience. From a perceived performance point of view, "suboptimal fonts importing" can result in flicker as text is styled or when falling back to other fonts.
Make fallback fonts the same size and weight so that when fonts load the page change is less noticeable.
### Interactive elements are interactive
Make sure visible interactive elements are always interactive and responsive. If input elements are visible, the user should be able to interact with them without a lag. Users feel that something is laggy when they take more than 50ms to react. They feel that a page is behaving poorly when content repaints slower than 16.67ms (or 60 frames per second) or repaints at uneven intervals.
Make things like type-ahead a progressive enhancement: use CSS to display input modal, JS to add autocomplete as it is available
### Make task initiators appear more interactive
Making a content request on `keydown` rather than waiting for `keyup` can reduce the perceived load time of the content by 200ms. Adding an interesting but unobtrusive 200ms animation to that `keyup` event can reduce another 200ms of the perceived load. You're not saving 400ms of time, but the user doesn't feel like they're waiting for content until, well, until they're waiting for content.
Conclusion
----------
By reducing the time that a user has to wait for *useful* content, and keeping the site responsive and engaging, the users will feel like the site performs better β even the actual time to load resources stays the same.
* Previous
* Overview: Performance
* Next |
Multimedia: Images - Learn web development | Multimedia: Images
==================
* Previous
* Overview: Performance
* Next
Media, namely images and video, account for over 70% of the bytes downloaded for the average website. In terms of download performance, eliminating media, and reducing file size is the low-hanging fruit. This article looks at optimizing images and video to improve web performance.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, and basic knowledge of
client-side web technologies.
|
| Objective: |
To learn about the various image formats, their impact on performance,
and how to reduce the impact of images on overall page load time.
|
**Note:** This is a high-level introduction to optimizing multimedia delivery on the web, covering general principles and techniques. For a more in-depth guide, see https://web.dev/learn/images.
Why optimize your multimedia?
-----------------------------
For the average website, 51% of its bandwidth comes from imagery, followed by video at 25%, so it's safe to say it's important to address and optimize your multimedia content.
You need to be considerate of data usage. Many people are on capped data plans or even pay-as-you-go where they are literally paying by the megabyte. This isn't an emerging market problem either. As of 2018, 24% of the United Kingdom still use pay-as-you-go.
You also need to be considerate of memory as many mobile devices have limited RAM. It's important to remember that when images are downloaded, they need to be stored in memory.
Optimizing image delivery
-------------------------
Despite being the largest consumer of bandwidth, the impact of image downloading on perceived performance is far lower than many expect (primarily because the page text content is downloaded immediately and users can see the images being rendered as they arrive). However, for a good user experience it's still important that a visitor can see them as soon as possible.
### Loading strategy
One of the biggest improvements to most websites is lazy-loading images beneath the fold, rather than downloading them all on initial page load regardless of whether a visitor scrolls to see them or not. Many JavaScript libraries can implement this for you, such as lazysizes, and browser vendors are working on a native `lazyload` attribute that is currently in the experimental phase.
Beyond loading a subset of images, you should look into the format of the images themselves:
* Are you loading the most optimal file formats?
* Have you compressed the images well?
* Are you loading the correct sizes?
#### The most optimal format
The optimal file format typically depends on the character of the image.
**Note:** For general information on image types see the Image file type and format guide
The SVG format is more appropriate for images that have few colors and that are not photo-realistic. This requires the source to be available as in a vector graphic format. Should such an image only exist as a bitmap, then PNG would be the fallback format to choose. Examples of these types of motifs are logos, illustrations, charts, or icons (note: SVGs are far better than icon fonts!). Both formats support transparency.
PNGs can be saved with three different output combinations:
* 24-bit color + 8-bit transparency β offer full-color accuracy and smooth transparency at the expense of size. You probably want to avoid this combination in favor of WebP (see below).
* 8-bit color + 8-bit transparency β offer no more than 255 colors but maintain smooth transparencies. The size is not too big. Those are the PNGs you would probably want.
* 8-bit color + 1-bit transparency β offer no more than 255 colors and just offer no or full transparency per pixel which makes the transparency borders appear hard and jagged. The size is small but the price is visual fidelity.
A good online tool for optimizing SVGs is SVGOMG. For PNGs there is ImageOptim online or Squoosh.
With photographic motifs that do not feature transparency, there is a much wider range of formats to choose from. If you want to play it safe, then you would go for well-compressed **Progressive JPEGs**. Progressive JPEGs, in contrast to normal JPEGs, render progressively (hence the name), meaning the user sees a low-resolution version that gains clarity as the image downloads, rather than the image loading at full resolution top-to-bottom or even only rendering once completely downloaded. A good compressor for these would be MozJPEG, e.g. available to use in the online image optimization tool Squoosh. A quality setting of 75% should yield decent results.
Other formats improve on JPEG's capabilities regarding compression, but are not available on every browser:
* WebP β Excellent choice for both images and animated images. WebP offers much better compression than PNG or JPEG with support for higher color depths, animated frames, transparency, etc. (but not progressive display.). Supported by all major browsers except Safari 14 on macOS desktop Big Sur or earlier.
**Note:** Despite Apple announcing support for WebP in Safari 14, Safari versions earlier than 16.0 don't display `.webp` images successfully on macOS desktop versions earlier than 11/Big Sur. Safari for iOS 14 *does* display `.webp` images successfully.
* AVIF β Good choice for both images and animated images due to high performance and royalty-free image format (even more efficient than WebP, but not as widely supported). It is now supported on Chrome, Edge, Opera, and Firefox. See also an online tool to convert previous image formats to AVIF.
* **JPEG2000** β once to be the successor to JPEG but only supported in Safari. Doesn't support progressive display either.
Given the narrow support for JPEG-XR and JPEG2000, and also taking decode costs into the equation, the only serious contender for JPEG is WebP. Which is why you could offer your images in that flavor too. This can be done via the `<picture>` element with the help of a `<source>` element equipped with a type attribute.
If all of this sounds a bit complicated or feels like too much work for your team then there are also online services that you can use as image CDNs that will automate the serving of the correct image format on the fly, according to the type of device or browser requesting the image. The biggest ones are Cloudinary and Image Engine.
Finally, should you want to include animated images on your page, then know that Safari allows the use of video files within `<img>` and `<picture>` elements. These also allow you to add in an **Animated WebP** for all other modern browsers.
```html
<picture>
<source type="video/mp4" src="giphy.mp4" />
<source type="image/webp" src="giphy.webp" />
<img src="giphy.gif" alt="A GIF animation" />
</picture>
```
#### Serving the optimal size
In image delivery the "one size fits all" approach will not yield the best results, meaning that for smaller screens you would want to serve images with smaller resolution and vice versa for larger screens. On top of that, you'd also want to serve higher resolution images to those devices that boast a high DPI screen (e.g. "Retina"). So apart from creating plenty of intermediate image variants you also need a way to serve the right file to the right browser. That's where you would need to upgrade your `<picture>` and `<source>` elements with media and/or sizes attributes. A detailed article on how to combine all of these attributes can be found here.
Two interesting effects to keep in mind regarding high dpi screens is that:
* with a high DPI screen, humans will spot compression artifacts a lot later, meaning that for images meant for these screens you can crank up compression beyond usual.
* Only a very few people can spot an increase in resolution beyond 2Γ DPI, which means you don't need to serve images resolving higher than 2Γ.
#### Controlling the priority (and ordering) of downloading images
Getting the most important images in front of visitors sooner than the less important can deliver improved perceived performance.
The first thing to check is that your content images use `<img>` or `<picture>` elements and your background images are defined in CSS with `background-image` β images referenced in `<img>` elements are assigned a higher loading priority than background images.
Secondly, with the adoption of Priority Hints, you can control the priority further by adding a `fetchPriority` attribute to your image tags. An example use case for priority hints on images are carousels where the first image is a higher priority than the subsequent images.
### Rendering strategy: preventing jank when loading images
As images are loaded asynchronously and continue to load after the first paint, if their dimensions aren't defined before load, they can cause reflows to the page content. For example, when text gets pushed down the page by images loading. For this reason, it's critical that you set `width` and `height` attributes so that the browser can reserve space for them in the layout.
When the `width` and `height` attributes of an image are included on an HTML `<img>` element, the aspect ratio of the image can be calculated by the browser prior to the image being loaded. This aspect ratio is used to reserve the space needed to display the image, reducing or even preventing a layout shift when the image is downloaded and painted to the screen. Reducing layout shift is a major component of good user experience and web performance.
Browsers begin rendering content as HTML is parsed, often before all assets, including images, are downloaded. Including dimensions enable browsers to reserve a correctly-sized placeholder box for each image to appear in when the images are loaded when first rendering the page.
![Two screenshots the first without an image but with space reserved, the second showing the image loaded into the reserved space.](/en-US/docs/Learn/Performance/Multimedia/ar-guide.jpg)
Without the `width` and `height` attributes, no placeholder space is created, creating a noticeable jank, or layout shift, in the page when the image loads after the page is rendered. Page reflow and repaints are performance and usability issues.
In responsive designs, when a container is narrower than an image, the following CSS is generally used to keep images from breaking out of their containers:
```css
img {
max-width: 100%;
height: auto;
}
```
While useful for responsive layouts, this causes jank when width and height information are not included, as if no height information is present when the `<img>` element is parsed but before the image has loaded, this CSS effectively has set the height to 0. When the image loads after the page has been initially rendered to the screen, the page reflows and repaints creating a layout shift as it creates space for the newly determined height.
Browsers have a mechanism for sizing images before the actual image is loaded. When an `<img>`, `<video>`, or `<input type="button">` element has `width` and `height` attributes set on it, its aspect ratio is calculated before load time, and is available to the browser, using the dimensions provided.
The aspect ratio is then used to calculate the height and therefore the correct size is applied to the `<img>` element, meaning that the aforementioned jank will not occur, or be minimal if the listed dimensions are not fully accurate, when the image loads.
The aspect ratio is used to reserve space only on the image load. Once the image has loaded, the intrinsic aspect ratio of the loaded image, rather than the aspect ratio from the attributes, is used. This ensures that it displays at the correct aspect ratio even if the attribute dimensions are not accurate.
While developer best practices from the last decade may have recommended omitting the `width` and `height` attributes of an image on an HTML `<img>`, due to aspect ratio mapping, including these two attributes is considered a developer best practice.
For any background images, it's important you set a `background-color` value so any content overlaid is still readable before the image has downloaded.
Conclusion
----------
In this section, we took a look at image optimization. You now have a general understanding of how to optimize half of the average website's average bandwidth total. This is just one of the types of media consuming users' bandwidth and slowing down page load. Let's take a look at video optimization, tackling the next 20% of bandwidth consumption.
* Previous
* Overview: Performance
* Next |
HTML performance optimization - Learn web development | HTML performance optimization
=============================
* Previous
* Overview: Performance
* Next
HTML is by default fast and accessible. It is our job, as developers, to ensure that we preserve these two properties when creating or editing HTML code. Complications can occur when, for example, the file size of a `<video>` embed is too large or when JavaScript parsing blocks the rendering of critical page elements. This article walks you through the key HTML performance features that can drastically improve the quality of your web page.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, and basic knowledge of
client-side web technologies.
|
| Objective: |
To learn about the impact of HTML on website performance
and how to optimize your HTML to improve performance.
|
To optimize or not to optimize
------------------------------
The first question you should answer before starting to optimize your HTML is "what do I need to optimize?". Some of the tips and techniques discussed below are good practices that will benefit just about any web project, whereas some are only needed in certain situations. Trying to apply all these techniques everywhere is probably unnecessary, and may be a waste of your time. You should figure out what performance optimizations are actually needed in each project.
To do this, you need to measure the performance of your site. As this link shows, there are several different ways to measure performance, some involving sophisticated performance APIs. The best way to get started, however, is to learn how to use tools such as built-in browser network and performance tools, to examine the parts of the page that are taking a long time to load and need optimizing.
Key HTML performance issues
---------------------------
HTML is simple in terms of performance β it is mostly text, which is small in size, and therefore, mostly quick to download and render. The key issues that can impact the performance of a web page include:
* Size of the image and video files: It is important to consider how to handle the content of replaced elements such as `<img>` and `<video>`. Image and video files are large and can add significantly to the weight of the page. Therefore, it is important to minimize the amount of bytes that get downloaded on a user's device (for example, serve smaller images for mobile). You also need to consider improving the perceived performance by loading images and videos on a page only when they are needed.
* Delivery of embedded content: This is usually the content embedded in `<iframe>` elements. Loading content into `<iframe>`s can impact performance significantly, so it should be considered carefully.
* Order of resource loading: To maximize the perceived and actual performance, the HTML should be loaded first, in the order in which it appears on the page. You can then use various features to influence the order of resource loading for better performance. For example, you can preload critical CSS and fonts early, but defer non-critical JavaScript until later on.
**Note:** There is an argument to be made for simplifying your HTML structure and minifying your source code, so that rendering and downloads are faster. However, HTML file size is negligible compared to images and videos, and browser rendering is very fast these days. If your HTML source is so large and complex that it is creating rendering and download performance hits, you probably have bigger problems, and should aim to simplify it and split the content up.
Responsive handling of replaced elements
----------------------------------------
Responsive design has revolutionized the way that web content layout is handled across different devices. One key advantage that it enables is dynamic switching of layouts optimized for different screen sizes, for example a wide screen layout versus a narrow (mobile) screen layout. It can also handle dynamic switching of content based on other device attributes, such as resolution or preference for light or dark color scheme.
The so-called "mobile first" technique can ensure that the default layout is for small-screen devices, so mobiles can just download images suitable for their screens, and don't need to take the performance hit of downloading larger desktop images. However, since this is controlled using media queries in your CSS, it can only positively affect performance of images loaded in CSS.
In the sections below, we'll summarize how to implement responsive replaced elements. You can find a lot more detail about these implementations in the Video and audio content and Responsive images guides.
### Providing different image resolutions via srcset
To provide different resolution versions of the same image depending on the device's resolution and viewport size, you can use the `srcset` and `sizes` attributes.
This example provides different size images for different screen widths:
```html
<img
srcset="480w.jpg 480w, 800w.jpg 800w"
sizes="(max-width: 600px) 480px,
800px"
src="800w.jpg"
alt="Family portrait" />
```
`srcset` provides the intrinsic size of the source images along with their filenames, and `sizes` provides media queries alongside image slot widths that need to be filled in each case. The browser then decides which images makes sense to load for each slot. As an example, if the screen width is `600px` or less, then `max-width: 600px` is true, and therefore, the slot to fill is said to be `480px`. In this case, the browser will likely choose to load the 480w.jpg file (480px-wide image). This helps with performance because browsers don't load larger images than they need.
This example provides different resolution images for different screen resolutions:
```html
<img
srcset="320w.jpg, 480w.jpg 1.5x, 640w.jpg 2x"
src="640w.jpg"
alt="Family portrait" />
```
`1.5x`, `2x`, etc. are relative resolution indicators. If the image is styled to be 320px-wide (for example with `width: 320px` in CSS), the browser will load `320w.jpg` if the device is low resolution (one device pixel per CSS pixel), or `640x.jpg` if the device is high resolution (two device pixels per CSS pixel or more).
In both cases, the `src` attribute provides a default image to load if the browser does not support `src`/`srcset`.
### Providing different sources for images and videos
The `<picture>` element builds on the traditional `<img>` element, allowing you to provide multiple different sources for different situations. For example if the layout is wide, you will probably want a wide image, and if it is narrow, you will want a narrower image that still works in that context.
Of course, this also works to provide a smaller download of information on mobile devices, helping with performance.
An example is as follows:
```html
<picture>
<source media="(max-width: 799px)" srcset="narrow-banner-480w.jpg" />
<source media="(min-width: 800px)" srcset="wide-banner-800w.jpg" />
<img src="large-banner-800w.jpg" alt="Dense forest scene" />
</picture>
```
The `<source>` elements contain media queries inside `media` attributes. If a media query returns true, the image referenced in its `<source>` element's `srcset` attribute is loaded. In the above example, if the viewport width is `799px` or less, the `narrow-banner-480w.jpg` image is loaded. Also note how the `<picture>` element includes an `<img>` element, which provides a default image to load in the case of browsers that don't support `<picture>`.
Note the use of the `srcset` attribute in this example. As shown in the previous section, you can provide different resolutions for each image source.
`<video>` elements work in a similar way, in terms of providing different sources:
```html
<video controls>
<source src="video/smaller.mp4" type="video/mp4" />
<source src="video/smaller.webm" type="video/webm" />
<source src="video/larger.mp4" type="video/mp4" media="(min-width: 800px)" />
<source
src="video/larger.webm"
type="video/webm"
media="(min-width: 800px)" />
<!-- fallback for browsers that don't support video element -->
<a href="video/larger.mp4">download video</a>
</video>
```
There are, however, some key differences between providing sources for images and videos:
* In the above example, we are using `src` rather than `srcset`; you can't specify different resolutions for videos via `srcset`.
* Instead, you specify different resolutions inside the different `<source>` elements.
* Note how we are also specifying different video formats inside different `<source>` elements, with each format being identified via its MIME type inside the `type` attribute. Browsers will load the first one they come across that they support, where the media query test returns true.
### Lazy loading images
A very useful technique for improving performance is **lazy loading**. This refers to the practice of not loading all images immediately when the HTML is rendered, but instead only loading them when they are actually visible to the user in the viewport (or imminently visible). This means that the immediately visible/usable content is ready to use more quickly, whereas subsequent content only has its images rendered when scrolled to, and the browser won't waste bandwidth loading images that the user will never see.
Lazy loading has historically been handled using JavaScript, but browsers now have a `loading` attribute available that can instruct the browser to lazy load images automatically:
```html
<img src="800w.jpg" alt="Family portrait" loading="lazy" />
```
See Browser-level image lazy loading for the web on web.dev for detailed information.
You can also lazy load video content by using the `preload` attribute. For example:
```html
<video controls preload="none" poster="poster.jpg">
<source src="video.webm" type="video/webm" />
<source src="video.mp4" type="video/mp4" />
</video>
```
Giving `preload` a value of `none` tells the browser to not preload any of the video data before the user decides to play it, which is obviously good for performance. Instead, it will just show the image indicated by the `poster` attribute. Different browsers have different default video loading behavior, so it is good to be explicit.
See Lazy loading video on web.dev for detailed information.
Handling embedded content
-------------------------
It is very common for content to be embedded in web pages from other sources. This is most commonly done when displaying advertising on a site to generate revenue β the ads are usually generated by a third-party company of some kind and embedded onto your page. Other uses might include:
* Displaying shared content that a user might need across multiple pages, such as a shopping cart or profile information.
* Displaying third-party content related to the organization's main site, such as a social media posts feed.
Embedding content is most commonly done using `<iframe>` elements, although other less commonly used embedding elements do exist, such as `<object>` and `<embed>`. We'll concentrate on `<iframe>`s in this section.
The most important and key piece of advice for using `<iframe>`s is: "Don't use embedded `<iframe>`s unless you absolutely have to". If you are creating a page with multiple different panes of information on it, it might sound organizationally sensible to break those up into separate pages and load them into different `<iframe>`s. However, this has a number of problems associated with it in terms of performance and otherwise:
* Loading the content into an `<iframe>` is much more expensive than loading the content as part of the same direct page β not only does it require extra HTTP requests to load the content, but the browser also needs to create a separate page instance for each one. Each one is effectively a separate web page instance embedded in the top-level web page.
* Following on from the previous point, you'll also need to handle any CSS styling or JavaScript manipulation separately for each different `<iframe>` (unless the embedded pages are from the same origin), which becomes much more complex. You can't target embedded content with CSS and JavaScript applied to the top-level page, or vice versa. This is a sensible security measure that is fundamental to the web. Imagine all the problems you might run into if third-party embedded content could arbitrarily run scripts against any page it was embedded in!
* Each `<iframe>` would also need to load any shared data and media files separately β you can't share cached assets across different page embeds (again, unless the embedded pages are from the same origin). This can lead to a page using much more bandwidth than you might expect.
It is advisable to put the content into a single page. If you want to pull in new content dynamically as the page changes, it is still better for performance to load it into the same page rather than putting it into an `<iframe>`. You might grab the new data using the `fetch()` method, for example, and then inject it into the page using some DOM scripting. See Fetching data from the server and Manipulating documents for more information.
**Note:** If you control the content and it is relatively simple, you could consider using base-64 encoded content in the `src` attribute to populate the `<iframe>`, or even insert raw HTML into the `srcdoc` attribute (See Iframe Performance Part 2: The Good News for more information).
If you must use `<iframe>`s, then use them sparingly.
#### Lazy loading iframes
In the same way as `<img>` elements, you can also use the `loading` attribute to instruct the browser to lazy-load `<iframe>` content that is initially offscreen, thereby improving performance:
```html
<iframe src="https://example.com" loading="lazy" width="600" height="400">
</iframe>
```
See It's time to lazy-load offscreen iframes! for more information.
Handling resource loading order
-------------------------------
Ordering of resource loading is important for maximizing perceived and actual performance. When a web page is loaded:
1. The HTML is generally parsed first, in the order in which it appears on the page.
2. Any found CSS is parsed to understand the styles that need to be applied to the page. During this time, linked assets such as images and web fonts start to be fetched.
3. Any found JavaScript is parsed, evaluated, and run against the page. By default, this blocks parsing of the HTML that appears after the `<script>` elements where the JavaScript is encountered.
4. Slightly later on, the browser works out how each HTML element should be styled, given the CSS applied to it.
5. The styled result is then painted to the screen.
**Note:** This is a very simplified account of what happens, but it does give you an idea.
Various HTML features allow you to modify how resource loading happens to improve performance. We'll explore some of these now.
### Handling JavaScript loading
Parsing and executing JavaScript blocks the parsing of subsequent DOM content. This increases the time until that content is rendered and usable by the users of the page. A small script won't make much difference, but consider that modern web applications tend to be very JavaScript-heavy.
Another side effect of the default JavaScript parsing behavior is that, if the script being rendered relies on DOM content that appears later on in the page, you'll get errors.
For example, imagine a simple paragraph on a page:
```html
<p>My paragraph</p>
```
Now imagine a JavaScript file that contains the following code:
```js
const pElem = document.querySelector("p");
pElem.addEventListener("click", () => {
alert("You clicked the paragraph");
});
```
We can apply this script to the page by referring to it in a `<script>` element like this:
```html
<script src="index.js"></script>
```
If we put this `<script>` element before the `<p>` element in the source order (for example, in the `<head>` element), the page will throw an error (Chrome for example reports "Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')" to the console). This occurs because the script relies on the `<p>` element to work, but at the point the script is parsed, the `<p>` element does not exist on the page. It has not yet been rendered.
You can fix the above issue by putting the `<script>` element after the `<p>` element (for example at the end of the document body), or by running the code inside a suitable event handler (for example run it on the `DOMContentLoaded`, which fires when the DOM has been completely parsed).
However, this doesn't solve the problem of waiting for the script to load. Better performance can be achieved by adding the `async` attribute to the `<script>` element:
```html
<script async src="index.js"></script>
```
This causes the script to be fetched in parallel with the DOM parsing, so it is ready at the same time, and won't block rendering, thereby improving performance.
**Note:** There is another attribute, `defer`, which causes the script to be executed after the document has been parsed, but before firing `DOMContentLoaded`. This has a similar effect to `async`.
Another JavaScript load handling tip is to split your script up into code modules and load each part when required, instead of putting all your code into one giant script and loading it all at the beginning. This is done using JavaScript modules. Read the linked article for a detailed guide.
### Preloading content with rel="preload"
The fetching of other resources (such as images, videos, or font files) linked to from your HTML, CSS, and JavaScript can also cause performance problems, blocking your code from executing and slowing down the experience. One way to mitigate such problems is to use `rel="preload"` to turn `<link>` elements into preloaders. For example:
```html
<link rel="preload" href="sintel-short.mp4" as="video" type="video/mp4" />
```
Upon coming across a `rel="preload"` link, the browser will fetch the referenced resource as soon as possible and make it available in the browser cache so that it will be ready for use sooner when it is referenced in subsequent code. It is useful to preload high-priority resources that the user will encounter early on in a page so that the experience is as smooth as possible.
See the following articles for detailed information on using `rel="preload"`:
* `rel="preload"`
* Preload critical assets to improve loading speed on web.dev (2020)
**Note:** You can use `rel="preload"` to preload CSS and JavaScript files as well.
**Note:** There are other `rel` values that are also designed to speed up various aspects of page loading: `dns-prefetch`, `preconnect`, `modulepreload`, `prefetch`, and `prerender`. Go to the linked page and find out what they do.
* Previous
* Overview: Performance
* Next
See also
--------
* Fetching data from the server
* Manipulating documents |
CSS performance optimization - Learn web development | CSS performance optimization
============================
* Previous
* Overview: Performance
* Next
When developing a website, you need to consider how the browser is handling the CSS on your site. To mitigate any performance issues that CSS might be causing, you should optimize it. For example, you should optimize the CSS to mitigate render-blocking and minimize the number of required reflows. This article walks you through key CSS performance optimization techniques.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, and basic knowledge of
client-side web technologies.
|
| Objective: |
To learn about the impact of CSS on website performance
and how to optimize your CSS to improve performance.
|
To optimize or not to optimize
------------------------------
The first question you should answer before starting to optimize your CSS is "what do I need to optimize?". Some of the tips and techniques discussed below are good practices that will benefit just about any web project, whereas some are only needed in certain situations. Trying to apply all these techniques everywhere is probably unnecessary, and may be a waste of your time. You should figure out what performance optimizations are actually needed in each project.
To do this, you need to measure the performance of your site. As the previous link shows, there are several different ways to measure performance, some involving sophisticated performance APIs. The best way to get started however, is to learn how to use tools such as built-in browser network and performance tools, to see what parts of the page load are taking a long time and need optimizing.
Optimizing rendering
--------------------
Browsers follow a specific rendering path β paint only occurs after layout, which occurs after the render tree is created, which in turn requires both the DOM and the CSSOM trees.
Showing users an unstyled page and then repainting it after the CSS styles have been parsed would be a bad user experience. For this reason, CSS is render blocking until the browser determines that the CSS is required. The browser can paint the page after it has downloaded the CSS and built the CSS object model (CSSOM).
To optimize the CSSOM construction and improve page performance, you can do one or more of the following based on the current state of your CSS:
* **Remove unnecessary styles**: This may sound obvious, but it is surprising how many developers forget to clean up unused CSS rules that were added to their stylesheets during development and ended up not being used. All styles get parsed, whether they are being used during layout and painting or not, so it can speed up page rendering to get rid of unused ones. As How Do You Remove Unused CSS From a Site? (csstricks.com, 2019) summarizes, this is a difficult problem to solve for a large codebase, and there isn't a magic bullet to reliably find and remove unused CSS. You need to do the hard work of keeping your CSS modular and being careful and deliberate about what is added and removed.
* **Split CSS into separate modules**: Keeping CSS modular means that CSS not required at page load can be loaded later on, reducing initial CSS render-blocking and loading times. The simplest way to do this is by splitting up your CSS into separate files and loading only what is needed:
```html
<!-- Loading and parsing styles.css is render-blocking -->
<link rel="stylesheet" href="styles.css" />
<!-- Loading and parsing print.css is not render-blocking -->
<link rel="stylesheet" href="print.css" media="print" />
<!-- Loading and parsing mobile.css is not render-blocking on large screens -->
<link
rel="stylesheet"
href="mobile.css"
media="screen and (max-width: 480px)" />
```
The above example provides three sets of styles β default styles that will always load, styles that will only be loaded when the document is being printed, and styles that will be loaded only by devices with narrow screens. By default, the browser assumes that each specified style sheet is render-blocking. You can tell the browser when a style sheet should be applied by adding a `media` attribute containing a media query. When the browser sees a style sheet that it only needs to apply in a specific scenario, it still downloads the stylesheet, but doesn't render-block. By separating the CSS into multiple files, the main render-blocking file, in this case `styles.css`, is much smaller, reducing the time for which rendering is blocked.
* **Minify and compress your CSS**: Minifying involves removing all the whitespace in the file that is only there for human readability, once the code is put into production. You can reduce loading times considerably by minifying your CSS. Minification is generally done as part of a build process (for example, most JavaScript frameworks will minify code when you build a project ready for deployment). In addition to minification, make sure that the server that your site is hosted on uses compression such as gzip on files before serving them.
* **Simplify selectors**: People often write selectors that are more complex than needed for applying the required styles. This not only increases file sizes, but also the parsing time for those selectors. For example:
```css
/\* Very specific selector \*/
body div#main-content article.post h2.headline {
font-size: 24px;
}
/\* You probably only need this \*/
.headline {
font-size: 24px;
}
```
Making your selectors less complex and specific is also good for maintenance. It is easy to understand what simple selectors are doing, and it is easy to override styles when needed later on if the selectors are less specific.
* **Don't apply styles to more elements than needed**: A common mistake is to apply styles to all elements using the universal selector, or at least, to more elements than needed. This kind of styling can impact performance negatively, especially on larger sites.
```css
/\* Selects every element inside the <body> \*/
body \* {
font-size: 14px;
display: flex;
}
```
Remember that many properties (such as `font-size`) inherit their values from their parents, so you don't need to apply them everywhere. And powerful tools such as Flexbox need to be used sparingly. Using them everywhere can cause all kinds of unexpected behavior.
* **Cut down on image HTTP requests with CSS sprites**: CSS sprites is a technique that places several small images (such as icons) that you want to use on your site into a single image file, and then uses different `background-position` values to display the chunk of image that you want to show in each different place. This can dramatically cut down on the number of HTTP requests needed to fetch the images.
* **Preload important assets**: You can use `rel="preload"` to turn `<link>` elements into preloaders for critical assets. This includes CSS files, fonts, and images:
```html
<link rel="preload" href="style.css" as="style" />
<link
rel="preload"
href="ComicSans.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="bg-image-wide.png"
as="image"
media="(min-width: 601px)" />
```
With `preload`, the browser will fetch the referenced resources as soon as possible and make them available in the browser cache so that they will be ready for use sooner when they are referenced in subsequent code. It is useful to preload high-priority resources that the user will encounter early on in a page so that the experience is as smooth as possible. Note how you can also use `media` attributes to create responsive preloaders.
See also Preload critical assets to improve loading speed on web.dev (2020)
Handling animations
-------------------
Animations can improve perceived performance, making interfaces feel snappier and making users feel like progress is being made when they are waiting for a page to load (loading spinners, for example). However, larger animations and a higher number of animations will naturally require more processing power to handle, which can degrade performance.
The simplest advice is to cut down on all unnecessary animations. You could also provide users with a control/site preference to turn off animations if they are using a low-powered device or a mobile device with limited battery power. You could also use JavaScript to control whether or not animation is applied to the page in the first place. There is also a media query called `prefers-reduced-motion` that can be used to selectively serve animation styles or not based on a user's OS-level preferences for animation.
For essential DOM animations, you are advised to use CSS animations where possible, rather than JavaScript animations (the Web Animations API provides a way to directly hook into CSS animations using JavaScript).
### Choosing properties to animate
Next, animation performance relies heavily on what properties you are animating. Certain properties, when animated, trigger a reflow (and therefore also a repaint) and should be avoided. These include properties that:
* Alter an element's dimensions, such as `width`, `height`, `border`, and `padding`.
* Reposition an element, such as `margin`, `top`, `bottom`, `left`, and `right`.
* Change an element's layout, such as `align-content`, `align-items`, and `flex`.
* Add visual effects that change the element geometry, such as `box-shadow`.
Modern browsers are smart enough to repaint only the changed area of the document, rather than the entire page. As a result, larger animations are more costly.
If at all possible, it is better to animate properties that do not cause reflow/repaint. This includes:
* Transforms
* `opacity`
* `filter`
### Animating on the GPU
To further improve performance, you should consider moving animation work off the main thread and onto the device's GPU (also referred to as compositing). This is done by choosing specific types of animations that the browser will automatically send to the GPU to handle; these include:
* 3D transform animations such as `transform: translateZ()` and `rotate3d()`.
* Elements with certain other properties animated such as `position: fixed`.
* Elements with `will-change` applied (see the section below).
* Certain elements that are rendered in their own layer, including `<video>`, `<canvas>`, and `<iframe>`.
Animation on the GPU can result in improved performance, especially on mobile. However, moving animations to GPU is not always that simple. Read CSS GPU Animation: Doing It Right (smashingmagazine.com, 2016) for a very useful and detailed analysis.
Optimizing element changes with `will-change`
---------------------------------------------
Browsers may set up optimizations before an element is actually changed. These kinds of optimizations can increase the responsiveness of a page by doing potentially expensive work before it is required. The CSS `will-change` property hints to browsers how an element is expected to change.
**Note:** `will-change` is intended to be used as a last resort to try to deal with existing performance problems. It should not be used to anticipate performance problems.
```css
.element {
will-change: opacity, transform;
}
```
Optimizing for render blocking
------------------------------
CSS can scope styles to particular conditions with media queries. Media queries are important for a responsive web design and help us optimize a critical rendering path. The browser blocks rendering until it parses all of these styles but will not block rendering on styles it knows it will not use, such as the print stylesheets. By splitting the CSS into multiple files based on media queries, you can prevent render blocking during download of unused CSS. To create a non-blocking CSS link, move the not-immediately used styles, such as print styles, into separate file, add a `<link>` to the HTML mark up, and add a media query, in this case stating it's a print stylesheet.
```html
<!-- Loading and parsing styles.css is render-blocking -->
<link rel="stylesheet" href="styles.css" />
<!-- Loading and parsing print.css is not render-blocking -->
<link rel="stylesheet" href="print.css" media="print" />
<!-- Loading and parsing mobile.css is not render-blocking on large screens -->
<link
rel="stylesheet"
href="mobile.css"
media="screen and (max-width: 480px)" />
```
By default, the browser assumes that each specified style sheet is render blocking. Tell the browser when the style sheet should be applied by adding a `media` attribute with the media query. When the browser sees a style sheet it knows that it only needs to apply it for a specific scenario, it still downloads the stylesheet, but doesn't render block. By separating out the CSS into multiple files, the main render-blocking file, in this case `styles.css`, is much smaller, reducing the time that rendering is blocked.
Improving font performance
--------------------------
This section contains some useful tips for improving web font performance.
In general, think carefully about the fonts you use on your site. Some font files can be very large (multiple megabytes). While it can be tempting to use lots of fonts for visual excitement, this can slow down page load significantly, and cause your site to look like a mess. You probably only need about two or three fonts, and you can get away with less if you choose to use web safe fonts.
### Font loading
Bear in mind that a font is only loaded when it is actually applied to an element using the `font-family` property, not when it is first referenced using the `@font-face` at-rule:
```css
/\* Font not loaded here \*/
@font-face {
font-family: "Open Sans";
src: url("OpenSans-Regular-webfont.woff2") format("woff2");
}
h1,
h2,
h3 {
/\* It is actually loaded here \*/
font-family: "Open Sans";
}
```
It can therefore be beneficial to use `rel="preload"` to load important fonts early, so they will be available more quickly when they are actually needed:
```html
<link
rel="preload"
href="OpenSans-Regular-webfont.woff2"
as="font"
type="font/woff2"
crossorigin />
```
This is more likely to be beneficial if your `font-family` declaration is hidden inside a large external stylesheet, and won't be reached until significantly later in the parsing process. It is a tradeoff however β font files are quite large, and if you preload too many of them, you may delay other resources.
You can also consider:
* Using `rel="preconnect"` to make an early connection with the font provider. See Preconnect to critical third-party origins for details.
* Using the CSS Font Loading API to customize the font loading behavior via JavaScript.
### Loading only the glyphs you need
When choosing a font for body copy, it is harder to be sure of the glyphs that will be used in it, especially if you are dealing with user-generated content and/or content across multiple languages.
However, if you know you are going to use a specific set of glyphs (for example, glyphs for headings or specific punctuation characters only), you could limit the number of glyphs the browser has to download. This can be done by creating a font file that only contains the required subset. A process called subsetting. The `unicode-range` `@font-face` descriptor can then be used to specify when your subset font is used. If the page doesn't use any character in this range, the font is not downloaded.
```css
@font-face {
font-family: "Open Sans";
src: url("OpenSans-Regular-webfont.woff2") format("woff2");
unicode-range: U+0025-00FF;
}
```
### Defining font display behavior with the `font-display` descriptor
Applied to the `@font-face` at-rule, the `font-display` descriptor defines how font files are loaded and displayed by the browser, allowing text to appear with a fallback font while a font loads, or fails to load. This improves performance by making the text visible instead of having a blank screen, with a trade-off being a flash of unstyled text.
```css
@font-face {
font-family: someFont;
src: url(/path/to/fonts/someFont.woff) format("woff");
font-weight: 400;
font-style: normal;
font-display: fallback;
}
```
Optimizing styling recalculation with CSS containment
-----------------------------------------------------
By using the properties defined in the CSS containment module, you can instruct the browser to isolate different parts of a page and optimize their rendering independently from one another. This allows for improved performance in rendering individual sections. As an example, you can specify to the browser to not render certain containers until they are visible in the viewport.
The `contain` property allows an author to specify exactly what containment types they want applied to individual containers on the page. This allows the browser to recalculate layout, style, paint, size, or any combination of them for a limited part of the DOM.
```css
article {
contain: content;
}
```
The `content-visibility` property is a useful shortcut, which allows authors to apply a strong set of containments on a set of containers and specify that the browser should not lay out and render those containers until needed.
A second property, `contain-intrinsic-size`, is also available, which allows you to provide a placeholder size for containers while they are under the effects of containment. This means that the containers will take up space even if their contents have not yet been rendered, allowing containment to do its performance magic without the risk of scroll bar shift and jank as elements render and come into view. This improves the quality of the user experience as the content is loaded.
```css
article {
content-visibility: auto;
contain-intrinsic-size: 1000px;
}
```
* Previous
* Overview: Performance
* Next
See also
--------
* CSS animation performance
* Best practices for fonts on web.dev (2022)
* content-visibility: the new CSS property that boosts your rendering performance on web.dev (2022) |
Use CSS to solve common problems - Learn web development | Use CSS to solve common problems
================================
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?
Shadows can be added to boxes with the `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?
The `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?
A rundown of the different properties that might be useful when styling boxes using CSS.
How can I make elements semi-transparent?
The `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
* Styling backgrounds and borders
CSS and text
------------
How do I add a drop-shadow to text?
Shadows can be added to text with the `text-shadow` property. This tutorial explains how it works and shows an example.
How do I highlight the first line of a paragraph?
Find out how to target the first line of text in a paragraph with the `::first-line` pseudo-element.
How do I highlight the first paragraph in an article?
Find out how to target the first paragraph with the `:first-child` pseudo-class.
How do I highlight a paragraph only if it comes right after a heading?
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
* How to customize a list of elements
* How to style links
* CSS Selectors
CSS Layout
----------
How do I 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
* Using CSS multi-column layouts
* Using CSS Grid Layout
* Using CSS generated content
**Note:** We have a cookbook dedicated to CSS Layout solutions, with fully working examples and explanations of common layout tasks. Also check out Practical Positioning Examples, which shows how you can use positioning to create a tabbed info box, and a sliding hidden panel. |
CSS building blocks - Learn web development | CSS building blocks
===================
This module carries on where CSS first steps left off β now that you've gained familiarity with the language and its syntax, and got some basic experience using it, it's time to dive a bit deeper. This module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more.
The aim here is to provide you with a toolkit for writing competent CSS and help you understand all the essential theory, before moving on to more specific disciplines like text styling and CSS layout.
#### 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**
Prerequisites
-------------
Before starting this module, you should have:
1. Basic familiarity with using computers, and using the Web passively (i.e., just looking at it, consuming the content).
2. A basic work environment set up as detailed in Installing basic software, and an understanding of how to create and manage files, as detailed in Dealing with files.
3. Basic familiarity with HTML, as discussed in the Introduction to HTML module.
4. An understanding of the basics of CSS, as discussed in the CSS first steps module.
**Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Glitch.
Guides
------
This module contains the following articles, which cover the most essential parts of the CSS language. Along the way you'll come across plenty of exercises to allow you to test your understanding.
CSS selectors
There are a wide variety of CSS selectors available, allowing for fine-grained precision when selecting elements to style. In this article and its sub-articles, we'll run through the different types in great detail, seeing how they work. The sub-articles are as follows:
* Type, class, and ID selectors
* Attribute selectors
* Pseudo-classes and pseudo-elements
* Combinators
Cascade, specificity, and inheritance
The aim of this lesson is to develop your understanding of some of the most fundamental concepts of CSS β the cascade, specificity, and inheritance β which control how CSS is applied to HTML and how conflicts are resolved.
Cascade layers
This lesson aims to introduce you to cascade layers, a more advanced feature that builds on the fundamental concepts of the CSS cascade and CSS specificity.
The box model
Everything in CSS has a box around it, and understanding these boxes is key to being able to create layouts with CSS, or to align items with other items. In this lesson, we will take a proper look at the CSS *Box Model*, in order that you can move onto more complex layout tasks with an understanding of how it works and the terminology that relates to it.
Backgrounds and borders
In this lesson we will take a look at some of the creative things you can do with CSS backgrounds and borders. From adding gradients, background images, and rounded corners, backgrounds and borders are the answer to a lot of styling questions in CSS.
Handling different text directions
In recent years, CSS has evolved in order to better support different directionality of content, including right-to-left but also top-to-bottom content (such as Japanese) β these different directionalities are called **writing modes**. As you progress in your study and begin to work with layout, an understanding of writing modes will be very helpful to you, therefore we will introduce them in this article.
Overflowing content
In this lesson we will look at another important concept in CSS β **overflow**. Overflow is what happens when there is too much content to be contained comfortably inside a box. In this guide, you will learn what it is and how to manage it.
CSS values and units
Every property used in CSS has a value or set of values that are allowed for that property. In this lesson, we will take a look at some of the most common values and units in use.
Sizing items in CSS
In the various lessons so far you have come across a number of ways to size items on a web page using CSS. Understanding how big the different features in your design will be is important, and in this lesson, we will summarize the various ways elements get a size via CSS and define a few terms around sizing that will help you in the future.
Images, media, and form elements
In this lesson we will take a look at how certain special elements are treated in CSS. Images, other media, and form elements behave a little differently in terms of your ability to style them with CSS than regular boxes. Understanding what is and isn't possible can save some frustration, and this lesson will highlight some of the main things that you need to know.
Styling tables
Styling an HTML table isn't the most glamorous job in the world, but sometimes we all have to do it. This article provides a guide to making HTML tables look good, with some specific table styling techniques highlighted.
Debugging CSS
Sometimes when writing CSS you will encounter an issue where your CSS doesn't seem to be doing what you expect. This article will give you guidance on how to go about debugging a CSS problem, and show you how the DevTools included in all modern browsers can help you find out what is going on.
Organizing your CSS
As you start to work on larger stylesheets and big projects you will discover that maintaining a huge CSS file can be challenging. In this article, we will take a brief look at some best practices for writing your CSS to make it easily maintainable, and some of the solutions you will find in use by others to help improve maintainability.
Assessments
-----------
The following assessments will test your understanding of the CSS covered in the guides above.
Fundamental CSS comprehension
This assessment tests your understanding of basic syntax, selectors, specificity, box model, and more.
Creating fancy letterheaded paper
If you want to make the right impression, writing a letter on nice letterheaded paper can be a really good start. In this assessment, we'll challenge you to create an online template to achieve such a look.
A cool looking box
Here you'll get some practice in using background and border styling to create an eye-catching box.
See also
--------
Advanced styling effects
This article acts as a box of tricks, providing an introduction to some interesting advanced styling features such as box shadows, blend modes, and filters. |
CSS styling text - Learn web development | 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.
#### 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**
Prerequisites
-------------
Before starting this module, you should already have basic familiarity with HTML, as discussed in the Introduction to HTML module, and be comfortable with CSS fundamentals, as discussed in Introduction to CSS.
**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 or Glitch.
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
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
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
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
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
In this assessment we'll test your understanding of styling text by getting you to style the text for a community school's homepage. |
CSS layout - Learn web development | CSS layout
==========
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.
#### 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**
Prerequisites
-------------
Before starting this module, you should already:
1. Have basic familiarity with HTML, as discussed in the Introduction to HTML module.
2. Be comfortable with CSS fundamentals, as discussed in Introduction to CSS.
3. Understand how to style boxes.
**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 or Glitch.
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
This article will recap some of the CSS layout features we've already touched upon in previous modules β such as different `display` values β and introduce some of the concepts we'll be covering throughout this module.
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
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 to check your understanding before moving on.
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 before moving on.
Floats
Originally for floating images inside blocks of text, the `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
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 `position` values and how to use them.
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
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
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
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
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
An assessment to test your knowledge of different layout methods by laying out a webpage.
See also
--------
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
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. |
CSS first steps overview - Learn web development | CSS first steps overview
========================
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.
#### 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**
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, and an understanding of how to create and manage files, as detailed in Dealing with files.
3. Basic familiarity with HTML, as discussed in the 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 or Glitch.
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?
**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
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
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
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
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. |
Create fancy boxes - Learn web development | Create fancy boxes
==================
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. It's also a good idea, but not a prerequisite, to be familiar with some CSS layout basics.
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: `width`, `height`, `padding`, `border`, etc.
* Its background properties: `background`, `background-color`, `background-image`, `background-position`, `background-size`, etc.
* Its pseudo-element: `::before` and `::after`
* and some aside properties like: `box-shadow`, `rotate`, `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
```
<div class="fancy">Hi! I want to be fancy.</div>
```
This is something that is both very simple and very fun. The `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:
Backgrounds
-----------
When we talk about a fancy box, the core properties to handle that are background-\* properties. 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 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.
```
<div class="fancy">Hi! I want to be fancy.</div>
```
Okay, let's have fun with backgrounds:
```css
.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%);
}
```
**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. If you want to learn more about gradients, feel free to get into our dedicated article.
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.
### A cloud
```
<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;
}
```
### Blockquote
A more practical example of using pseudo-elements is to build a nice formatting for HTML `<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;
}
```
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:
```
<div class="fancy">Hi! I want to be fancy.</div>
```
Let's create some partial drop-shadow effects. The `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 `rotate` property, one of the three individual `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;
}
``` |
How to add a shadow to text - Learn web development | How to add a shadow to text
===========================
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, 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 β `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.
**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 for visitors who have difficulty with low-contrast text. |
How to highlight the first paragraph - Learn web development | How to highlight the first paragraph
====================================
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 `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 `:first-child`. This will select the element that is the first-child of a parent.
You can try changing `:first-child` to `: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 `pseudo-classes` can do it for you.
See also
--------
* The `pseudo-classes` reference page.
* Learn CSS: Pseudo-classes and pseudo-elements. |
How to highlight the first line of a paragraph - Learn web development | How to highlight the first line of a paragraph
==============================================
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 `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 `::first-line` pseudo-element. It selects the first formatted line of each paragraph, meaning that you can style it as you require.
**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 `:first-child` `pseudo-class`. This allows us to select the first line of the first child of `.wrapper` if that first child is a paragraph.
**Note:** When combining pseudo-elements with other selectors in a complex or compound selector, the pseudo-elements must appear after all the other components in the selector in which they appear.
See also
--------
* The `pseudo-elements` reference page.
* Learn CSS: Pseudo-classes and pseudo-elements. |
How to fill a box with an image without distorting it - Learn web development | How to fill a box with an image without distorting it
=====================================================
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 `<img>` element, the image will maintain the size and aspect ratio of the image file, or that of any HTML `width` or `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 `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. |
How to highlight a paragraph that comes after a heading - Learn web development | How to highlight a paragraph that comes after a heading
=======================================================
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 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. This combinator selects an element based on it being next to another element. In our HTML we have a h1 followed by a `<p>`. The `<p>` is the next sibling of the `<h1>` so we can select it with `h1 + p`.
See also
--------
* Learn CSS: Selectors.
* Learn CSS: Combinators. |
CSS FAQ - Learn web development | CSS FAQ
=======
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 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 than id selectors, so are easier to override if needed.
**Note:** See 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 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 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 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. 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 `<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.
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.
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 from our Cross-browser testing module.
**Note:** See the Mozilla CSS Extensions and WebKit CSS 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 learning article, and in particular the Introducing z-index section. |
How to make a box semi-transparent - Learn web development | How to make a box semi-transparent
==================================
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 `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>` 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.
**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. |
How to center an item - Learn web development | How to center an item
=====================
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 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 or grid container to turn on the ability to use alignment.
In the example below we have given the parent container `display: flex`; then set `justify-content` to center to align it horizontally, and `align-items` to center to align it vertically.
**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 `justify-content` and `align-items`.
See also
--------
* Box alignment in Flexbox
* Box alignment in Grid layout |
How to add a shadow to an element - Learn web development | How to add a shadow to an element
=================================
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 `box-shadow` property (if you want to add a shadow to the text itself, you need `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.
**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
* Learn CSS: Advanced styling effects. |
Using CSS generated content - Learn web development | Using CSS generated content
===========================
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 `<li>` or other element with `display: list-item;`. To specify this, make a rule and add `::before`, `::after`, or `::marker` to the selector. In the declaration, specify the `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
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 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 and Characters and case 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 `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");
}
``` |
How to fade a button on hover - Learn web development | How to fade a button on hover
=============================
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 `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 `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.
**Note:** The `transition` property is a shorthand for `transition-delay`, `transition-duration`, `transition-property`, and `transition-timing-function`. See the pages for these properties on MDN to find ways to tweak your transitions.
See also
--------
* Using CSS transitions |
Web fonts - Learn web development | Web fonts
=========
* Previous
* Overview: Styling text
* Next
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.
| | |
| --- | --- |
| Prerequisites: |
HTML basics (study
Introduction to HTML), CSS basics (study
Introduction to CSS),
CSS text and font fundamentals.
|
| Objective: |
To learn how to apply web fonts to a web page, using either a third
party service, or by writing your own code.
|
Font families recap
-------------------
As we looked at in Fundamental text and font styling, the fonts applied to your HTML can be controlled using the `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. 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 `@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 `@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 to investigate and manipulate the fonts in use on your page, whether they are web fonts or not. This video provides a nice walkthrough:
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 and web-font-start.css files as a starting point to add your code to (see the live example). 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, dafont, and Everything Fonts.
* A paid font distributor: This is a site that makes fonts available for a charge, such as fonts.com or myfonts.com. You can also buy fonts directly from font foundries, for example Linotype, Monotype, or Exljbris.
* 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 section for more details.
Let's find some fonts! Go to Font Squirrel 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.
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 for converting ttf to woff
2. fontforge for converting from ttf to svg
3. batik ttf2svg for converting from ttf to svg
4. 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.
![The finished design of a Web font active learning exercise. The page has two headings and three paragraphs. The page contains different fonts and text at different sizes.](/en-US/docs/Learn/CSS/Styling_text/Web_fonts/web-font-example.png)
**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 and web-font-finished.css. You can also download the code from GitHub or run the finished example live.
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 and Cloud.typography. Most of these services are subscription-based, with the notable exception of Google Fonts, 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.
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 `<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 and google-font.css, if you need to check your work against ours (see it live).
@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.
* `font-weight`/`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 `font-weight`/`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 by Roger Johansson shows what to do in more detail.
**Note:** You can also specify particular `font-variant` and `font-stretch` values for your web fonts. In newer browsers, you can also specify a `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 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.
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.
* Previous
* Overview: Styling text
* Next |
Typesetting a community school homepage - Learn web development | Typesetting a community school homepage
=======================================
* Previous
* Overview: 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.
| | |
| --- | --- |
| Prerequisites: |
Before attempting this assessment you should have already worked through
all the articles in this module.
|
| Objective: | To test comprehension of CSS text styling techniques. |
Starting point
--------------
To get this assessment started, you should:
* Go and grab the HTML and CSS files for the exercise, and the provided external link icon.
* Make a copy of them on your local computer.
Alternatively, you could use an online editor such as CodePen, JSFiddle, or Glitch.
You could paste the HTML and fill in the CSS into one of these online editors, and use this external link icon as a background image.
**Note:** If you get stuck, you can reach out to us in one of our 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:
![A screenshot of the finished design of the 'Community school website homepage' text styling assessment. The heading reads 'St Huxley's Community College'. There is a red line separating the banner header from the content. The main content has three columns. The first, widest column has a few paragraphs which imply the importance of college to Students. The second column has a list of links to the top course choices offered by the college. The third column contains a vertical navigation bar with rectangular outlined button links to different sections of the website.](/en-US/docs/Learn/CSS/Styling_text/Typesetting_a_homepage/example2.png)
* Previous
* Overview: Styling text |
Styling lists - Learn web development | Styling lists
=============
* Previous
* Overview: Styling text
* Next
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.
| | |
| --- | --- |
| Prerequisites: |
HTML basics (study
Introduction to HTML), CSS basics (study
Introduction to CSS),
CSS text and font fundamentals.
|
| Objective: |
To become familiar with the best practices and properties related to
styling lists.
|
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 (check out the source code 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, you'll notice a couple of styling defaults:
* The `<ul>` and `<ol>` elements have a top and bottom `margin` of `16px` (`1em`) and a `padding-left` of `40px` (`2.5em`). If the directionality attribute `dir` is set to right-to-left (`rtl`) for `ul` and `ol` elements, in that case `padding-right` comes into effect and its default value is `40px` (`2.5em`) .
* The list items (`<li>` elements) have no set defaults for spacing.
* The `<dl>` element has a top and bottom `margin` of `16px` (`1em`), but no padding set.
* The `<dd>` elements have `margin-left` of `40px` (`2.5em`).
* The `<p>` elements we've included for reference have a top and bottom `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 on GitHub, and find the source code 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 `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 `<ul>` or `<ol>` elements:
* `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.
* `list-style-position`: Sets whether the bullets, at the start of each item, appear inside or outside the lists.
* `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 `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:
![an ordered list with the bullet points set to appear outside the list item text.](/en-US/docs/Learn/CSS/Styling_text/Styling_lists/outer-bullets.png)
You can find a lot more options by checking out the `list-style-type` reference page.
### Bullet position
The `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;
}
```
![an ordered list with the bullet points set to appear inside the list item text.](/en-US/docs/Learn/CSS/Styling_text/Styling_lists/inner-bullets.png)
### Using a custom bullet image
The `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 `background` family of properties, which you've learned in the 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 `padding-left` of the `<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 `list-style-type` to `none`, so that no bullet appears by default. We're going to use `background` properties to handle the bullets instead.
* Inserted a bullet onto each unordered list item. The relevant properties are as follows:
+ `background-image`: This references the path to the image file you want to use as the bullet.
+ `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.
+ `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.
+ `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:
![an unordered list with the bullet points set as little star images](/en-US/docs/Learn/CSS/Styling_text/Styling_lists/list_formatting.png)
### list-style shorthand
The three properties mentioned above can all be set using a single shorthand property, `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` 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:
### reversed
The `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:
**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` 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:
**Note:** Even if you are using a non-number `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.
```
<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>
```
```
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);
```
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.
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:
* `@counter-style`
* `counter-increment`
* `counter-reset`
* Previous
* Overview: Styling text
* Next |
Styling links - Learn web development | Styling links
=============
* Previous
* Overview: Styling text
* Next
When styling links, 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.
| | |
| --- | --- |
| Prerequisites: |
HTML basics (study
Introduction to HTML), CSS basics (study
Introduction to CSS),
CSS text and font fundamentals.
|
| Objective: |
To learn how to style link states, and how to use links effectively in
common UI features like navigation menus.
|
Let's look at some links
------------------------
We looked at how links are implemented in your HTML according to best practices in 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:
* **Link**: A link that has a destination (i.e., not just a named anchor), styled using the `:link` pseudo class.
* **Visited**: A link that has already been visited (exists in the browser's history), styled using the `:visited` pseudo class.
* **Hover**: A link that is hovered over by a user's mouse pointer, styled using the `:hover` pseudo class.
* **Focus**: A link that is focused (e.g., moved to by a keyboard user using the
`Tab`
key or something similar, or programmatically focused using `HTMLElement.focus()`) β this is styled using the `:focus` pseudo class.
* **Active**: A link that is activated (e.g., clicked on), styled using the `: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
`option`
+
`tab`
, or enable the Full Keyboard Access: All controls option by pressing
`Ctrl`
+
`F7`
.)
* 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;
}
```
**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 `<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:
* `color` for the text color.
* `cursor` for the mouse pointer style β you shouldn't turn this off unless you've got a very good reason.
* `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:
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.
```
<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>
```
```
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);
```
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.
Let's look at some HTML and CSS that will give us the effect we want. First, some simple HTML to style:
```html
<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;
}
```
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 in the last article. This time, however, we're using the `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 `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 `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 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: `a[href^="http"]` selects `<a>` elements, but only if they have an `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 and responsive web 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:
The HTML defines a `<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. 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 `text-decoration` and `outline` β we don't want those spoiling our look.
+ The last three declarations are to center the text inside each link, set the `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 on your websites (or web fonts, as they are better known).
* Previous
* Overview: Styling text
* Next |
Fundamental text and font styling - Learn web development | Fundamental text and font styling
=================================
* Overview: Styling text
* Next
In this article we'll start you on your journey towards mastering text styling with 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.
| | |
| --- | --- |
| Prerequisites: |
HTML basics (study
Introduction to HTML), CSS basics (study
Introduction to CSS).
|
| Objective: |
To learn the fundamental properties and techniques needed to style text
on web pages.
|
What is involved in styling text in CSS?
----------------------------------------
Text inside an element is laid out inside the element's content 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 `<br>` element.
**Note:** If the above paragraph leaves you feeling confused, then no matter β go back and review our 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 `<span>` or `<strong>`), or use a text-specific pseudo-element like ::first-letter (selects the first letter of an element's text), ::first-line (selects the first line of an element's text), or ::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 (see also the source code).
### Color
The `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 `text-decoration` property.
`color` can accept any CSS color unit, for example:
```css
p {
color: red;
}
```
This will cause the paragraphs to become red, rather than the standard browser default of black, like so:
```
<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>
```
### Font families
To set a different font for your text, you use the `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. 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* initiative in the late 90s and early 2000s):
| Name | Generic type | Notes |
| --- | --- | --- |
| Arial | sans-serif |
It's often considered best practice to also add *Helvetica* as a
preferred alternative to *Arial* as, although their font faces
are almost identical, *Helvetica* is considered to have a nicer
shape, even if *Arial* is more broadly available.
|
| Courier New | monospace |
Some OSes have an alternative (possibly older) version of the
*Courier New* font called *Courier*. It's considered best
practice to use both with *Courier New* as the preferred
alternative.
|
| Georgia | serif | |
| Times New Roman | serif |
Some OSes have an alternative (possibly older) version of the
*Times New Roman* font called *Times*. It's considered
best practice to use both with *Times New Roman* as the preferred
alternative.
|
| Trebuchet MS | sans-serif |
You should be careful with using this font β it isn't widely available
on mobile OSes.
|
| Verdana | sans-serif | |
**Note:** Among various resources, the 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 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:
| Term | Definition | Example |
| --- | --- | --- |
| `serif` |
Fonts that have serifs (the flourishes and other small details you see
at the ends of the strokes in some typefaces).
|
```
My big red elephant
```
```
body {
font-family: serif;
}
```
|
| `sans-serif` | Fonts that don't have serifs. |
```
My big red elephant
```
```
body {
font-family: sans-serif;
}
```
|
| `monospace` |
Fonts where every character has the same width, typically used in code
listings.
|
```
My big red elephant
```
```
body {
font-family: monospace;
}
```
|
| `cursive` |
Fonts that are intended to emulate handwriting, with flowing, connected
strokes.
|
```
My big red elephant
```
```
body {
font-family: cursive;
}
```
|
| `fantasy` | Fonts that are intended to be decorative. |
```
My big red elephant
```
```
body {
font-family: fantasy;
}
```
|
#### 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 `<custom-ident>` or a `<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:
```
<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>
```
### Font size
In our previous module's CSS values and units article, we reviewed length and size units. Font size (set with the `font-size` property) can take values measured in most of these units (and others, such as 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. `<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 β `<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 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 `<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:
* `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.
* `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.
* `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).
* `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 `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 `text-decoration` is a shorthand property for `text-decoration-line`, `text-decoration-style`, and `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:
```
<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;
}
```
### Text drop shadows
You can apply drop shadows to your text using the `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, 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.
4. The base color of the shadow, which can take any CSS color unit. If not included, it defaults to `currentcolor`, i.e. the shadow's color is taken from the element's `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 h1 element in our Tommy The Cat example, we'd end up with this:
```
<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>
```
```
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;
}
```
**Note:** You can see more interesting examples of `text-shadow` usage in the Sitepoint article Moonlighting with 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 `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 `hyphens`, to break some of the longer words across lines.
If we applied `text-align: center;` to the h1 in our example, we'd end up with this:
```
<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
The `line-height` property sets the height of each line of text. This property can not only take most length and size units, but can also take a unitless value, which acts as a multiplier and is generally considered the best option. With a unitless value, the `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 `<p>` elements in our example would give us this result:
```
<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;
}
```
### Letter and word spacing
The `letter-spacing` and `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.
To illustrate, we could apply some word- and letter-spacing to the first line of each `<p>` element in our HTML sample with:
```css
p::first-line {
letter-spacing: 4px;
word-spacing: 4px;
}
```
This renders our HTML as:
```
<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;
}
```
### 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:
* `font-variant`: Switch between small caps and normal font alternatives.
* `font-kerning`: Switch font kerning options on and off.
* `font-feature-settings`: Switch various OpenType font features on and off.
* `font-variant-alternates`: Control the use of alternate glyphs for a given font-face.
* `font-variant-caps`: Control the use of alternate capital glyphs.
* `font-variant-east-asian`: Control the usage of alternate glyphs for East Asian scripts, like Japanese and Chinese.
* `font-variant-ligatures`: Control which ligatures and contextual forms are used in text.
* `font-variant-numeric`: Control the usage of alternate glyphs for numbers, fractions, and ordinal markers.
* `font-variant-position`: Control the usage of alternate glyphs of smaller sizes positioned as superscript or subscript.
* `font-size-adjust`: Adjust the visual size of the font independently of its actual font size.
* `font-stretch`: Switch between possible alternative stretched versions of a given font.
* `text-underline-position`: Specify the position of underlines set using the `text-decoration-line` property `underline` value.
* `text-rendering`: Try to perform some text rendering optimization.
Text layout styles:
* `text-indent`: Specify how much horizontal space should be left before the beginning of the first line of the text content.
* `text-overflow`: Define how overflowed content that is not displayed is signaled to users.
* `white-space`: Define how whitespace and associated line breaks inside the element are handled.
* `word-break`: Specify whether to break lines within words.
* `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.)
* `hyphens`: Switch on and off hyphenation for supported languages.
* `line-break`: Relax or strengthen line breaking for Asian languages.
* `text-align-last`: Define how the last line of a block or a line, right before a forced line break, is aligned.
* `text-orientation`: Define the orientation of the text in a line.
* `overflow-wrap`: Specify whether or not the browser may break lines within words in order to prevent overflow.
* `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 `font`. These are written in the following order: `font-style`, `font-variant`, `font-weight`, `font-stretch`, `font-size`, `line-height`, and `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 `font-size` and `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.
```
<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>
```
```
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);
```
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.
* Overview: Styling text
* Next |
CSS selectors - Learn web development | CSS selectors
=============
* Overview: Building blocks
* Next
In CSS, selectors are used to target the HTML elements on our web pages that we want to style. There are a wide variety of CSS selectors available, allowing for fine-grained precision when selecting elements to style. In this article and its sub-articles we'll run through the different types in great detail, seeing how they work.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: | To learn how CSS selectors work in detail. |
What is a selector?
-------------------
A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the *subject of the selector*.
![Some code with the h1 highlighted.](/en-US/docs/Learn/CSS/Building_blocks/Selectors/selector.png)
In other articles you may have met some different selectors, and learned that there are selectors that target the document in different ways β for example by selecting an element such as `h1`, or a class such as `.special`.
In CSS, selectors are defined in the CSS Selectors specification; like any other part of CSS they need to have support in browsers for them to work. The majority of selectors that you will come across are defined in the Level 3 Selectors specification and Level 4 Selectors specification, which are both mature specifications, therefore you will find excellent browser support for these selectors.
Selector lists
--------------
If you have more than one thing which uses the same CSS then the individual selectors can be combined into a *selector list* so that the rule is applied to all of the individual selectors. For example, if I have the same CSS for an `h1` and also a class of `.special`, I could write this as two separate rules.
```css
h1 {
color: blue;
}
.special {
color: blue;
}
```
I could also combine these into a selector list, by adding a comma between them.
```css
h1, .special {
color: blue;
}
```
White space is valid before or after the comma. You may also find the selectors more readable if each is on a new line.
```css
h1,
.special {
color: blue;
}
```
In the live example below try combining the two selectors which have identical declarations. The visual display should be the same after combining them.
When you group selectors in this way, if any selector is syntactically invalid, the whole rule will be ignored.
In the following example, the invalid class selector rule will be ignored, whereas the `h1` would still be styled.
```css
h1 {
color: blue;
}
..special {
color: blue;
}
```
When combined however, neither the `h1` nor the class will be styled as the entire rule is deemed invalid.
```css
h1, ..special {
color: blue;
}
```
Types of selectors
------------------
There are a few different groupings of selectors, and knowing which type of selector you might need will help you to find the right tool for the job. In this article's subarticles we will look at the different groups of selectors in more detail.
### Type, class, and ID selectors
Type selectors target an HTML element such as an `<h1>`:
```css
h1 {
}
```
Class selectors target an element that has a specific value for its `class` attribute:
```css
.box {
}
```
ID selectors target an element that has a specific value for its `id` attribute:
```css
#unique {
}
```
### Attribute selectors
This group of selectors gives you different ways to select elements based on the presence of a certain attribute on an element:
```css
a[title] {
}
```
Or even make a selection based on the presence of an attribute with a particular value:
```css
a[href="https://example.com"]
{
}
```
### Pseudo-classes and pseudo-elements
This group of selectors includes pseudo-classes, which style certain states of an element. The `:hover` pseudo-class for example selects an element only when it is being hovered over by the mouse pointer:
```css
a:hover {
}
```
It also includes pseudo-elements, which select a certain part of an element rather than the element itself. For example, `::first-line` always selects the first line of text inside an element (a `<p>` in the below case), acting as if a `<span>` was wrapped around the first formatted line and then selected.
```css
p::first-line {
}
```
### Combinators
The final group of selectors combine other selectors in order to target elements within our documents. The following, for example, selects paragraphs that are direct children of `<article>` elements using the child combinator (`>`):
```css
article > p {
}
```
Summary
-------
In this article we've introduced CSS selectors, which enable you to target particular HTML elements. Next, we'll take a closer look at type, class, and ID selectors.
For a complete list of selectors, see our CSS selectors reference.
* Overview: Building blocks
* Next |
Test your skills: Writing modes and logical properties - Learn web development | Test your skills: Writing modes and logical properties
======================================================
The aim of this skill test is to assess whether you understand how to handle different text directions using writing modes and logical properties in CSS.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, the box is displayed with a horizontal writing mode. Can you add a line of CSS to change it so it uses a vertical writing mode with right to left text?
Your final result should look like the image below:
![A box with a vertical writing mode](/en-US/docs/Learn/CSS/Building_blocks/Writing_Modes_Tasks/mdn-writing-modes1.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, we want you to use logical properties to replace `width` and `height` in order to maintain the aspect ratio of the box as it is turned vertically.
Your final result should look like the image below:
![Two boxes one horizontal the other vertical](/en-US/docs/Learn/CSS/Building_blocks/Writing_Modes_Tasks/mdn-writing-modes2.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 3
------
In this task, we want you to use logical versions of the margin, border, and padding properties so that the edges of the box relate to the text rather than following top, left, bottom and right.
Your final result should look like the image below:
![Two boxes one horizontal one vertical with different margin, border and padding](/en-US/docs/Learn/CSS/Building_blocks/Writing_Modes_Tasks/mdn-writing-modes3.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
A cool-looking box - Learn web development | A cool-looking box
==================
* Previous
* Overview: Building blocks
In this assessment, you'll get some more practice in creating cool-looking boxes by trying to create an eye-catching box.
| | |
| --- | --- |
| Prerequisites: |
Before attempting this assessment you should have already worked
through all the articles in this module.
|
| Objective: |
To test comprehension of the CSS box model and other box-related
features such as borders and backgrounds.
|
Starting point
--------------
To get this assessment started, you should:
* Make local copies of the starting HTML and CSS β save them as `index.html` and `style.css` in a new directory.
Alternatively, you could use an online editor such as CodePen, JSFiddle, or Glitch.
You could paste the HTML and fill in the CSS into one of these online editors.
**Note:** If you get stuck, you can reach out to us in one of our communication channels.
Project brief
-------------
Your task is to create a cool, fancy box and explore the fun we can have with CSS.
### General tasks
* Apply the CSS to the HTML.
### Styling the box
We'd like you to style the provided `<div>`, giving it the following:
* A reasonable width for a large box, say around 200 pixels.
* A reasonable height for a large box, centering the text vertically in the process.
* Center the box horizontally.
* Center the text within the box.
* A slight increase in font size, to around 17-18 pixel computed style. Use rems. Write a comment about how you worked out the value.
* A base color for the design. Give the box this color as its background color.
* A contrasting color for the text and a black text shadow.
* A fairly subtle border radius.
* A 1-pixel solid border with a color similar to the base color, but a slightly darker shade.
* A linear semi-transparent black gradient that goes toward the bottom right corner. Make it completely transparent at the start, grading to around 0.2 opacity by 30% along, and remaining at the same color until the end.
* Multiple box shadows. Give it one standard box shadow to make the box look slightly raised off the page. The other two should be inset box shadows β a semi-transparent white shadow near the top left and a semi-transparent black shadow near the bottom right β to add to the nice raised 3D look of the box.
Hints and tips
--------------
* Use the W3C CSS Validator to catch and fix mistakes in your CSS.
Example
-------
The following screenshot shows an example of what the finished design could look like:
![A big red box with rounded corners. White text with drop shadow reads 'this is a cool box'.](/en-US/docs/Learn/CSS/Building_blocks/A_cool_looking_box/fancy-box2.png)
* Previous
* Overview: Building blocks |
Images, media, and form elements - Learn web development | Images, media, and form elements
================================
* Previous
* Overview: Building blocks
* Next
In this lesson we will take a look at how certain special elements are treated in CSS. Images, other media, and form elements behave a little differently from regular boxes in terms of your ability to style them with CSS. Understanding what is and isn't possible can save some frustration, and this lesson will highlight some of the main things that you need to know.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: |
To understand the way that some elements behave unusually when styled
with CSS.
|
Replaced elements
-----------------
Images and video are described as **replaced elements**. This means that CSS cannot affect the internal layout of these elements β only their position on the page amongst other elements. As we will see however, there are various things that CSS can do with an image.
Certain replaced elements, such as images and video, are also described as having an **aspect ratio**. This means that it has a size in both the horizontal (x) and vertical (y) dimensions, and will be displayed using the intrinsic dimensions of the file by default.
Sizing images
-------------
As you already know from following these lessons, everything in CSS generates a box. If you place an image inside a box that is smaller or larger than the intrinsic dimensions of the image file in either direction, it will either appear smaller than the box, or overflow the box. You need to make a decision about what happens with the overflow.
In the example below we have two boxes, both 200 pixels in size:
* One contains an image which is smaller than 200 pixels β it is smaller than the box and doesn't stretch to fill it.
* The other is larger than 200 pixels and overflows the box.
So what can we do about the overflowing issue?
As we learned in our previous lesson, a common technique is to make the `max-width` of an image 100%. This will enable the image to become smaller in size than the box but not larger. This technique will also work with other replaced elements such as `<video>`s, or `<iframe>`s.
**Try adding `max-width: 100%` to the `<img>` element in the example above. You will see that the smaller image remains unchanged, but the larger one becomes smaller to fit into the box.**
You can make other choices about images inside containers. For example, you may want to size an image so it completely covers a box.
The `object-fit` property can help you here. When using `object-fit` the replaced element can be sized to fit a box in a variety of ways.
Below we have used the value `cover`, which sizes the image down, maintaining the aspect ratio so that it neatly fills the box. As the aspect ratio is maintained, some parts of the image will be cropped by the box.
If we use `contain` as a value, the image will be scaled down until it is small enough to fit inside the box. This will result in "letterboxing" if it is not the same aspect ratio as the box.
You could also try the value of `fill`, which will fill the box but not maintain the aspect ratio.
Replaced elements in layout
---------------------------
When using various CSS layout techniques on replaced elements, you may well find that they behave slightly differently from other elements. For example, in a flex or grid layout, elements are stretched by default to fill the entire area. Images will not stretch, and instead will be aligned to the start of the grid area or flex container.
You can see this happening in the example below where we have a two column, two row grid container, which has four items in it. All of the `<div>` elements have a background color and stretch to fill the row and column. The image, however, does not stretch.
If you are following these lessons in order then you may not have looked at layout yet. Just keep in mind that replaced elements, when they become part of a grid or flex layout, have different default behaviors, essentially to avoid them being stretched strangely by the layout.
To force the image to stretch to fill the grid cell it is in, you'd have to do something like the following:
```css
img {
width: 100%;
height: 100%;
}
```
This would, however, stretch the image, so it's probably not what you'd want to do.
Form elements
-------------
Form elements can be a tricky issue when it comes to styling with CSS. The Web Forms module contains detailed guides to the trickier aspects of styling these, which I will not fully reproduce here. There are, however, a few key basics worth highlighting in this section.
Many form controls are added to your page by way of the `<input>` element β this defines simple form fields such as text inputs, through to more complex fields such as color and date pickers. There are some additional elements, such as `<textarea>` for multiline text input, and also elements used to contain and label parts of forms such as `<fieldset>` and `<legend>`.
HTML also contains attributes that enable web developers to indicate which fields are required, and even the type of content that needs to be entered. If the user enters something unexpected, or leaves a required field blank, the browser can show an error message. Different browsers vary with one another in how much styling and customization they allow for such items.
### Styling text input elements
Elements that allow for text input, such as `<input type="text">`, and the more specific `<input type="email">`, and the `<textarea>` element are quite easy to style and tend to behave just like other boxes on your page. The default styling of these elements will differ, however, based on the operating system and browser that your user visits the site with.
In the example below we have styled some text inputs using CSS β you can see that things such as borders, margins and padding all apply as you would expect. We are using attribute selectors to target the different input types. Try changing how this form looks by adjusting the borders, adding background colors to the fields, and changing fonts and padding.
**Warning:** You should take care when changing the styling of form elements to make sure it is still obvious to the user they are form elements. You could create a form input with no borders and background that is almost indistinguishable from the content around it, but this would make it very hard to recognize and fill in.
As explained in the lessons on styling web forms, many of the more complex input types are rendered by the operating system and are inaccessible to styling. You should, therefore, always assume that forms are going to look quite different for different visitors and test complex forms in a number of browsers.
### Inheritance and form elements
In some browsers, form elements do not inherit font styling by default. Therefore, if you want to be sure that your form fields use the font defined on the body, or on a parent element, you should add this rule to your CSS.
```css
button,
input,
select,
textarea {
font-family: inherit;
font-size: 100%;
}
```
### Form elements and box-sizing
Across browsers, form elements use different box sizing rules for different widgets. You learned about the `box-sizing` property in our box model lesson and you can use this knowledge when styling forms to ensure a consistent experience when setting widths and heights on form elements.
For consistency, it is a good idea to set margins and padding to `0` on all elements, then add these back in when styling particular controls:
```css
button,
input,
select,
textarea {
box-sizing: border-box;
padding: 0;
margin: 0;
}
```
### Other useful settings
In addition to the rules mentioned above, you should also set `overflow: auto` on `<textarea>`s to stop IE showing a scrollbar when there is no need for one:
```css
textarea {
overflow: auto;
}
```
### Putting it all together into a "reset"
As a final step, we can wrap up the various properties discussed above into the following "form reset" to provide a consistent base to work from. This includes all the items mentioned in the last three sections:
```css
button,
input,
select,
textarea {
font-family: inherit;
font-size: 100%;
box-sizing: border-box;
padding: 0;
margin: 0;
}
textarea {
overflow: auto;
}
```
**Note:** Normalizing stylesheets are used by many developers to create a set of baseline styles to use on all projects. Typically these do similar things to those described above, making sure that anything different across browsers is set to a consistent default before you do your own work on the CSS. They are not as important as they once were, as browsers are typically more consistent than in the past. However if you want to take a look at one example, check out Normalize.css, which is a very popular stylesheet used as a base by many projects.
For further information on styling forms, take a look at the two articles in the HTML section of these guides.
* Styling web forms
* Advanced form styling
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Images and form elements.
Summary
-------
This lesson has highlighted some of the differences you will encounter when working with images, media, and other unusual elements in CSS.
In the next article, we'll learn how to style HTML tables.
* Previous
* Overview: Building blocks
* Next |
Test your skills: Backgrounds and borders - Learn web development | Test your skills: Backgrounds and borders
=========================================
The aim of this skill test is to assess whether you understand backgrounds and borders of boxes in CSS.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, we want you to add a background, border, and some simple styling to a page header:
1. Give the box a 5px black solid border, with rounded corners of 10px.
2. Add a background image (use the URL `balloons.jpg`) and size it so that it covers the box.
3. Give the `<h2>` a semi-transparent black background color, and make the text white.
Your final result should look like the image below:
![Images shows a box with a photograph background, rounded border and white text on a semi-transparent black background.](/en-US/docs/Learn/CSS/Building_blocks/Test_your_skills_backgrounds_and_borders/backgrounds-task1.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, we want you to add background images, a border, and some other styling to a decorative box:
* Give the box a 5px lightblue border and round the top left corner 20px and the bottom right corner 40px.
* The heading uses the `star.png` image as a background image, with a single centered star on the left and a repeating pattern of stars on the right.
* Make sure that the heading text does not overlay the image, and that it is centered β you will need to use techniques learned in previous lessons to achieve this.
Your final result should look like the image below:
![Images shows a box with a blue border rounded at the top left and bottom right corners. On the left of the text is a single star, on the right 3 stars.](/en-US/docs/Learn/CSS/Building_blocks/Test_your_skills_backgrounds_and_borders/backgrounds-task2.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Test your skills: The Cascade - Learn web development | Test your skills: The Cascade
=============================
The aim of this skill test is to assess whether you understand universal property values for controlling inheritance in CSS.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, we want you to use one of the special values we looked at in the controlling inheritance section. To write a declaration in a new rule that will reset the background color back to white, without using an actual color value.
Your final result should look like the image below:
![Barely visible yellow links on a white background.](/en-US/docs/Learn/CSS/Building_blocks/Cascade_tasks/mdn-cascade.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, we want you to make your changes by leveraging the order of cascade layers section. Edit an existing declaration, without touching the lightgreen declaration, using the cascade layer order to make the links rebeccapurple.
Your final result should look like the image below:
![Barely visible yellow links on a white background.](/en-US/docs/Learn/CSS/Building_blocks/Cascade_tasks/mdn-cascade.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Cascade, specificity, and inheritance - Learn web development | Cascade, specificity, and inheritance
=====================================
* Previous
* Overview: Building blocks
* Next
The aim of this lesson is to develop your understanding of some of the most fundamental concepts of CSS β the cascade, specificity, and inheritance β which control how CSS is applied to HTML and how conflicts between style declarations are resolved.
While working through this lesson may seem less relevant immediately and a little more academic than some other parts of the course, an understanding of these concepts will save you from a lot of pain later on! We encourage you to work through this section carefully and check that you understand the concepts before moving on.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: |
To learn about the cascade and specificity, and how inheritance works in
CSS.
|
Conflicting rules
-----------------
CSS stands for **Cascading Style Sheets**, and that first word *cascading* is incredibly important to understand β the way that the cascade behaves is key to understanding CSS.
At some point, you will be working on a project and you will find that the CSS you thought should be applied to an element is not working. Often, the problem is that you create two rules that apply different values of the same property to the same element. **Cascade** and the closely-related concept of **specificity** are mechanisms that control which rule applies when there is such a conflict. The rule that's styling your element may not be the one you expect, so you need to understand how these mechanisms work.
Also significant here is the concept of **inheritance**, which means that some CSS properties by default inherit values set on the current element's parent element and some don't. This can also cause some behavior that you might not expect.
Let's start by taking a quick look at the key things we are dealing with, then we'll look at each in turn and see how they interact with each other and your CSS. These can seem like a tricky set of concepts to understand. As you get more practice writing CSS, the way it works will become more obvious to you.
### Cascade
Stylesheets **cascade** β at a very simple level, this means that the origin, the cascade layer, and the order of CSS rules matter. When two rules from the same cascade layer apply and both have equal specificity, the one that is defined last in the stylesheet is the one that will be used.
In the below example, we have two rules that could apply to the `<h1>` element. The `<h1>` content ends up being colored blue. This is because both the rules are from the same source, have an identical element selector, and therefore, carry the same specificity, but the last one in the source order wins.
### Specificity
Specificity is the algorithm that the browser uses to decide which property value is applied to an element. If multiple style blocks have different selectors that configure the same property with different values and target the same element, specificity decides the property value that gets applied to the element. Specificity is basically a measure of how specific a selector's selection will be:
* An element selector is less specific; it will select all elements of that type that appear on a page, so it has less weight. Pseudo-element selectors have the same specificity as regular element selectors.
* A class selector is more specific; it will select only the elements on a page that have a specific `class` attribute value, so it has more weight. Attribute selectors and pseudo-classes have the same weight as a class.
Below, we again have two rules that could apply to the `<h1>` element. The `<h1>` content below ends up being colored red because the class selector `main-heading` gives its rule a higher specificity. So even though the rule with the `<h1>` element selector appears further down in the source order, the one with the higher specificity, defined using the class selector, will be applied.
We'll explain the specificity algorithm later on.
### Inheritance
Inheritance also needs to be understood in this context β some CSS property values set on parent elements are inherited by their child elements, and some aren't.
For example, if you set a `color` and `font-family` on an element, every element inside it will also be styled with that color and font, unless you've applied different color and font values directly to them.
Some properties do not inherit β for example, if you set a `width` of 50% on an element, all of its descendants do not get a width of 50% of their parent's width. If this was the case, CSS would be very frustrating to use!
**Note:** On MDN CSS property reference pages, you can find a technical information box called "Formal definition", which lists a number of data points about that property, including whether it is inherited or not. See the color property Formal definition section as an example.
Understanding how the concepts work together
--------------------------------------------
These three concepts (cascade, specificity, and inheritance) together control which CSS applies to what element. In the sections below, we'll see how they work together. It can sometimes seem a little bit complicated, but you will start to remember them as you get more experienced with CSS, and you can always look up the details if you forget! Even experienced developers don't remember all the details.
The following video shows how you can use the Firefox DevTools to inspect a page's cascade, specificity, and more:
Understanding inheritance
-------------------------
We'll start with inheritance. In the example below, we have a `<ul>` element with two levels of unordered lists nested inside it. We have given the outer `<ul>` a border, padding, and font color.
The `color` property is an inherited property. So, the `color` property value is applied to the direct children and also to the indirect children β the immediate child `<li>`s and those inside the first nested list. We have then added the class `special` to the second nested list and applied a different color to it. This then inherits down through its children.
Properties like `width` (as mentioned earlier), `margin`, `padding`, and `border` are not inherited properties. If a border were to be inherited by the children in this list example, every single list and list item would gain a border β probably not an effect we would ever want!
Though every CSS property page lists whether or not the property is inherited, you can often guess the same intuitively if you know what aspect the property value will style.
### Controlling inheritance
CSS provides five special universal property values for controlling inheritance. Every CSS property accepts these values.
`inherit`
Sets the property value applied to a selected element to be the same as that of its parent element. Effectively, this "turns on inheritance".
`initial`
Sets the property value applied to a selected element to the initial value of that property.
`revert`
Resets the property value applied to a selected element to the browser's default styling rather than the defaults applied to that property. This value acts like `unset` in many cases.
`revert-layer`
Resets the property value applied to a selected element to the value established in a previous cascade layer.
`unset`
Resets the property to its natural value, which means that if the property is naturally inherited it acts like `inherit`, otherwise it acts like `initial`.
**Note:** See Origin types for more information on each of these and how they work.
We can look at a list of links and explore how universal values work. The live example below allows you to play with the CSS and see what happens when you make changes. Playing with code really is the best way to better understand HTML and CSS.
For example:
1. The second list item has the class `my-class-1` applied. This sets the color of the `<a>` element nested inside to `inherit`. If you remove the rule, how does it change the color of the link?
2. Do you understand why the third and fourth links are the color that they are? The third link is set to `initial`, which means it uses the initial value of the property (in this case black) and not the browser default for links, which is blue. The fourth is set to `unset` which means that the link text uses the color of the parent element, green.
3. Which of the links will change color if you define a new color for the `<a>` element β for example `a { color: red; }`?
4. After reading the next section on resetting all properties, come back and change the `color` property to `all`. Notice how the second link is on a new line and has a bullet. What properties do you think were inherited?
### Resetting all property values
The CSS shorthand property `all` can be used to apply one of these inheritance values to (almost) all properties at once. Its value can be any one of the inheritance values (`inherit`, `initial`, `revert`, `revert-layer`, or `unset`). It's a convenient way to undo changes made to styles so that you can get back to a known starting point before beginning new changes.
In the below example, we have two blockquotes. The first has styling applied to the blockquote element itself. The second has a class applied to the blockquote, which sets the value of `all` to `unset`.
Try setting the value of `all` to some of the other available values and observe what the difference is.
Understanding the cascade
-------------------------
We now understand that inheritance is why a paragraph nested deep in the structure of your HTML is the same color as the CSS applied to the body. From the introductory lessons, we have an understanding of how to change the CSS applied to something at any point in the document β whether by assigning CSS to an element or by creating a class. We will now look at how cascade defines which CSS rules apply when more than one style block apply the same property, but with different values, to the same element.
There are three factors to consider, listed here in increasing order of importance. Later ones overrule earlier ones:
1. **Source order**
2. **Specificity**
3. **Importance**
We will look at these to see how browsers figure out exactly what CSS should be applied.
### Source order
We have already seen how source order matters to the cascade. If you have more than one rule, all of which have exactly the same weight, then the one that comes last in the CSS will win. You can think of this as: the rule that is nearer the element itself overwrites the earlier ones until the last one wins and gets to style the element.
Source order only matters when the specificity weight of the rules is the same, so let's look at specificity:
### Specificity
You will often run into a situation where you know that a rule comes later in the stylesheet, but an earlier, conflicting rule is applied. This happens because the earlier rule has a **higher specificity** β it is more specific, and therefore, is being chosen by the browser as the one that should style the element.
As we saw earlier in this lesson, a class selector has more weight than an element selector, so the properties defined in the class style block will override those defined in the element style block.
Something to note here is that although we are thinking about selectors and the rules that are applied to the text or component they select, it isn't the entire rule that is overwritten, only the properties that are declared in multiple places.
This behavior helps avoid repetition in your CSS. A common practice is to define generic styles for the basic elements, and then create classes for those that are different. For example, in the stylesheet below, we have defined generic styles for level 2 headings, and then created some classes that change only some of the properties and values. The values defined initially are applied to all headings, then the more specific values are applied to the headings with the classes.
Let's now have a look at how the browser will calculate specificity. We already know that an element selector has low specificity and can be overwritten by a class. Essentially a value in points is awarded to different types of selectors, and adding these up gives you the weight of that particular selector, which can then be assessed against other potential matches.
The amount of specificity a selector has is measured using three different values (or components), which can be thought of as ID, CLASS, and ELEMENT columns in the hundreds, tens, and ones place:
* **Identifiers**: Score one in this column for each ID selector contained inside the overall selector.
* **Classes**: Score one in this column for each class selector, attribute selector, or pseudo-class contained inside the overall selector.
* **Elements**: Score one in this column for each element selector or pseudo-element contained inside the overall selector.
**Note:** The universal selector (`*`), combinators (`+`, `>`, `~`, ' '), and specificity adjustment selector (`:where()`) along with its parameters, have no effect on specificity.
The negation (`:not()`), relational selector (`:has()`), the matches-any (`:is()`) pseudo-classes, and CSS nesting themselves don't add to specificity, but their parameters or nested rules do. The specificity weight that each contributes to the specificity algorithm is the specificity weight of the selector in the parameter or nested rule with the greatest weight.
The following table shows a few isolated examples to get you in the mood. Try going through these, and make sure you understand why they have the specificity that we have given them. We've not covered selectors in detail yet, but you can find details of each selector on the MDN selectors reference.
| Selector | Identifiers | Classes | Elements | Total specificity |
| --- | --- | --- | --- | --- |
| `h1` | 0 | 0 | 1 | 0-0-1 |
| `h1 + p::first-letter` | 0 | 0 | 3 | 0-0-3 |
| `li > a[href*="en-US"] > .inline-warning` | 0 | 2 | 2 | 0-2-2 |
| `#identifier` | 1 | 0 | 0 | 1-0-0 |
| `button:not(#mainBtn, .cta`) | 1 | 0 | 1 | 1-0-1 |
Before we move on, let's look at an example in action.
So what's going on here? First of all, we are only interested in the first seven rules of this example, and as you'll notice, we have included their specificity values in a comment before each one.
* The first two selectors are competing over the styling of the link's background color. The second one wins and makes the background color blue because it has an extra ID selector in the chain: its specificity is 2-0-1 vs. 1-0-1.
* Selectors 3 and 4 are competing over the styling of the link's text color. The second one wins and makes the text white because although it has one less element selector, the missing selector is swapped out for a class selector, which has more weight than infinity element selectors. The winning specificity is 1-1-3 vs. 1-0-4.
* Selectors 5β7 are competing over the styling of the link's border when hovered. Selector 6 clearly loses to selector 5 with a specificity of 0-2-3 vs. 0-2-4; it has one fewer element selectors in the chain. Selector 7, however, beats both selectors 5 and 6 because it has the same number of sub-selectors in the chain as selector 5, but an element has been swapped out for a class selector. So the winning specificity is 0-3-3 vs. 0-2-3 and 0-2-4.
**Note:** Each selector type has its own level of specificity that cannot be overwritten by selectors with a lower specificity level. For example, a *million* **class** selectors combined would not be able to overwrite the specificity of *one* **id** selector.
The best way to evaluate specificity is to score the specificity levels individually starting from the highest and moving on to the lowest when necessary. Only when there is a tie between selector scores within a specificity column do you need to evaluate the next column down; otherwise, you can disregard the lower specificity selectors since they can never overwrite the higher specificity selectors.
### Inline styles
Inline styles, that is, the style declaration inside a `style` attribute, take precedence over all normal styles, no matter the specificity. Such declarations don't have selectors, but their specificity can be construed as 1-0-0-0; always more than any other specificity weight no matter how many IDs are in the selectors.
### !important
There is a special piece of CSS that you can use to overrule all of the above calculations, even inline styles - the `!important` flag. However, you should be very careful while using it. This flag is used to make an individual property and value pair the most specific rule, thereby overriding the normal rules of the cascade, including normal inline styles.
**Note:** It is useful to know that the `!important` flag exists so that you know what it is when you come across it in other people's code. **However, we strongly recommend that you never use it unless you absolutely have to.** The `!important` flag changes the way the cascade normally works, so it can make debugging CSS problems really hard to work out, especially in a large stylesheet.
Take a look at this example where we have two paragraphs, one of which has an ID.
Let's walk through this to see what's happening β try removing some of the properties to see what happens if you are finding it hard to understand:
1. You'll see that the third rule's `color` and `padding` values have been applied, but the `background-color` hasn't. Why? Really, all three should surely apply because rules later in the source order generally override earlier rules.
2. However, the rules above it win because class selectors have higher specificity than element selectors.
3. Both elements have a `class` of `better`, but the 2nd one has an `id` of `winning` too. Since IDs have an *even higher* specificity than classes (you can only have one element with each unique ID on a page, but many elements with the same class β ID selectors are *very specific* in what they target), the red background color and the 1px black border should both be applied to the 2nd element, with the first element getting the gray background color, and no border, as specified by the class.
4. The 2nd element *does* get the red background color, but no border. Why? Because of the `!important` flag in the second rule. Adding the `!important` flag after `border: none` means that this declaration will win over the `border` value in the previous rule, even though the ID selector has higher specificity.
**Note:** The only way to override an important declaration is to include another important declaration with the *same specificity* later in the source order, or one with higher specificity, or to include an important declaration in a prior cascade layer (we haven't covered cascade layers yet).
One situation in which you may have to use the `!important` flag is when you are working on a CMS where you can't edit the core CSS modules, and you really want to override an inline style or an important declaration that can't be overridden in any other way. But really, don't use it if you can avoid it.
The effect of CSS location
--------------------------
Finally, it is important to note that the precedence of a CSS declaration depends on what stylesheet and cascade layer it is specified in.
It is possible for users to set custom stylesheets to override the developer's styles. For example, a visually impaired user might want to set the font size on all web pages they visit to be double the normal size to allow for easier reading.
It is also possible to declare developer styles in cascade layers: you can make non-layered styles override styles declared in layers or you can make styles declared in later layers override styles from earlier declared layers. For example, as a developer you may not be able to edit a third-party stylesheet, but you can import the external stylesheet into a cascade layer so that all of your styles easily override the imported styles without worrying about third-party selector specificity.
### Order of overriding declarations
Conflicting declarations will be applied in the following order, with later ones overriding earlier ones:
1. Declarations in user agent style sheets (e.g., the browser's default styles, used when no other styling is set).
2. Normal declarations in user style sheets (custom styles set by a user).
3. Normal declarations in author style sheets (these are the styles set by us, the web developers).
4. Important declarations in author style sheets.
5. Important declarations in user style sheets.
6. Important declarations in user agent style sheets.
**Note:** The order of precedence is inverted for styles flagged with `!important`. It makes sense for web developers' stylesheets to override user stylesheets, so the design can be kept as intended; however, sometimes users have good reasons to override web developer styles, as mentioned above, and this can be achieved by using `!important` in their rules.
### Order of cascade layers
Even though cascade layers is an advanced topic and you might not use this feature right away, it's important to understand how layers cascade.
When you declare CSS in cascade layers, the order of precedence is determined by the order in which the layers are declared. CSS styles declared outside of any layer are combined together, in the order in which those styles are declared, into an unnamed layer, as if it were the last declared layer. With competing normal (not important) styles, later layers take precedence over earlier defined layers. For styles flagged with `!important`, however, the order is reversed, with important styles in earlier layers taking precedence over important styles declared in subsequent layers or outside of any layer. Inline styles take precedence over all author styles, no matter the layer.
When you have multiple style blocks in different layers providing competing values for a property on a single element, the order in which the layers are declared determines the precedence. Specificity between layers doesn't matter, but specificity within a single layer still does.
Let's discuss a few things from the above example to understand what's happening. Two layers have been declared, `firstLayer` and `secondLayer`, in that order. Even though the specificity in `secondLayer` is the highest, no properties from that declaration are used. Why? Because non-layered normal styles take precedence over layered normal styles, no matter the specificity, and important layered styles take precedence over important styles declared in later layers, again, no matter the specificity.
If you change the first line of CSS in this example to read `@layer secondLayer, firstLayer;`, you will change the layer declaration order, and all the important styles from `firstLayer` will be changed to their respective values in `secondLayer`.
### Scoping proximity
Another advanced topic that you might not use right away but may need to understand in the future is `@scope`. This is an at-rule that enables you to create a block of rules that will only apply to a specific subsection of the HTML on your page. For example, you can specify styles that will only apply to `<img>` elements when they're nested inside elements that have a `feature` class:
```css
@scope (.feature) {
img {
border: 2px solid black;
display: block;
}
}
```
**Scoping proximity** is the mechanism that resolves conflicts between scoped elements. Scoping proximity states that when two scopes have conflicting styles, the style with the smallest number of hops up the DOM tree hierarchy to the scope root wins. See How `@scope` conflicts are resolved for more details and an example.
**Note:** Scoping proximity overrules source order but is itself overridden by other, higher-priority criteria such as importance, layers, and specificity.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: The Cascade.
Summary
-------
If you understood most of this article, then well done β you've started getting familiar with the fundamental mechanics of CSS. Next up, we'll take a deeper look at Cascade Layers.
If you didn't fully understand the cascade, specificity, and inheritance, then don't worry! This is definitely the most complicated thing we've covered so far in the course and is something that even professional web developers sometimes find tricky. We'd advise that you return to this article a few times as you continue through the course, and keep thinking about it.
Refer back here if you start to come across strange issues with styles not applying as expected. It could be a specificity issue.
* Previous
* Overview: Building blocks
* Next |
Test your skills: Images and form elements - Learn web development | Test your skills: Images and form elements
==========================================
The aim of this skill test is to assess whether you understand how special elements like images, media and form elements are treated in CSS.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, you have an image that is overflowing the box. We want the image to scale down to fit inside the box without any extra white space, but we do not mind if some part of the image is cropped.
Your final result should look like the image below:
![An image in a box](/en-US/docs/Learn/CSS/Building_blocks/Images_tasks/mdn-images-object-fit.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, you have a simple form. Your task is to make the following changes:
* Use attribute selectors to target the search field and button inside `.myform`.
* Make the form field and button use the same text size as the rest of the form.
* Give the form field and button 10 px of padding.
* Give the button a background of `rebeccapurple`, white foreground, no border and rounded corners of 5px.
Your final result should look like the image below:
![A single line form](/en-US/docs/Learn/CSS/Building_blocks/Images_tasks/mdn-images-form.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Overflowing content - Learn web development | Overflowing content
===================
* Previous
* Overview: Building blocks
* Next
Overflow is what happens when there is too much content to fit in an element box. In this guide, you will learn what overflow is and how to manage it.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: | To understand overflow and how to manage it. |
What is overflow?
-----------------
Everything in CSS is a box. You can constrain the size of these boxes by assigning values of `width` and `height` (or `inline-size` and `block-size`). **Overflow happens when there is too much content to fit in a box.** CSS provides various tools to manage overflow. As you go further with CSS layout and writing CSS, you will encounter more overflow situations.
CSS tries to avoid "data loss"
------------------------------
Let's consider two examples that demonstrate the default behavior of CSS when there is overflow.
The first example is a box that has been restricted by setting a `height`. Then we add content that exceeds the allocated space. The content overflows the box and falls into the paragraph below.
The second example is a word in a box. The box has been made too small for the word and so it breaks out of the box.
You might wonder why CSS works in such a messy way, displaying content outside of its intended container. Why not hide overflowing content? Why not scale the size of the container to fit all the content?
Wherever possible, CSS does not hide content. This would cause data loss. The problem with data loss is that you might not notice. Website visitors may not notice. If the submit button on a form disappears and no one can complete the form, this could be a big problem! Instead, CSS overflows in visible ways. You are more likely to see there is a problem. At worst, a site visitor will let you know that content is overlapping.
If you restrict a box with a `width` or a `height`, CSS trusts you to know what you are doing. CSS assumes that you are managing the potential for overflow. In general, restricting the block dimension is problematic when the box contains text. There may be more text than you expected when designing the site, or the text may be larger (for example, if the user has increased their font size).
The next two lessons explain different approaches to control sizing in ways that are less prone to overflow. However, if you need a fixed size, you can also control how the overflow behaves. Let's read on!
The overflow property
---------------------
The `overflow` property helps you manage an element's content overflow. Using this property, you can convey to a browser how it should handle overflow content. The default value of the `<overflow>` value type is `visible`. With this default setting, one can see content when it overflows.
To crop content when it overflows, you can set `overflow: hidden`. This does exactly what it says: it hides overflow. Beware that this can make some content invisible. You should only do this if hiding content won't cause problems.
Instead, perhaps you would like to add scrollbars when content overflows? Using `overflow: scroll`, browsers with visible scrollbars will always display themβeven if there is not enough content to overflow. This offers the advantage of keeping the layout consistent, instead of scrollbars appearing or disappearing, depending upon the amount of content in the container.
**Remove some content from the box below. Notice how the scrollbars remain, even if there is no need for scrolling.**
In the example above, we only need to scroll on the `y` axis, however we get scrollbars in both axes. To just scroll on the `y` axis, you could use the `overflow-y` property, setting `overflow-y: scroll`.
You can also enable scrolling along the x-axis by using `overflow-x`, although this is not a recommended way to accommodate long words! If you have a long word in a small box, consider using the `word-break` or `overflow-wrap` property. In addition, some of the methods discussed in Sizing items in CSS may help you create boxes that scale better with varying amounts of content.
As with `scroll`, you get a scrollbar in the scrolling dimension whether or not there is enough content to cause a scrollbar.
**Note:** You can specify x- and y-axis scrolling using the `overflow` property, passing two values. If two keywords are specified, the first applies to `overflow-x` and the second applies to `overflow-y`. Otherwise, both `overflow-x` and `overflow-y` are set to the same value. For example, `overflow: scroll hidden` would set `overflow-x` to `scroll` and `overflow-y` to `hidden`.
If you only want scrollbars to appear when there is more content than can fit in the box, use `overflow: auto`. This allows the browser to determine if it should display scrollbars.
**In the example below, remove content until it fits into the box. You should see the scrollbars disappear.**
Overflow establishes a Block Formatting Context
-----------------------------------------------
When you use the `<overflow>` values `scroll` and `auto`, you create a **Block Formatting Context** (BFC). This means that the content of an element box with these `overflow` values acquires a self-contained layout. Content outside such an element box cannot poke into the element box, and nothing from the element box can poke into the surrounding layout. This enables scrolling behavior, as all box content needs to be contained and not overlap to create a consistent scrolling experience.
Unwanted overflow in web design
-------------------------------
Modern layout methods (described in CSS layout) manage overflow. They largely work without assumptions or dependencies for how much content there will be on a web page.
This was not always the norm. In the past, some sites were built with fixed-height containers to align box bottoms. These boxes may otherwise have had no relationship to each other. This was fragile. If you encounter a box where content is overlaying other content on the page in legacy applications, you will now recognize that this happens with overflow. Ideally, you will refactor the layout to not rely on fixed-height containers.
When developing a site, always keep overflow in mind. Test designs with large and small amounts of content. Increase and decrease font sizes by at least two increments. Ensure your CSS is robust. Changing overflow values to hide content or to add scrollbars is reserved for a few select use cases (for example, where you intend to have a scrolling box).
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Overflow.
Summary
-------
This lesson introduced the concept of overflow. You should understand that default CSS avoids making overflowing content invisible. You have discovered that you can manage potential overflow, and also, that you should test work to make sure it does not accidentally cause problematic overflow.
In the next article, we'll take a look at the most common values and units in CSS.
* Previous
* Overview: Building blocks
* Next |
Styling tables - Learn web development | Styling tables
==============
* Previous
* Overview: Building blocks
* Next
Styling an HTML table isn't the most glamorous job in the world, but sometimes we all have to do it. This article provides a guide to making HTML tables look good, with some specific table styling techniques highlighted.
| | |
| --- | --- |
| Prerequisites: |
HTML basics (study
Introduction to HTML), knowledge of
HTML tables, and an idea of
how CSS works (study CSS first steps.)
|
| Objective: | To learn how to effectively style HTML tables. |
A typical HTML table
--------------------
Let's start by looking at a typical HTML table. Well, I say typical β most HTML table examples are about shoes, or the weather, or employees; we decided to make things more interesting by making it about famous punk bands from the UK. The markup looks like so:
```html
<table>
<caption>
A summary of the UK's most famous punk bands
</caption>
<thead>
<tr>
<th scope="col">Band</th>
<th scope="col">Year formed</th>
<th scope="col">No. of Albums</th>
<th scope="col">Most famous song</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Buzzcocks</th>
<td>1976</td>
<td>9</td>
<td>Ever fallen in love (with someone you shouldn't've)</td>
</tr>
<tr>
<th scope="row">The Clash</th>
<td>1976</td>
<td>6</td>
<td>London Calling</td>
</tr>
<!-- several other great bands -->
<tr>
<th scope="row">The Stranglers</th>
<td>1974</td>
<td>17</td>
<td>No More Heroes</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row" colspan="2">Total albums</th>
<td colspan="2">77</td>
</tr>
</tfoot>
</table>
```
The table is nicely marked up, easily stylable, and accessible, thanks to features such as `scope`, `<caption>`, `<thead>`, `<tbody>`, etc. Unfortunately, it doesn't look good when rendered on the screen (see it live at punk-bands-unstyled.html):
![an unstyled table showing a summary of Uk's famous punk bands](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables/table-unstyled.png)
With only the default browser styling it looks cramped, hard to read, and boring. We need to use some CSS to fix this up.
Styling our table
-----------------
Let's work through styling our table example together.
1. To start with, make a local copy of the sample markup, download both images (noise and leopardskin), and put the three resulting files in a working directory somewhere on your local computer.
2. Next, create a new file called `style.css` and save it in the same directory as your other files.
3. Link the CSS to the HTML by placing the following line of HTML inside your `<head>`:
```html
<link href="style.css" rel="stylesheet" />
```
### Spacing and layout
The first thing we need to do is sort out the spacing/layout β default table styling is so cramped! To do this, add the following CSS to your `style.css` file:
```css
/\* spacing \*/
table {
table-layout: fixed;
width: 100%;
border-collapse: collapse;
border: 3px solid purple;
}
thead th:nth-child(1) {
width: 30%;
}
thead th:nth-child(2) {
width: 20%;
}
thead th:nth-child(3) {
width: 15%;
}
thead th:nth-child(4) {
width: 35%;
}
th,
td {
padding: 20px;
}
```
The most important parts to note are as follows:
* A `table-layout` value of `fixed` is generally a good idea to set on your table, as it makes the table behave a bit more predictably by default. Normally, table columns tend to be sized according to how much content they contain, which produces some strange results. With `table-layout: fixed`, you can size your columns according to the width of their headings, and then deal with their content as appropriate. This is why we've selected the four different headings with the `thead th:nth-child(n)` (`:nth-child`) selector ("Select the n-th child that is a `<th>` element in a sequence, inside a `<thead>` element") and given them set percentage widths. The entire column width follows the width of its heading, making for a nice way to size your table columns. Chris Coyier discusses this technique in more detail in Fixed Table Layouts.
We've coupled this with a `width` of 100%, meaning that the table will fill any container it is put in, and be nicely responsive (although it would still need some more work to get it looking good on narrow screen widths).
* A `border-collapse` value of `collapse` is standard best practice for any table styling effort. By default, when you set borders on table elements, they will all have spacing between them, as the below image illustrates:
![a 2 by 2 table with default spacing between the borders showing no border collapse](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables/no-border-collapse.png) This doesn't look very nice (although it might be the look you want, who knows?). With `border-collapse: collapse;` set, the borders collapse down into one, which looks much better:
![a 2 by 2 table with border-collapse property set to collapse showing borders collapse into one](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables/border-collapse.png)
* We've put a `border` around the whole table, which is needed because we'll be putting some borders round the table header and footer later on β it looks really odd and disjointed when you don't have a border round the whole outside of the table and end up with gaps.
* We've set some `padding` on the `<th>` and `<td>` elements β this gives the data items some space to breathe, making the table look a lot more legible.
At this point, our table already looks a lot better:
![a semi-styled table with spacing to make the data more legible and showing a summary of Uk's famous punk bands](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables/table-with-spacing.png)
### Some simple typography
Now we'll get our text sorted out a bit.
First of all, we've found a font on Google Fonts that is suitable for a table about punk bands. You can go there and find a different one if you like; you'll just have to replace our provided `<link>` element and custom `font-family` declaration with the ones Google Fonts gives you.
First, add the following `<link>` element into your HTML head, just above your existing `<link>` element:
```html
<link
href="https://fonts.googleapis.com/css?family=Rock+Salt"
rel="stylesheet"
type="text/css" />
```
Now add the following CSS into your `style.css` file, below the previous addition:
```css
/\* typography \*/
html {
font-family: "helvetica neue", helvetica, arial, sans-serif;
}
thead th,
tfoot th {
font-family: "Rock Salt", cursive;
}
th {
letter-spacing: 2px;
}
td {
letter-spacing: 1px;
}
tbody td {
text-align: center;
}
tfoot th {
text-align: right;
}
```
There is nothing really specific to tables here; we are generally tweaking the font styling to make things easier to read:
* We have set a global sans-serif font stack; this is purely a stylistic choice. We've also set our custom font on the headings inside the `<thead>` and `<tfoot>` elements, for a nice grungy, punky look.
* We've set some `letter-spacing` on the headings and cells, as we feel it aids readability. Again, mostly a stylistic choice.
* We've center-aligned the text in the table cells inside the `<tbody>` so that they line up with the headings. By default, cells are given a `text-align` value of `left`, and headings are given a value of `center`, but generally it looks better to have the alignments set the same for both. The default bold weight on the heading fonts is enough to differentiate their look.
* We've right-aligned the heading inside the `<tfoot>` so that it is visually associated better with its data point.
The result looks a bit neater:
![a styled table with a global sans-serif font stack and good spacing to make the data more legible and showing a summary of Uk's famous punk bands](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables/table-with-typography.png)
### Graphics and colors
Now onto graphics and colors! Because the table is full of punk and attitude, we need to give it some bright imposing styling to suit it. Don't worry, you don't have to make your tables this loud β you can opt for something more subtle and tasteful.
Start by adding the following CSS to your `style.css` file, again at the bottom:
```css
/\* graphics and colors \*/
thead,
tfoot {
background: url(leopardskin.jpg);
color: white;
text-shadow: 1px 1px 1px black;
}
thead th,
tfoot th,
tfoot td {
background: linear-gradient(to bottom, rgb(0 0 0 / 10%), rgb(0 0 0 / 50%));
border: 3px solid purple;
}
```
Again, there's nothing specific to tables here, but it is worthwhile to note a few things.
We've added a `background-image` to the `<thead>` and `<tfoot>`, and changed the `color` of all the text inside the header and footer to white (and given it a `text-shadow`) so it is readable. You should always make sure your text contrasts well with your background, so it is readable.
We've also added a linear gradient to the `<th>` and `<td>` elements inside the header and footer for a nice bit of texture, as well as giving those elements a bright purple border. It is useful to have multiple nested elements available so you can layer styles on top of one another. Yes, we could have put both the background image and the linear gradient on the `<thead>` and `<tfoot>` elements using multiple background images, but we decided to do it separately for the benefit of older browsers that don't support multiple background images or linear gradients.
#### Zebra striping
We wanted to dedicate a separate section to showing you how to implement **zebra stripes** β alternating rows of color that make the different data rows in your table easier to parse and read. Add the following CSS to the bottom of your `style.css` file:
```css
/\* zebra striping \*/
tbody tr:nth-child(odd) {
background-color: #ff33cc;
}
tbody tr:nth-child(even) {
background-color: #e495e4;
}
tbody tr {
background-image: url(noise.png);
}
table {
background-color: #ff33cc;
}
```
* Earlier on you saw the `:nth-child` selector being used to select specific child elements. It can also be given a formula as a parameter, so it will select a sequence of elements. The formula `2n+1` would select all the odd numbered children (1, 3, 5, etc.) and the formula `2n` would select all the even numbered children (2, 4, 6, etc.) We've used the `odd` and `even` keywords in our code, which do exactly the same things as the aforementioned formulae. In this case we are giving the odd and even rows different (lurid) colors.
* We've also added a repeating background tile to all the body rows, which is just a bit of noise (a semi-transparent `.png` with a bit of visual distortion on it) to provide some texture.
* Lastly, we've given the entire table a solid background color so that browsers that don't support the `:nth-child` selector still have a background for their body rows.
This color explosion results in the following look:
![a well styled table with a repeating background in the body rows and the entire table a solid background to make the data showing a summary of Uk's famous punk bands more appealing](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables/table-with-color.png)
Now, this may be a bit over the top and not to your taste, but the point we are trying to make here is that tables don't have to be boring and academic.
### Styling the caption
There is one last thing to do with our table β style the caption. To do this, add the following to the bottom of your `style.css` file:
```css
/\* caption \*/
caption {
font-family: "Rock Salt", cursive;
padding: 20px;
font-style: italic;
caption-side: bottom;
color: #666;
text-align: right;
letter-spacing: 1px;
}
```
There is nothing remarkable here, except for the `caption-side` property, which has been given a value of `bottom`. This causes the caption to be positioned on the bottom of the table, which along with the other declarations gives us this final look (see it live at punk-bands-complete.html):
![a white background below the styled table containing a caption of what the table is about. "a summary of Uk's famous punk bands" in this case](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables/table-with-caption.png)
Table styling quick tips
------------------------
Before moving on, we thought we'd provide you with a quick list of the most useful points illustrated above:
* Make your table markup as simple as possible, and keep things flexible, e.g. by using percentages, so the design is more responsive.
* Use `table-layout``: fixed` to create a more predictable table layout that allows you to easily set column widths by setting `width` on their headings (`<th>`).
* Use `border-collapse``: collapse` to make table elements borders collapse into each other, producing a neater and easier to control look.
* Use `<thead>`, `<tbody>`, and `<tfoot>` to break up your table into logical chunks and provide extra places to apply CSS to, so it is easier to layer styles on top of one another if required.
* Use zebra striping to make alternative rows easier to read.
* Use `text-align` to line up your `<th>` and `<td>` text, to make things neater and easier to follow.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Tables.
Summary
-------
With styling tables now behind us, we need something else to occupy our time. The next article explores debugging CSS β how to solve problems such as layouts not looking like they should, or properties not applying when you think they should. This includes information on using browser DevTools to find solutions to your problems.
* Previous
* Overview: Building blocks
* Next |
Test your skills: Sizing - Learn web development | Test your skills: Sizing
========================
The aim of this skill test is to assess whether you understand the different ways of sizing items in CSS.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, you have two boxes. The first should be sized so that the height will be at least 100 pixels tall, even if there is less content that would cause it to grow to that height. However, the content should not overflow if there is more content than fits in 100 pixels. Test this box by removing the content from the HTML to make sure you still get a 100 pixel tall box even with no content.
The second box should be fixed at 100 pixels tall, so that content will overflow if there is too much.
![Two boxes one with overflowing content](/en-US/docs/Learn/CSS/Building_blocks/Sizing_tasks/mdn-sizing-height-min-height.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, you have a box, which contains another box. Your task is to make the inner box 60% of the width of the outer box. The value of the `box-sizing` property is set to `border-box`, which means that the total width includes any padding and border. You should also give the inner box padding of 10% using the width (or inline size) as the size from which that percentage is calculated.
Your final result should look like the image below:
![A box with another box nested inside](/en-US/docs/Learn/CSS/Building_blocks/Sizing_tasks/mdn-sizing-percentages.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 3
------
In this task, you have two images in boxes. One image is smaller than the box, the other is larger and breaking out of the box. If you imagine that the box is responsive and therefore could grow and shrink, which property would you apply to the image so that the large image shrinks down into the box but the small image does not stretch.
Your final result should look like the images below:
![Two boxes with images in](/en-US/docs/Learn/CSS/Building_blocks/Sizing_tasks/mdn-sizing-max-width.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Handling different text directions - Learn web development | Handling different text directions
==================================
* Previous
* Overview: Building blocks
* Next
Many of the properties and values that we have encountered so far in our CSS learning have been tied to the physical dimensions of our screen. We create borders on the top, right, bottom, and left of a box, for example. These physical dimensions map very neatly to content that is viewed horizontally, and by default the web tends to support left-to-right languages (e.g. English or French) better than right-to-left languages (such as Arabic).
In recent years however, CSS has evolved in order to better support different directionality of content, including right-to-left but also top-to-bottom content (such as Japanese) β these different directionalities are called **writing modes**. As you progress in your study and begin to work with layout, an understanding of writing modes will be very helpful to you, therefore we will introduce them now.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: | To understand the importance of writing modes to modern CSS. |
What are writing modes?
-----------------------
A writing mode in CSS refers to whether the text is running horizontally or vertically. The `writing-mode` property lets us switch from one writing mode to another. You don't need to be working in a language which uses a vertical writing mode to want to do this β you could also change the writing mode of parts of your layout for creative purposes.
In the example below we have a heading displayed using `writing-mode: vertical-rl`. The text now runs vertically. Vertical text is common in graphic design, and can be a way to add a more interesting look and feel to your web design.
The three possible values for the `writing-mode` property are:
* `horizontal-tb`: Top-to-bottom block flow direction. Sentences run horizontally.
* `vertical-rl`: Right-to-left block flow direction. Sentences run vertically.
* `vertical-lr`: Left-to-right block flow direction. Sentences run vertically.
So the `writing-mode` property is in reality setting the direction in which block-level elements are displayed on the page β either from top-to-bottom, right-to-left, or left-to-right. This then dictates the direction text flows in sentences.
Writing modes and block and inline layout
-----------------------------------------
We have already discussed block and inline layout, and the fact that some things display as block elements and others as inline elements. As we have seen described above, block and inline is tied to the writing mode of the document, and not the physical screen. Blocks are only displayed from the top to the bottom of the page if you are using a writing mode that displays text horizontally, such as English.
If we look at an example this will become clearer. In this next example I have two boxes that contain a heading and a paragraph. The first uses `writing-mode: horizontal-tb`, a writing mode that is written horizontally and from the top of the page to the bottom. The second uses `writing-mode: vertical-rl`; this is a writing mode that is written vertically and from right to left.
When we switch the writing mode, we are changing which direction is block and which is inline. In a `horizontal-tb` writing mode the block direction runs from top to bottom; in a `vertical-rl` writing mode the block direction runs right-to-left horizontally. So the **block dimension** is always the direction blocks are displayed on the page in the writing mode in use. The **inline dimension** is always the direction a sentence flows.
This figure shows the two dimensions when in a horizontal writing mode.
![Showing the block and inline axis for a horizontal writing mode.](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions/horizontal-tb.png)
This figure shows the two dimensions in a vertical writing mode.
![Showing the block and inline axis for a vertical writing mode.](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions/vertical.png)
Once you start to look at CSS layout, and in particular the newer layout methods, this idea of block and inline becomes very important. We will revisit it later on.
### Direction
In addition to writing mode we also have text direction. As mentioned above, some languages such as Arabic are written horizontally, but right-to-left. This is not something you are likely to use in a creative sense β if you want to line something up on the right there are other ways to do so β however it is important to understand this as part of the nature of CSS. The web is not just for languages that are displayed left-to-right!
Due to the fact that writing mode and direction of text can change, newer CSS layout methods do not refer to left and right, and top and bottom. Instead they will talk about *start* and *end* along with this idea of inline and block. Don't worry too much about that right now, but keep these ideas in mind as you start to look at layout; you will find it really helpful in your understanding of CSS.
Logical properties and values
-----------------------------
The reason to talk about writing modes and direction at this point in your learning is that we have already looked at a lot of properties that are tied to the physical dimensions of the screen, and these make more sense when in a horizontal writing mode.
Let's take a look at our two boxes again β one with a `horizontal-tb` writing mode and one with `vertical-rl`. I have given both of these boxes a `width`. You can see that when the box is in the vertical writing mode, it still has a width, and this is causing the text to overflow.
What we really want in this scenario is to essentially swap height with width in accordance to the writing mode. When we're in a vertical writing mode we want the box to expand in the block dimension just like it does in the horizontal mode.
To make this easier, CSS has recently developed a set of mapped properties. These essentially replace physical properties β things like `width` and `height` β with **logical**, or **flow relative** versions.
The property mapped to `width` when in a horizontal writing mode is called `inline-size` β it refers to the size in the inline dimension. The property for `height` is named `block-size` and is the size in the block dimension. You can see how this works in the example below where we have replaced `width` with `inline-size`.
### Logical margin, border, and padding properties
In the last two lessons we have learned about the CSS box model, and CSS borders. In the margin, border, and padding properties you will find many instances of physical properties, for example `margin-top`, `padding-left`, and `border-bottom`. In the same way that we have mappings for width and height there are mappings for these properties.
The `margin-top` property is mapped to `margin-block-start` β this will always refer to the margin at the start of the block dimension.
The `padding-left` property maps to `padding-inline-start`, the padding that is applied to the start of the inline direction. This will be where sentences start in that writing mode. The `border-bottom` property maps to `border-block-end`, which is the border at the end of the block dimension.
You can see a comparison between physical and logical properties below.
**If you change the writing mode of the boxes by switching the `writing-mode` property on `.box` to `vertical-rl`, you will see how the physical properties stay tied to their physical direction, whereas the logical properties switch with the writing mode.**
**You can also see that the h2 has a black `border-bottom`. Can you work out how to make that bottom border always go below the text in both writing modes?**
There are a huge number of properties when you consider all of the individual border longhands, and you can see all of the mapped properties on the MDN page for Logical Properties and Values.
### Logical values
We have so far looked at logical property names. There are also some properties that take physical values of `top`, `right`, `bottom`, and `left`. These values also have mappings, to logical values β `block-start`, `inline-end`, `block-end`, and `inline-start`.
For example, you can float an image left to cause text to wrap round the image. You could replace `left` with `inline-start` as shown in the example below.
**Change the writing mode on this example to `vertical-rl` to see what happens to the image. Change `inline-start` to `inline-end` to change the float.**
Here we are also using logical margin values to ensure the margin is in the correct place no matter what the writing mode is.
### Should you use physical or logical properties?
The logical properties and values are newer than their physical equivalents, and therefore have only recently been implemented in browsers. You can check any property page on MDN to see how far back the browser support goes. If you are not using multiple writing modes, then for now you might prefer to use the physical versions. However, ultimately we expect that people will transition to the logical versions for most things, as they make a lot of sense once you also start dealing with layout methods such as flexbox and grid.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Writing modes and logical properties.
Summary
-------
The concepts explained in this lesson are becoming increasingly important in CSS. An understanding of the block and inline direction β and how text flow changes with a change in writing mode β will be very useful going forward. It will help you in understanding CSS even if you never use a writing mode other than a horizontal one.
In the next article, we'll take a good look at overflow in CSS.
* Previous
* Overview: Building blocks
* Next |
Creating fancy letterheaded paper - Learn web development | Creating fancy letterheaded paper
=================================
* Previous
* Overview: Building blocks
* Next
If you want to make the right impression, writing a letter on nice letterheaded paper can be a really good start. In this assessment we'll challenge you to create an online template to achieve such a look.
| | |
| --- | --- |
| Prerequisites: |
Before attempting this assessment you should have already worked through
all the articles in this module.
|
| Objective: |
To test comprehension of CSS box model, and other box-related features
such as implementing backgrounds.
|
Starting point
--------------
To get this assessment started, you should:
* Make local copies of the HTML and CSS β save them as `index.html` and `style.css` in a new directory.
* Save local copies of the top, bottom and logo images in the same directory as your code files.
Alternatively, you could use an online editor such as CodePen, JSFiddle, or Glitch.
You could paste the HTML and fill in the CSS into one of these online editors.
**Note:** If you get stuck, you can reach out to us in one of our communication channels.
Project brief
-------------
You have been given the files needed to create a letterheaded paper template. You just need to put the files together. To get there, you need to:
### The main letter
* Apply the CSS to the HTML.
* Add a background declaration to the letter that:
+ Fixes the top image to the top of the letter
+ Fixes the bottom image to the bottom of the letter
+ Adds a semi-transparent gradient over the top of both of the previous backgrounds that gives the letter a bit of texture. Make it slightly dark right near the top and bottom, but completely transparent for a large part of the center.
* Add another background declaration that just adds the top image to the top of the letter, as a fallback for browsers that don't support the previous declaration.
* Add a white background color to the letter.
* Add a 1mm top and bottom solid border to the letter, in a color that is in keeping with the rest of the color scheme.
### The logo
* To the h1, add the logo as a background image.
* Add a filter to the logo to give it a subtle drop shadow.
* Now comment out the filter and implement the drop shadow in a different (slightly more cross-browser compatible) way, which still follows the shape of the round image.
Hints and tips
--------------
* Remember that you can create a fallback for older browsers by putting the fallback version of a declaration first, followed by the version that works across newer browsers only. Older browsers will apply the first declaration and ignore the second one, whereas newer browsers will apply the first one, then override it with the second one.
* Feel free to create your own graphics for the assessment if you wish.
Example
-------
The following screenshot shows an example of what the finished design could look like:
![Full A4 page composed of at the top left two triangular shapes, first one is green, second one is red, at the top right darker red trapezoid shape. Below the green triangular, a red circle filled with a green star with white text on it: Awesome company. At the bottom left of the page, darker red trapezoid shape, follow by the two triangular shapes: the red one, then the green one. Above the green triangular shape, black text displaying a postal address.](/en-US/docs/Learn/CSS/Building_blocks/Creating_fancy_letterheaded_paper/letterhead.png)
* Previous
* Overview: Building blocks
* Next |
Test your skills: The box model - Learn web development | Test your skills: The box model
===============================
The aim of this skill test is to assess whether you understand the CSS box model.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, there are two boxes below, one is using the standard box model, the other the alternate box model. Change the width of the second box by adding declarations to the `.alternate` class, so that it matches the visual width of the first box.
Your final result should look like the image below:
![Two boxes of the same size](/en-US/docs/Learn/CSS/Building_blocks/Box_Model_Tasks/mdn-box-model1.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, add to the box:
* A 5px, black, dotted border.
* A top margin of 20px.
* A right margin of 1em.
* A bottom margin of 40px.
* A left margin of 2em.
* Padding on all sides of 1em.
Your final result should look like the image below:
![A box with a dotted border](/en-US/docs/Learn/CSS/Building_blocks/Box_Model_Tasks/mdn-box-model2.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 3
------
In this task, the inline element has a margin, padding and border. However, the lines above and below are overlapping it. What can you add to your CSS to cause the size of the margin, padding, and border to be respected by the other lines, while still keeping the element inline?
Your final result should look like the image below:
![An inline box with space between it and the text around it.](/en-US/docs/Learn/CSS/Building_blocks/Box_Model_Tasks/mdn-box-model3.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
The box model - Learn web development | The box model
=============
* Previous
* Overview: Building blocks
* Next
Everything in CSS has a box around it, and understanding these boxes is key to being able to create more complex layouts with CSS, or to align items with other items. In this lesson, we will take a look at the CSS *Box Model*. You'll get an understanding of how it works and the terminology that relates to it.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: |
To learn about the CSS Box Model, what makes up the box model and how to
switch to the alternate model.
|
Block and inline boxes
----------------------
In CSS we have several types of boxes that generally fit into the categories of **block boxes** and **inline boxes**. The type refers to how the box behaves in terms of page flow and in relation to other boxes on the page. Boxes have an **inner display type** and an **outer display type**.
In general, you can set various values for the display type using the `display` property, which can have various values.
Outer display type
------------------
If a box has an outer display type of `block`, then:
* The box will break onto a new line.
* The `width` and `height` properties are respected.
* Padding, margin and border will cause other elements to be pushed away from the box.
* If `width` is not specified, the box will extend in the inline direction to fill the space available in its container. In most cases, the box will become as wide as its container, filling up 100% of the space available.
Some HTML elements, such as `<h1>` and `<p>`, use `block` as their outer display type by default.
If a box has an outer display type of `inline`, then:
* The box will not break onto a new line.
* The `width` and `height` properties will not apply.
* Top and bottom padding, margins, and borders will apply but will not cause other inline boxes to move away from the box.
* Left and right padding, margins, and borders will apply and will cause other inline boxes to move away from the box.
Some HTML elements, such as `<a>`, `<span>`, `<em>` and `<strong>` use `inline` as their outer display type by default.
Inner display type
------------------
Boxes also have an *inner* display type, which dictates how elements inside that box are laid out.
Block and inline layout is the default way things behave on the web. By default and without any other instruction, the elements inside a box are also laid out in **normal flow** and behave as block or inline boxes.
You can change the inner display type for example by setting `display: flex;`. The element will still use the outer display type `block` but this changes the inner display type to `flex`. Any direct children of this box will become flex items and behave according to the Flexbox specification.
When you move on to learn about CSS Layout in more detail, you will encounter `flex`, and various other inner values that your boxes can have, for example `grid`.
**Note:** To read more about the values of display, and how boxes work in block and inline layout, take a look at the MDN guide Block and Inline Layout.
Examples of different display types
-----------------------------------
The example below has three different HTML elements, all of which have an outer display type of `block`.
* A paragraph with a border added in CSS. The browser renders this as a block box. The paragraph starts on a new line and extends the entire available width.
* A list, which is laid out using `display: flex`. This establishes flex layout for the children of the container, which are flex items. The list itself is a block box and β like the paragraph β expands to the full container width and breaks onto a new line.
* A block-level paragraph, inside which are two `<span>` elements. These elements would normally be `inline`, however, one of the elements has a class of "block" which gets set to `display: block`.
In the next example, we can see how `inline` elements behave.
* The `<span>` elements in the first paragraph are inline by default and so do not force line breaks.
* The `<ul>` element that is set to `display: inline-flex` creates an inline box containing some flex items.
* The two paragraphs are both set to `display: inline`. The inline flex container and paragraphs all run together on one line rather than breaking onto new lines (as they would do if they were displaying as block-level elements).
**To toggle between the display modes, you can change `display: inline` to `display: block` or `display: inline-flex` to `display: flex`.**
The key thing to remember for now is: Changing the value of the `display` property can change whether the outer display type of a box is block or inline. This changes the way it displays alongside other elements in the layout.
What is the CSS box model?
--------------------------
The CSS box model as a whole applies to block boxes and defines how the different parts of a box β margin, border, padding, and content β work together to create a box that you can see on a page. Inline boxes use just *some* of the behavior defined in the box model.
To add complexity, there is a standard and an alternate box model. By default, browsers use the standard box model.
### Parts of a box
Making up a block box in CSS we have the:
* **Content box**: The area where your content is displayed; size it using properties like `inline-size` and `block-size` or `width` and `height`.
* **Padding box**: The padding sits around the content as white space; size it using `padding` and related properties.
* **Border box**: The border box wraps the content and any padding; size it using `border` and related properties.
* **Margin box**: The margin is the outermost layer, wrapping the content, padding, and border as whitespace between this box and other elements; size it using `margin` and related properties.
The below diagram shows these layers:
![Diagram of the box model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model/box-model.png)
### The standard CSS box model
In the standard box model, if you set `inline-size` and `block-size` (or `width` and `height`) property values on a box, these values define the `inline-size` and `block-size` (`width` and `height` in horizontal languages) of the *content box*. Any padding and borders are then added to those dimensions to get the total size taken up by the box (see the image below).
If we assume that a box has the following CSS:
```css
.box {
width: 350px;
height: 150px;
margin: 10px;
padding: 25px;
border: 5px solid black;
}
```
The *actual* space taken up by the box will be 410px wide (350 + 25 + 25 + 5 + 5) and 210px high (150 + 25 + 25 + 5 + 5).
![Showing the size of the box when the standard box model is being used.](/en-US/docs/Learn/CSS/Building_blocks/The_box_model/standard-box-model.png)
**Note:** The margin is not counted towards the actual size of the box β sure, it affects the total space that the box will take up on the page, but only the space outside the box. The box's area stops at the border β it does not extend into the margin.
### The alternative CSS box model
In the alternative box model, any width is the width of the visible box on the page. The content area width is that width minus the width for the padding and border (see image below). No need to add up the border and padding to get the real size of the box.
To turn on the alternative model for an element, set `box-sizing: border-box` on it:
```css
.box {
box-sizing: border-box;
}
```
If we assume the box has the same CSS as above:
```css
.box {
width: 350px;
inline-size: 350px;
height: 150px;
block-size: 150px;
margin: 10px;
padding: 25px;
border: 5px solid black;
}
```
Now, the *actual* space taken up by the box will be 350px in the inline direction and 150px in the block direction.
![Showing the size of the box when the alternate box model is being used.](/en-US/docs/Learn/CSS/Building_blocks/The_box_model/alternate-box-model.png)
To use the alternative box model for all of your elements (which is a common choice among developers), set the `box-sizing` property on the `<html>` element and set all other elements to inherit that value:
```css
html {
box-sizing: border-box;
}
\*,
\*::before,
\*::after {
box-sizing: inherit;
}
```
To understand the underlying idea, you can read the CSS Tricks article on box-sizing.
Playing with box models
-----------------------
In the example below, you can see two boxes. Both have a class of `.box`, which gives them the same `width`, `height`, `margin`, `border`, and `padding`. The only difference is that the second box has been set to use the alternative box model.
**Can you change the size of the second box (by adding CSS to the `.alternate` class) to make it match the first box in width and height?**
**Note:** You can find a solution for this task here.
### Use browser DevTools to view the box model
Your browser developer tools can make understanding the box model far easier. If you inspect an element in Firefox's DevTools, you can see the size of the element plus its margin, padding, and border. Inspecting an element in this way is a great way to find out if your box is really the size you think it is!
![Inspecting the box model of an element using Firefox DevTools](/en-US/docs/Learn/CSS/Building_blocks/The_box_model/box-model-devtools.png)
Margins, padding, and borders
-----------------------------
You've already seen the `margin`, `padding`, and `border` properties at work in the example above. The properties used in that example are **shorthands** and allow us to set all four sides of the box at once. These shorthands also have equivalent longhand properties, which allow control over the different sides of the box individually.
Let's explore these properties in more detail.
### Margin
The margin is an invisible space around your box. It pushes other elements away from the box. Margins can have positive or negative values. Setting a negative margin on one side of your box can cause it to overlap other things on the page. Whether you are using the standard or alternative box model, the margin is always added after the size of the visible box has been calculated.
We can control all margins of an element at once using the `margin` property, or each side individually using the equivalent longhand properties:
* `margin-top`
* `margin-right`
* `margin-bottom`
* `margin-left`
**In the example below, try changing the margin values to see how the box is pushed around due to the margin creating or removing space (if it is a negative margin) between this element and the containing element.**
#### Margin collapsing
Depending on whether two elements whose margins touch have positive or negative margins, the results will be different:
* Two positive margins will combine to become one margin. Its size will be equal to the largest individual margin.
* Two negative margins will collapse and the smallest (furthest from zero) value will be used.
* If one margin is negative, its value will be *subtracted* from the total.
In the example below, we have two paragraphs. The top paragraph has a `margin-bottom` of 50 pixels, the other has a `margin-top` of 30 pixels. The margins have collapsed together so the actual margin between the boxes is 50 pixels and not the total of the two margins.
**You can test this by setting the `margin-top` of paragraph two to 0. The visible margin between the two paragraphs will not change β it retains the 50 pixels set in the `margin-bottom` of paragraph one. If you set it to -10px, you'll see that the overall margin becomes 40px β it subtracts from the 50px.**
A number of rules dictate when margins do and do not collapse. For further information see the detailed page on mastering margin collapsing. The main thing to remember is that margin collapsing is a thing that happens if you are creating space with margins and don't get the space you expect.
### Borders
The border is drawn between the margin and the padding of a box. If you are using the standard box model, the size of the border is added to the `width` and `height` of the content box. If you are using the alternative box model, then the bigger the border is, the smaller the content box is, as the border takes up some of that available `width` and `height` of the element box.
For styling borders, there are a large number of properties β there are four borders, and each border has a style, width, and color that we might want to manipulate.
You can set the width, style, or color of all four borders at once using the `border` property.
To set the properties of each side individually, use:
* `border-top`
* `border-right`
* `border-bottom`
* `border-left`
To set the width, style, or color of all sides, use:
* `border-width`
* `border-style`
* `border-color`
To set the width, style, or color of a single side, use one of the more granular longhand properties:
* `border-top-width`
* `border-top-style`
* `border-top-color`
* `border-right-width`
* `border-right-style`
* `border-right-color`
* `border-bottom-width`
* `border-bottom-style`
* `border-bottom-color`
* `border-left-width`
* `border-left-style`
* `border-left-color`
In the example below, we have used various shorthands and longhands to create borders. Play around with the different properties to check that you understand how they work. The MDN pages for the border properties give you information about the different available border styles.
### Padding
The padding sits between the border and the content area and is used to push the content away from the border. Unlike margins, you cannot have a negative padding. Any background applied to your element will display behind the padding.
The `padding` property controls the padding on all sides of an element. To control each side individually, use these longhand properties:
* `padding-top`
* `padding-right`
* `padding-bottom`
* `padding-left`
In the example below, you can change the values for padding on the class `.box` to see that this changes where the text begins in relation to the box. You can also change the padding on the class `.container` to create space between the container and the box. You can change the padding on any element to create space between its border and whatever is inside the element.
The box model and inline boxes
------------------------------
All of the above fully applies to block boxes. Some of the properties can apply to inline boxes too, such as those created by a `<span>` element.
In the example below, we have a `<span>` inside a paragraph. We have applied a `width`, `height`, `margin`, `border`, and `padding` to it. You can see that the width and height are ignored. The top and bottom margin, padding, and border are respected but don't change the relationship of other content to our inline box. The padding and border overlap other words in the paragraph. The left and right padding, margins, and borders move other content away from the box.
Using display: inline-block
---------------------------
`display: inline-block` is a special value of `display`, which provides a middle ground between `inline` and `block`. Use it if you do not want an item to break onto a new line, but do want it to respect `width` and `height` and avoid the overlapping seen above.
An element with `display: inline-block` does a subset of the block things we already know about:
* The `width` and `height` properties are respected.
* `padding`, `margin`, and `border` will cause other elements to be pushed away from the box.
It does not, however, break onto a new line, and will only become larger than its content if you explicitly add `width` and `height` properties.
**In this next example, we have added `display: inline-block` to our `<span>` element. Try changing this to `display: block` or removing the line completely to see the difference in display models.**
Where this can be useful is when you want to give a link a larger hit area by adding `padding`. `<a>` is an inline element like `<span>`; you can use `display: inline-block` to allow padding to be set on it, making it easier for a user to click the link.
You see this fairly frequently in navigation bars. The navigation below is displayed in a row using flexbox and we have added padding to the `<a>` element as we want to be able to change the `background-color` when the `<a>` is hovered. The padding appears to overlap the border on the `<ul>` element. This is because the `<a>` is an inline element.
**Add `display: inline-block` to the rule with the `.links-list a` selector, and you will see how it fixes this issue by causing the padding to be respected by other elements.**
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: The box model.
Summary
-------
That's most of what you need to understand about the box model. You may want to return to this lesson in the future if you ever find yourself confused about how big boxes are in your layout.
In the next article, we'll take a look at how backgrounds and borders can be used to make your plain boxes look more interesting.
* Previous
* Overview: Building blocks
* Next |
Test your skills: Overflow - Learn web development | Test your skills: Overflow
==========================
The aim of this skill test is to assess whether you understand overflow in CSS and how to manage it.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, the content is overflowing the box because it has a fixed height. Keep the height but cause the box to have scrollbars only if there is enough text to cause an overflow. Test by removing some of the text from the HTML, that if there is only a small amount of text that does not overflow, no scrollbar appears.
![A small box with a border and a vertical scrollbar.](/en-US/docs/Learn/CSS/Building_blocks/Overflow_Tasks/mdn-overflow1.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, there is an image in the box that is bigger than the dimensions of the box so that it overflows visibly. Change it so that any image outside of the box is hidden.
Your final result should look like the image below:
![A box with an image which fills the box but does not spill out the edges.](/en-US/docs/Learn/CSS/Building_blocks/Overflow_Tasks/mdn-overflow2.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Fundamental CSS comprehension - Learn web development | Fundamental CSS comprehension
=============================
* Previous
* Overview: Building blocks
* Next
You've covered a lot in this module, so it must feel good to have reached the end! The final step before you move on is to attempt the assessment for the module β this involves a number of related exercises that must be completed in order to create the final design β a business card/gamer card/social media profile.
| | |
| --- | --- |
| Prerequisites: |
Before attempting this assessment you should have already worked through
all the articles in this module.
|
| Objective: | To test comprehension of fundamental CSS theory, syntax and mechanics. |
Starting point
--------------
To get this assessment started, you should:
* Go and grab the HTML file for the exercise, and the associated image file, and save them in a new directory on your local computer. If you want to use your own image file and fill your own name in, you are welcome to β just make sure the image is square.
* Grab the CSS resources text file β this contains a set of raw selectors and rulesets that you'll need to study and combine to answer part of this assessment.
Alternatively, you could use an online editor such as CodePen, JSFiddle, or Glitch.
You could paste the HTML and fill in the CSS into one of these online editors, and use this URL to point the `<img>` element to the image file.
**Note:** If you get stuck, you can reach out to us in one of our communication channels.
Project brief
-------------
You have been provided with some raw HTML and an image, and need to write the necessary CSS to style this into a nifty little online business card, which can perhaps double as a gamer card or social media profile. The following sections describe what you need to do.
Basic setup:
* First of all, create a new file in the same directory as your HTML and image files. Call it something really imaginative like `style.css`.
* Link your CSS to your HTML file via a `<link>` element.
* The first two rulesets in the CSS resource file are yours, for FREE! After you've finished rejoicing at your good fortune, copy and paste them into the top of your new CSS file. Use them as a test to make sure your CSS is properly applied to your HTML.
* Above the two rules, add a CSS comment with some text inside it to indicate that this is a set of general styles for the overall page. "General page styles" would do. Also add three more comments at the bottom of the CSS file to indicate styles specific to the setup of the card container, styles specific to the header and footer, and styles specific to the main business card contents. From now on, subsequent styles added to the stylesheet should be organized in an appropriate place.
Taking care of the selectors and rulesets provided in the CSS resource file:
* Next up, we'd like you to look at the four selectors, and calculate the specificity for each one. Write these down somewhere where they can be found later on, such as in a comment at the top of your CSS.
* Now it's time to put the right selector on the right rule set! You've got four pairs of selector and ruleset to match in your CSS resources. Do this now, and add them to your CSS file. You need to:
+ Give the main card container a fixed width/height, solid background color, border, and border-radius (rounded corners!), amongst other things.
+ Give the header a background gradient that goes from darker to lighter, plus rounded corners that fit in with the rounded corners set on the main card container.
+ Give the footer a background gradient that goes from lighter to darker, plus rounded corners that fit in with the rounded corners set on the main card container.
+ Float the image to the right so that it sticks to the right-hand side of the main business card contents, and give it a max-height of 100% (a clever trick that ensures that it will grow/shrink to stay the same height as its parent container, regardless of what height it becomes.)
* Beware! There are two errors in the provided rulesets. Using any technique that you know, track these down and fix them before moving on.
New rulesets you need to write:
* Write a ruleset that targets both the card header, and card footer, giving them both a computed total height of 50px (including a content height of 30px and padding of 10px on all sides.) But express it in `em`s.
* The default margin applied to the `<h2>` and `<p>` elements by the browser will interfere with our design, so write a rule that targets all these elements and sets their margin to 0.
* To stop the image from spilling out of the main business card content (the `<article>` element), we need to give it a specific height. Set the `<article>`'s height to 120px, but expressed in `em`s. Also give it a background color of semi-transparent black, resulting in a slightly darker shade that lets the background red color shine through a bit too.
* Write a ruleset that gives the `<h2>` an effective font size of 20px (but expressed in `em`s) and an appropriate line height to place it in the center of the header's content box. Recall from earlier that the content box height should be 30px β this gives you all the numbers you need to calculate the line height.
* Write a ruleset that gives the `<p>` inside the footer an effective font size of 15px (but expressed in `em`s) and an appropriate line height to place it in the center of the footer's content box. Recall from earlier that the content box height should be 30px β this gives you all the numbers you need to calculate the line height.
* As a last little touch, give the paragraph inside the `<article>` an appropriate padding value so that its left edge lines up with the `<h2>` and footer paragraph, and set its color to be fairly light so it is easy to read.
**Note:** Bear in mind that the second ruleset sets `font-size: 10px;` on the `<html>` element β this means that for any descendants of `<html>`, an em will be equal to 10px rather than 16px as it is by default. (This is of course, provided the descendants in question don't have any ancestors sitting in between them and `<html>` in the hierarchy that have a different `font-size` set on them. This could affect the values you need, although in this simple example this is not an issue.)
Other things to think about:
* You'll get bonus marks if you write your CSS for maximum readability, with a separate declaration on each line.
* You should include `.card` at the start of the selector chain in all your rules, so that these rules wouldn't interfere with the styling of any other elements if the business card were to be put on a page with a load of other content.
Hints and tips
--------------
* You don't need to edit the HTML in any way, except to apply the CSS to your HTML.
* When trying to work out the `em` value you need to represent a certain pixel length, think about what base font size the root (`<html>`) element has, and what it needs to be multiplied by to get the desired value. That'll give you your em value, at least in a simple case like this.
Example
-------
The following screenshot shows an example of what the finished design should look like:
![A view of the finished business card, show a reader header and footer, and a darker center panel containing the main details and image.](/en-US/docs/Learn/CSS/Building_blocks/Fundamental_CSS_comprehension/business-card.png)
* Previous
* Overview: Building blocks
* Next |
Organizing your CSS - Learn web development | Organizing your CSS
===================
* Previous
* Overview: Building blocks
* Next
As you start to work on larger stylesheets and big projects you will discover that maintaining a huge CSS file can be challenging. In this article we will take a brief look at some best practices for writing your CSS to make it easily maintainable, and some of the solutions you will find in use by others to help improve maintainability.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: |
To learn some tips and best practices for organizing stylesheets, and
find out about some of the naming conventions and tools in common usage
to help with CSS organization and team working.
|
Tips to keep your CSS tidy
--------------------------
Here are some general suggestions for ways to keep your stylesheets organized and tidy.
### Does your project have a coding style guide?
If you are working with a team on an existing project, the first thing to check is whether the project has an existing style guide for CSS. The team style guide should always win over your own personal preferences. There often isn't a right or wrong way to do things, but consistency is important.
For example, have a look at the CSS guidelines for MDN code examples.
### Keep it consistent
If you get to set the rules for the project or are working alone, then the most important thing to do is to keep things consistent. Consistency can be applied in all sorts of ways, such as using the same naming conventions for classes, choosing one method of describing color, or maintaining consistent formatting. (For example, will you use tabs or spaces to indent your code? If spaces, how many spaces?)
Having a set of rules you always follow reduces the amount of mental overhead needed when writing CSS, as some of the decisions are already made.
### Formatting readable CSS
There are a couple of ways you will see CSS formatted. Some developers put all of the rules onto a single line, like so:
```css
.box {background-color: #567895; }
h2 {background-color: black; color: white; }
```
Other developers prefer to break everything onto a new line:
```css
.box {
background-color: #567895;
}
h2 {
background-color: black;
color: white;
}
```
CSS doesn't mind which one you use. We personally find it is more readable to have each property and value pair on a new line.
### Comment your CSS
Adding comments to your CSS will help any future developer work with your CSS file, but will also help you when you come back to the project after a break.
```css
/\* This is a CSS comment
It can be broken onto multiple lines. \*/
```
A good tip is to add a block of comments between logical sections in your stylesheet too, to help locate different sections quickly when scanning it, or even to give you something to search for to jump right into that part of the CSS. If you use a string that won't appear in the code, you can jump from section to section by searching for it β below we have used `||`.
```css
/\* || General styles \*/
/\* β¦ \*/
/\* || Typography \*/
/\* β¦ \*/
/\* || Header and Main Navigation \*/
/\* β¦ \*/
```
You don't need to comment every single thing in your CSS, as much of it will be self-explanatory. What you should comment are the things where you made a particular decision for a reason.
You may have used a CSS property in a specific way to get around older browser incompatibilities, for example:
```css
.box {
background-color: red; /\* fallback for older browsers that don't support gradients \*/
background-image: linear-gradient(to right, #ff0000, #aa0000);
}
```
Perhaps you followed a tutorial to achieve something, and the CSS isn't very self-explanatory or recognizable. In that case, you could add the URL of the tutorial to the comments. You will thank yourself when you come back to this project in a year or so and can vaguely remember that there was a great tutorial about that thing, but can't recall where it's from.
### Create logical sections in your stylesheet
It is a good idea to have all of the common styling first in the stylesheet. This means all of the styles which will generally apply unless you do something special with that element. You will typically have rules set up for:
* `body`
* `p`
* `h1`, `h2`, `h3`, `h4`, `h5`
* `ul` and `ol`
* The `table` properties
* Links
In this section of the stylesheet we are providing default styling for the type on the site, setting up a default style for data tables and lists and so on.
```css
/\* || GENERAL STYLES \*/
body {
/\* β¦ \*/
}
h1,
h2,
h3,
h4 {
/\* β¦ \*/
}
ul {
/\* β¦ \*/
}
blockquote {
/\* β¦ \*/
}
```
After this section, we could define a few utility classes, for example, a class that removes the default list style for lists we're going to display as flex items or in some other way. If you have a few styling choices you know you will want to apply to lots of different elements, they can be put in this section.
```css
/\* || UTILITIES \*/
.nobullets {
list-style: none;
margin: 0;
padding: 0;
}
/\* β¦ \*/
```
Then we can add everything that is used sitewide. That might be things like the basic page layout, the header, navigation styling, and so on.
```css
/\* || SITEWIDE \*/
.main-nav {
/\* β¦ \*/
}
.logo {
/\* β¦ \*/
}
```
Finally, we will include CSS for specific things, broken down by the context, page, or even component in which they are used.
```css
/\* || STORE PAGES \*/
.product-listing {
/\* β¦ \*/
}
.product-box {
/\* β¦ \*/
}
```
By ordering things in this way, we at least have an idea in which part of the stylesheet we will be looking for something that we want to change.
### Avoid overly-specific selectors
If you create very specific selectors, you will often find that you need to duplicate chunks of your CSS to apply the same rules to another element. For example, you might have something like the below selector, which applies the rule to a `<p>` with a class of `box` inside an `<article>` with a class of `main`.
```css
article.main p.box {
border: 1px solid #ccc;
}
```
If you then wanted to apply the same rules to something outside of `main`, or to something other than a `<p>`, you would have to add another selector to these rules or create a whole new ruleset. Instead, you could use the selector `.box` to apply your rule to any element that has the class `box`:
```css
.box {
border: 1px solid #ccc;
}
```
There will be times when making something more specific makes sense; however, this will generally be an exception rather than usual practice.
### Break large stylesheets into multiple smaller ones
In cases where you have very different styles for distinct parts of the site, you might want to have one stylesheet that includes all the global rules, as well as some smaller stylesheets that include the specific rules needed for those sections. You can link to multiple stylesheets from one page, and the normal rules of the cascade apply, with rules in stylesheets linked later coming after rules in stylesheets linked earlier.
For example, we might have an online store as part of the site, with a lot of CSS used only for styling the product listings and forms needed for the store. It would make sense to have those things in a different stylesheet, only linked to on store pages.
This can make it easier to keep your CSS organized, and also means that if multiple people are working on the CSS, you will have fewer situations where two people need to work on the same stylesheet at once, leading to conflicts in source control.
Other tools that can help
-------------------------
CSS itself doesn't have much in the way of in-built organization; therefore, the level of consistency in your CSS will largely depend on you. The web community has developed various tools and approaches that can help you to manage larger CSS projects. Since you are likely to come across these aids when working with other people, and since they are often of help generally, we've included a short guide to some of them.
### CSS methodologies
Instead of needing to come up with your own rules for writing CSS, you may benefit from adopting one of the approaches already designed by the community and tested across many projects. These methodologies are essentially CSS coding guides that take a very structured approach to writing and organizing CSS. Typically they tend to render CSS more verbosely than you might have if you wrote and optimized every selector to a custom set of rules for that project.
However, you do gain a lot of structure by adopting one. Since many of these systems are widely used, other developers are more likely to understand the approach you are using and be able to write their own CSS in the same way, rather than having to work out your own personal methodology from scratch.
#### OOCSS
Most of the approaches you will encounter owe something to the concept of Object Oriented CSS (OOCSS), an approach made popular by the work of Nicole Sullivan. The basic idea of OOCSS is to separate your CSS into reusable objects, which can be used anywhere you need on your site. The standard example of OOCSS is the pattern described as The Media Object. This is a pattern with a fixed size image, video or other element on one side, and flexible content on the other. It's a pattern we see all over websites for comments, listings, and so on.
If you are not taking an OOCSS approach you might create a custom CSS for the different places this pattern is used, for example, by creating two classes, one called `comment` with a bunch of rules for the component parts, and another called `list-item` with almost the same rules as the `comment` class except for some tiny differences. The differences between these two components are the list-item has a bottom border, and images in comments have a border whereas list-item images do not.
```css
.comment {
display: grid;
grid-template-columns: 1fr 3fr;
}
.comment img {
border: 1px solid grey;
}
.comment .content {
font-size: 0.8rem;
}
.list-item {
display: grid;
grid-template-columns: 1fr 3fr;
border-bottom: 1px solid grey;
}
.list-item .content {
font-size: 0.8rem;
}
```
In OOCSS, you would create one pattern called `media` that would have all of the common CSS for both patterns β a base class for things that are generally the shape of the media object. Then we'd add an additional class to deal with those tiny differences, thus extending that styling in specific ways.
```css
.media {
display: grid;
grid-template-columns: 1fr 3fr;
}
.media .content {
font-size: 0.8rem;
}
.comment img {
border: 1px solid grey;
}
.list-item {
border-bottom: 1px solid grey;
}
```
In your HTML, the comment would need both the `media` and `comment` classes applied:
```html
<div class="media comment">
<img src="" alt="" />
<div class="content"></div>
</div>
```
The list-item would have `media` and `list-item` applied:
```html
<ul>
<li class="media list-item">
<img src="" alt="" />
<div class="content"></div>
</li>
</ul>
```
The work that Nicole Sullivan did in describing this approach and promoting it means that even people who are not strictly following an OOCSS approach today will generally be reusing CSS in this way β it has entered our understanding as a good way to approach things in general.
#### BEM
BEM stands for Block Element Modifier. In BEM a block is a stand-alone entity such as a button, menu, or logo. An element is something like a list item or a title that is tied to the block it is in. A modifier is a flag on a block or element that changes the styling or behavior. You will be able to recognize code that uses BEM due to the extensive use of dashes and underscores in the CSS classes. For example, look at the classes applied to this HTML from the page about BEM Naming conventions:
```html
<form class="form form--theme-xmas form--simple">
<label class="label form\_\_label" for="inputId"></label>
<input class="form\_\_input" type="text" id="inputId" />
<input
class="form\_\_submit form\_\_submit--disabled"
type="submit"
value="Submit" />
</form>
```
The additional classes are similar to those used in the OOCSS example; however, they use the strict naming conventions of BEM.
BEM is widely used in larger web projects and many people write their CSS in this way. It is likely that you will come across examples, even in tutorials, that use BEM syntax, without mentioning why the CSS is structured in such a way.
Read more about this system BEM 101 on CSS Tricks.
#### Other common systems
There are a large number of these systems in use. Other popular approaches include Scalable and Modular Architecture for CSS (SMACSS), created by Jonathan Snook, ITCSS from Harry Roberts, and Atomic CSS (ACSS), originally created by Yahoo!. If you come across a project that uses one of these approaches, then the advantage is that you will be able to search and find many articles and guides to help you understand how to code in the same style.
The disadvantage of using such a system is that they can seem overly complex, especially for smaller projects.
### Build systems for CSS
Another way to organize CSS is to take advantage of some of the tooling that is available for front-end developers, which allows you to take a slightly more programmatic approach to writing CSS. There are a number of tools, which we refer to as *pre-processors* and *post-processors*. A pre-processor runs over your raw files and turns them into a stylesheet, whereas a post-processor takes your finished stylesheet and does something to it β perhaps to optimize it in order that it will load faster.
Using any of these tools will require that your development environment be able to run the scripts that do the pre- and post-processing. Many code editors can do this for you, or you can install command line tools to help.
The most popular pre-processor is Sass. This is not a Sass tutorial, so I will briefly explain a couple of the things that Sass can do, which are really helpful in terms of organization even if you don't use any of the other Sass features. If you want to learn a lot more about Sass, start with the Sass basics article, then move on to their other documentation.
#### Defining variables
CSS now has native custom properties, making this feature increasingly less important. However, one of the reasons you might use Sass is to be able to define all of the colors and fonts used in a project as settings, then to use that variable around the project. This means that if you realize you have used the wrong shade of blue, you only need change it in one place.
If we created a variable called `$base-color`, as in the first line below, we could then use it through the stylesheet anywhere that required that color.
```scss
$base-color: #c6538c;
.alert {
border: 1px solid $base-color;
}
```
Once compiled to CSS, you would end up with the following CSS in the final stylesheet.
```css
.alert {
border: 1px solid #c6538c;
}
```
#### Compiling component stylesheets
I mentioned above that one way to organize CSS is to break down stylesheets into smaller stylesheets. When using Sass you can take this to another level and have lots of very small stylesheets β even going as far as having a separate stylesheet for each component. By using the included functionality in Sass (partials), these can all be compiled together into one or a small number of stylesheets to actually link into your website.
So, for example, with partials, you could have several style files inside a directory, say `foundation/_code.scss`, `foundation/_lists.scss`, `foundation/_footer.scss`, `foundation/_links.scss`, etc. You could then use the Sass `@use` rule to load them into other stylesheets:
```scss
// foundation/\_index.scss
@use "code";
@use "lists";
@use "footer";
@use "links";
```
If the partials are all loaded into an index file, as implied above, you can then load that entire directory into another stylesheet in one go:
```scss
// style.scss
@use "foundation";
```
**Note:** A simple way to try out Sass is to use CodePen β you can enable Sass for your CSS in the Settings for a Pen, and CodePen will then run the Sass parser for you in order that you can see the resulting webpage with regular CSS applied. Sometimes you will find that CSS tutorials have used Sass rather than plain CSS in their CodePen demos, so it is handy to know a little bit about it.
#### Post-processing for optimization
If you are concerned about adding size to your stylesheets, for example, by adding a lot of additional comments and whitespace, then a post-processing step could be to optimize the CSS by stripping out anything unnecessary in the production version. An example of a post-processor solution for doing this would be cssnano.
Summary
-------
This is the final part of our building blocks module, and as you can see there are many ways in which your exploration of CSS can continue from this point β but now you can go on to testing yourself with our assessments: the first one is linked below.
To learn more about layout in CSS, see the CSS Layout module.
You should also now have the skills to explore the rest of the MDN CSS material. You can look up properties and values, explore our CSS Cookbook for patterns to use, or continue reading in some of the specific guides, such as our Guide to CSS Grid Layout.
* Previous
* Overview: Building blocks
* Next |
Test your skills: Values and units - Learn web development | Test your skills: Values and units
==================================
The aim of this skill test is to assess whether you understand different types of values and units used in CSS properties.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, the first list item has been given a background color using a hex color code. Your task is to complete the CSS using the same color in different formats, plus a final list item where you should make the background semi-opaque.
* The second list item should use RGB color.
* The third should use HSL color.
* The fourth should use RGB color but with the alpha channel set to `0.6`.
You can find conversions for the hex color at this link. You need to figure out how to use the values in CSS. Your final result should look like the image below:
![Four list items. The first three with the same background color and the last with a lighter background.](/en-US/docs/Learn/CSS/Building_blocks/Values_tasks/mdn-value-color.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, we want you to set the size of various items of text, as described below:
* The `<h1>` element should be 50 pixels.
* The `<h2>` element should be 2em.
* All `<p>` elements should be 16 pixels.
* A `<p>` element that is directly after an `<h1>` should be 120%.
Your final result should look like the image below:
![Some text at varying sizes.](/en-US/docs/Learn/CSS/Building_blocks/Values_tasks/mdn-value-length.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 3
------
In this task, we want you to move the background image so that it is centered horizontally and is 20% from the top of the box.
Your final result should look like the image below:
![A stat centered horizontally in a box and a short distance from the top of the box.](/en-US/docs/Learn/CSS/Building_blocks/Values_tasks/mdn-value-position.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Test your skills: Tables - Learn web development | Test your skills: Tables
========================
The aim of this skill test is to assess whether you understand how to style HTML tables in CSS.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task
----
In the lesson on styling tables we styled up a table in a rather garish manner. In this task, we are going to style the same table, but using some good practices for table design as outlined in the external article Web Typography: designing tables to be read not looked at.
Our finished table will look like the image below. There are a number of ways that you can achieve this, but we suggest you follow similar patterns as used in the tutorial to do the following things:
* Add padding of `0.3em` to the table headings and data and align them at the top of their cells.
* Align headings and data for columns containing numbers right.
* Align headings and data for columns containing text left.
* Add a 1px top and bottom solid border with the hex color `#999`, plus a 1px solid border of the same color above the footer.
* Remove the default spacing between the table elements borders to get the expected result.
* Stripe every odd row of the main table with the hex color `#eee`.
![A table with striped rows.](/en-US/docs/Learn/CSS/Building_blocks/Tables_tasks/mdn-table-bands.png)
Try updating the live code below to recreate the finished example:
Additional question:
* What can you do to make the table layout behave a bit more predictably? Think of how table columns are sized by default and how we can change this behavior to size the columns according to the width of their headings.
Download the starting point for this task to work in your own editor or in an online editor. |
CSS values and units - Learn web development | CSS values and units
====================
* Previous
* Overview: Building blocks
* Next
CSS rules contain declarations, which in turn are composed of properties and values.
Each property used in CSS has a **value type** that describes what kind of values it is allowed to have.
In this lesson, we will take a look at some of the most frequently used value types, what they are, and how they work.
**Note:** Each CSS property page has a syntax section that lists the value types you can use with that property.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps).
|
| Objective: |
To learn about the different types of values and units used in CSS
properties.
|
What is a CSS value?
--------------------
In CSS specifications and on the property pages here on MDN you will be able to spot value types as they will be surrounded by angle brackets, such as `<color>` or `<length>`. When you see the value type `<color>` as valid for a particular property, that means you can use any valid color as a value for that property, as listed on the `<color>` reference page.
**Note:** You'll see CSS value types referred to as *data types*. The terms are basically interchangeable β when you see something in CSS referred to as a data type, it is really just a fancy way of saying value type. The term *value* refers to any particular expression supported by a value type that you choose to use.
**Note:** CSS value types tend to be enclosed in angle brackets (`<`, `>`) to differentiate them from CSS properties.
For example there is a `color` property and a `<color>` data type.
This is not to be confused with HTML elements, as they also use angle brackets, but this is something to keep in mind that the context should make clear.
In the following example, we have set the color of our heading using a keyword, and the background using the `rgb()` function:
```css
h1 {
color: black;
background-color: rgb(197 93 161);
}
```
A value type in CSS is a way to define a collection of allowable values. This means that if you see `<color>` as valid you don't need to wonder which of the different types of color value can be used β keywords, hex values, `rgb()` functions, etc. You can use *any* available `<color>` values, assuming they are supported by your browser. The page on MDN for each value will give you information about browser support. For example, if you look at the page for `<color>` you will see that the browser compatibility section lists different types of color values and support for them.
Let's have a look at some of the types of values and units you may frequently encounter, with examples so that you can try out different possible values.
Numbers, lengths, and percentages
---------------------------------
There are various numeric value types that you might find yourself using in CSS. The following are all classed as numeric:
| Data type | Description |
| --- | --- |
| `<integer>` |
An `<integer>` is a whole number such as
`1024` or `-55`.
|
| `<number>` |
A `<number>` represents a decimal number β it may or may
not have a decimal point with a fractional component. For
example, `0.255`, `128`, or `-1.2`.
|
| `<dimension>` |
A `<dimension>` is a `<number>` with a
unit attached to it. For example, `45deg`, `5s`,
or `10px`. `<dimension>` is an umbrella
category that includes the `<length>`, `<angle>`, `<time>`, and
`<resolution>`
types.
|
| `<percentage>` |
A `<percentage>` represents a fraction of some other
value. For example, `50%`. Percentage values are always
relative to another quantity. For example, an element's length is
relative to its parent element's length.
|
### Lengths
The numeric type you will come across most frequently is `<length>`. For example, `10px` (pixels) or `30em`. There are two types of lengths used in CSS β relative and absolute. It's important to know the difference in order to understand how big things will become.
#### Absolute length units
The following are all **absolute** length units β they are not relative to anything else, and are generally considered to always be the same size.
| Unit | Name | Equivalent to |
| --- | --- | --- |
| `cm` | Centimeters | 1cm = 37.8px = 25.2/64in |
| `mm` | Millimeters | 1mm = 1/10th of 1cm |
| `Q` | Quarter-millimeters | 1Q = 1/40th of 1cm |
| `in` | Inches | 1in = 2.54cm = 96px |
| `pc` | Picas | 1pc = 1/6th of 1in |
| `pt` | Points | 1pt = 1/72nd of 1in |
| `px` | Pixels | 1px = 1/96th of 1in |
Most of these units are more useful when used for print, rather than screen output. For example, we don't typically use `cm` (centimeters) on screen. The only value that you will commonly use is `px` (pixels).
#### Relative length units
Relative length units are relative to something else, perhaps the size of the parent element's font, or the size of the viewport. The benefit of using relative units is that with some careful planning you can make it so the size of text or other elements scales relative to everything else on the page. Some of the most useful units for web development are listed in the table below.
| Unit | Relative to |
| --- | --- |
| `em` |
Font size of the parent, in the case of typographical properties like
`font-size`, and font size of the element itself, in the case of other properties
like `width`.
|
| `ex` | x-height of the element's font. |
| `ch` | The advance measure (width) of the glyph "0" of the element's font. |
| `rem` | Font size of the root element. |
| `lh` | Line height of the element. |
| `rlh` | Line height of the root element. When used on the `font-size` or `line-height` properties of the root element, it refers to the properties' initial value. |
| `vw` | 1% of the viewport's width. |
| `vh` | 1% of the viewport's height. |
| `vmin` | 1% of the viewport's smaller dimension. |
| `vmax` | 1% of the viewport's larger dimension. |
| `vb` | 1% of the size of the initial containing block in the direction of the root element's block axis. |
| `vi` | 1% of the size of the initial containing block in the direction of the root element's inline axis. |
| `svw, svh` | 1% of the small viewport's width and height, respectively. |
| `lvw, lvh` | 1% of the large viewport's width and height, respectively. |
| `dvw, dvh` | 1% of the dynamic viewport's width and height, respectively. |
#### Exploring an example
In the example below, you can see how some relative and absolute length units behave. The first box has a `width` set in pixels. As an absolute unit, this width will remain the same no matter what else changes.
The second box has a width set in `vw` (viewport width) units. This value is relative to the viewport width, and so 10vw is 10 percent of the width of the viewport. If you change the width of your browser window, the size of the box should change. However this example is embedded into the page using an `<iframe>`, so this won't work. To see this in action you'll have to try the example after opening it in its own browser tab.
The third box uses `em` units. These are relative to the font size. I've set a font size of `1em` on the containing `<div>`, which has a class of `.wrapper`. Change this value to `1.5em` and you will see that the font size of all the elements increases, but only the last item will get wider, as its width is relative to that font size.
After following the instructions above, try playing with the values in other ways, to see what you get.
#### ems and rems
`em` and `rem` are the two relative lengths you are likely to encounter most frequently when sizing anything from boxes to text. It's worth understanding how these work, and the differences between them, especially when you start getting on to more complex subjects like styling text or CSS layout. The below example provides a demonstration.
The HTML illustrated below is a set of nested lists β we have two lists in total and both examples have the same HTML. The only difference is that the first has a class of *ems* and the second a class of *rems*.
To start with, we set 16px as the font size on the `<html>` element.
**To recap, the em unit means "my parent element's font-size"** in the case of typography. The `<li>` elements inside the `<ul>` with a `class` of `ems` take their sizing from their parent. So each successive level of nesting gets progressively larger, as each has its font size set to `1.3em` β 1.3 times its parent's font size.
**To recap, the rem unit means "The root element's font-size"** (rem stands for "root em"). The `<li>` elements inside the `<ul>` with a `class` of `rems` take their sizing from the root element (`<html>`). This means that each successive level of nesting does not keep getting larger.
However, if you change the `<html>` element's `font-size` in the CSS you will see that everything else changes relative to it β both `rem`- and `em`-sized text.
#### Line height units
`lh` and `rlh` are relative lengths units similar to `em` and `rem`. The difference between `lh` and `rlh` is that the first one is relative to the line height of the element itself, while the second one is relative to the line height of the root element, usually `<html>`.
Using these units, we can precisely align box decoration to the text. In this example, we use `lh` unit to create notepad-like lines using `repeating-linear-gradient()`. It doesn't matter what's the line height of the text, the lines will always start in the right place.
```
body {
margin: 0;
display: grid;
grid-template-columns: 1fr 1fr;
padding: 24px;
gap: 24px;
background-color: floralwhite;
font-family: sans-serif;
}
@supports not (height: 1lh) {
body::before {
grid-column: 1 / -1;
padding: 8px;
border-radius: 4px;
background-color: tomato;
color: white;
content: "You browser doesnβt support lh unit just yet";
}
}
```
```css
p {
margin: 0;
background-image: repeating-linear-gradient(
to top,
lightskyblue 0 2px,
transparent 2px 1lh
);
}
```
```html
<p style="line-height: 2em">
Summer is a time for adventure, and this year was no exception. I had many
exciting experiences, but two of my favorites were my trip to the beach and my
week at summer camp.
</p>
<p style="line-height: 4em">
At the beach, I spent my days swimming, collecting shells, and building
sandcastles. I also went on a boat ride and saw dolphins swimming alongside
us.
</p>
```
### Percentages
In a lot of cases, a percentage is treated in the same way as a length. The thing with percentages is that they are always set relative to some other value. For example, if you set an element's `font-size` as a percentage, it will be a percentage of the `font-size` of the element's parent. If you use a percentage for a `width` value, it will be a percentage of the `width` of the parent.
In the below example the two percentage-sized boxes and the two pixel-sized boxes have the same class names. The sets are 40% and 200px wide respectively.
The difference is that the second set of two boxes is inside a wrapper that is 400 pixels wide. The second 200px wide box is the same width as the first one, but the second 40% box is now 40% of 400px β a lot narrower than the first one!
**Try changing the width of the wrapper or the percentage value to see how this works.**
The next example has font sizes set in percentages. Each `<li>` has a `font-size` of 80%; therefore, the nested list items become progressively smaller as they inherit their sizing from their parent.
Note that, while many value types accept a length or a percentage, there are some that only accept length. You can see which values are accepted on the MDN property reference pages. If the allowed value includes `<length-percentage>` then you can use a length or a percentage. If the allowed value only includes `<length>`, it is not possible to use a percentage.
### Numbers
Some value types accept numbers, without any unit added to them. An example of a property which accepts a unitless number is the `opacity` property, which controls the opacity of an element (how transparent it is). This property accepts a number between `0` (fully transparent) and `1` (fully opaque).
**In the below example, try changing the value of `opacity` to various decimal values between `0` and `1` and see how the box and its contents become more or less opaque.**
**Note:** When you use a number in CSS as a value it should not be surrounded in quotes.
Color
-----
Color values can be used in many places in CSS, whether you are specifying the color of text, backgrounds, borders, and lots more.
There are many ways to set color in CSS, allowing you to control plenty of exciting properties.
The standard color system available in modern computers supports 24-bit colors, which allows displaying about 16.7 million distinct colors via a combination of different red, green, and blue channels with 256 different values per channel (256 x 256 x 256 = 16,777,216).
In this section, we'll first look at the most commonly seen ways of specifying colors: using keywords, hexadecimal, and `rgb()` values.
We'll also take a quick look at additional color functions, enabling you to recognize them when you see them or experiment with different ways of applying color.
You will likely decide on a color palette and then use those colors β and your favorite way of specifying color β throughout your project.
You can mix and match color models, but it's usually best if your entire project uses the same method of declaring colors for consistency!
### Color keywords
You will see the color keywords (or 'named colors') used in many MDN code examples. As the `<named-color>`s data type contains a very finite number of color values, these are not commonly used on production websites. As the keyword represents the color as a human-readable text value, named colors are used in code examples to clearly tell the user what color is expected so the learner can focus on the content being taught.
**Try playing with different color values in the live examples below, to get more of an idea how they work.**
### Hexadecimal RGB values
The next type of color value you are likely to encounter is hexadecimal codes.
Hexadecimal uses 16 characters from `0-9` and `a-f`, so the entire range is `0123456789abcdef`.
Each hex color value consists of a hash/pound symbol (`#`) followed by three or six hexadecimal characters (`#fcc` or `#ffc0cb`, for example), with an optional one or two hexadecimal characters representing the alpha-transparency of the previous three or six character color values.
When using hexadecimal to describe RGB values, each **pair** of hexadecimal characters is a decimal number representing one of the channels β red, green and blue β and allows us to specify any of the 256 available values for each (16 x 16 = 256).
These values are less intuitive than keywords for defining colors, but they are a lot more versatile because you can represent any RGB color with them.
**Again, try changing the values to see how the colors vary.**
### RGB values
To create RGB values directly, the `rgb()` function takes three parameters representing **red**, **green**, and **blue** channel values of the colors, with an optional fourth value separated by a slash ('/') representing opacity, in much the same way as hex values. The difference with RGB is that each channel is represented not by two hex digits, but by a decimal number between 0 and 255 or a percent between 0% and 100% inclusive (but not a mixture of the two).
Let's rewrite our last example to use RGB colors:
You can pass a fourth parameter to `rgb()`, which represents the alpha channel of the color, which controls opacity. If you set this value to `0` it will make the color fully transparent, whereas `1` will make it fully opaque. Values in between give you different levels of transparency.
**Note:** Setting an alpha channel on a color has one key difference to using the `opacity` property we looked at earlier. When you use opacity you make the element and everything inside it opaque, whereas using RGB with an alpha parameter colors only makes the color you are specifying opaque.
In the example below, we have added a background image to the containing block of our colored boxes. We have then set the boxes to have different opacity values β notice how the background shows through more when the alpha channel value is smaller.
**In this example, try changing the alpha channel values to see how it affects the color output.**
**Note:** In older versions of CSS, the `rgb()` syntax didn't support an alpha parameter - you needed to use a different function called `rgba()` for that. These days you can pass an alpha parameter to `rgb()`, but for backwards compatibility with old websites, the `rgba()` syntax is still supported, and has exactly the same behavior as `rgb()`.
### Using hues to specify a color
If you want to go beyond keywords, hexadecimal, and `rgb()` for colors, you might want to try using `<hue>`.
Hue is the property that allows us to tell the difference or similarity between colors like red, orange, yellow, green, blue, etc.
The key concept is that you can specify a hue in an `<angle>` because most of the color models describe hues using a color wheel.
A great starting point for using hues in CSS is the `hsl()` function.
Let's take a quick look at the parts you can specify:
* **Hue**: The base shade of the color. This takes a `<hue>` value between 0 and 360, representing the angles around a color wheel.
* **Saturation**: How saturated is the color? This takes a value from 0β100%, where 0 is no color (it will appear as a shade of grey), and 100% is full color saturation.
* **Lightness**: How light or bright is the color? This takes a value from 0β100%, where 0 is no light (it will appear completely black) and 100% is full light (it will appear completely white).
Similar to `rgb()`, the `hsl()` color value also has an optional fourth value, separated from the color with a slash (`/`), representing the alpha transparency.
Let's update the RGB example to use HSL colors instead:
Just like with `rgb()` you can pass an alpha parameter to `hsl()` to specify opacity:
**Note:** In older versions of CSS, the `hsl()` syntax didn't support an alpha parameter - you needed to use a different function called `hsla()` for that. These days you can pass an alpha parameter to `hsl()`, but for backwards compatibility with old websites, the `hsla()` syntax is still supported, and has exactly the same behavior as `hsl()`.
There are other color functions available such as `hwb()` and `lch()` which also use `<hue>` component, and even functions such as `lab()` which let you work with colors based on what humans can see.
If you want to find out more about these functions and color spaces, see the Applying color to HTML elements using CSS guide, the `<color>` reference that lists all the different ways you can use colors in CSS, and the CSS color module that provides an overview of all the color types in CSS and the properties that use color values.
Images
------
The `<image>` value type is used wherever an image is a valid value. This can be an actual image file pointed to via a `url()` function, or a gradient.
In the example below, we have demonstrated an image and a gradient in use as a value for the CSS `background-image` property.
**Note:** There are some other possible values for `<image>`, however these are newer and currently have poor browser support. Check out the page on MDN for the `<image>` data type if you want to read about them.
Position
--------
The `<position>` value type represents a set of 2D coordinates, used to position an item such as a background image (via `background-position`). It can take keywords such as `top`, `left`, `bottom`, `right`, and `center` to align items with specific bounds of a 2D box, along with lengths, which represent offsets from the top and left-hand edges of the box.
A typical position value consists of two values β the first sets the position horizontally, the second vertically. If you only specify values for one axis the other will default to `center`.
In the following example we have positioned a background image 40px from the top and to the right of the container using a keyword.
**Play around with these values to see how you can push the image around.**
Strings and identifiers
-----------------------
Throughout the examples above, we've seen places where keywords are used as a value (for example `<color>` keywords like `red`, `black`, `rebeccapurple`, and `goldenrod`). These keywords are more accurately described as *identifiers*, a special value that CSS understands. As such they are not quoted β they are not treated as strings.
There are places where you use strings in CSS. For example, when specifying generated content. In this case, the value is quoted to demonstrate that it is a string. In the example below, we use unquoted color keywords along with a quoted generated content string.
Functions
---------
In programming, a function is a piece of code that does a specific task.
Functions are useful because you can write code once, then reuse it many times instead of writing the same logic over and over.
Most programming languages not only support functions but also come with convenient built-in functions for common tasks so you don't have to write them yourself from scratch.
CSS also has functions, which work in a similar way to functions in other languages.
In fact, we've already seen CSS functions in the Color section above with `rgb()` and `hsl()` functions.
Aside from applying colors, you can use functions in CSS to do a lot of other things.
For example Transform functions are a common way to move, rotate, and scale elements on a page.
You might see `translate()` for moving something horizontally or vertically, `rotate()` to rotate something, or `scale()` to make something bigger or smaller.
### Math functions
When you are creating styles for a project, you will probably start off with numbers like `300px` for lengths or `200ms` for durations.
If you want to have these values change based on other values, you will need to do some math.
You could calculate the percentage of a value or add a number to another number, then update your CSS with the result.
CSS has support for Math functions, which allow us to perform calculations instead of relying on static values or doing the math in JavaScript.
One of the most common math functions is `calc()` which lets you do operations like addition, subtraction, multiplication, and division.
For example, let's say we want to set the width of an element to be 20% of its parent container plus 100px.
We can't specify this width with a static value β if the parent uses a percentage width (or a relative unit like `em` or `rem`) then it will vary depending on the context it is used in, and other factors such as the user's device or browser window width.
However, we can use `calc()` to set the width of the element to be 20% of its parent container plus 100px.
The 20% is based on the width of the parent container (`.wrapper`) and if that width changes, the calculation will change too:
There are many other math functions that you can use in CSS, such as `min()`, `max()`, and `clamp()`; respectively these let you pick the smallest, largest, or middle value from a set of values.
You can also use Trigonometric functions like `sin()`, `cos()`, and `tan()` to calculate angles for rotating elements around a point, or choose colors that take a hue angle as a parameter.
Exponential functions might also be used for animations and transitions, when you require very specific control over how something moves and looks.
Knowing about CSS functions is useful so you recognize them when you see them. You should start experimenting with them in your projects β they will help you avoid writing custom or repetitive code to achieve results that you can get with regular CSS.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Values and units.
Summary
-------
This has been a quick run-through of the most common types of values and units you might encounter. You can have a look at all of the different types on the CSS Values and units reference page β you will encounter many of these in use as you work through these lessons.
The key thing to remember is that each property has a defined list of allowed value types, and each value type has a definition explaining what the values are. You can then look up the specifics here on MDN. For example, understanding that `<image>` also allows you to create a color gradient is useful but perhaps non-obvious knowledge to have!
In the next article, we'll take a look at how items are sized in CSS.
* Previous
* Overview: Building blocks
* Next |
Advanced styling effects - Learn web development | Advanced styling effects
========================
This article acts as a box of tricks, providing an introduction to some interesting advanced styling features such as box shadows, blend modes, and filters.
| | |
| --- | --- |
| Prerequisites: |
HTML basics (study
Introduction to HTML) and an idea of how CSS works (study
CSS first steps.)
|
| Objective: |
To get an idea about how to use some of the advanced styling effects
available in modern browsers.
|
Box shadows
-----------
`box-shadow` allows you to apply one or more drop shadows to an element's box. Like text shadows, box shadows are supported pretty well across browsers, including IE9+ and Edge. Users of older IE versions might just have to cope with no shadows, so just test your designs to make sure your content is legible without them.
You can find the examples in this section at box-shadow.html (see the source code too).
### A simple box shadow
Let's look at a simple example to get things started. First, some HTML:
```html
<article class="simple">
<p>
<strong>Warning</strong>: The thermostat on the cosmic transcender has
reached a critical level.
</p>
</article>
```
Now the CSS:
```css
p {
margin: 0;
}
article {
max-width: 500px;
padding: 10px;
background-color: red;
background-image: linear-gradient(
to bottom,
rgb(0 0 0 / 0%),
rgb(0 0 0 / 25%)
);
}
.simple {
box-shadow: 5px 5px 5px rgb(0 0 0 / 70%);
}
```
This gives us the following result:
You'll see that we've got four items in the `box-shadow` property value:
1. The first length value is the **horizontal offset** β the distance to the right the shadow is offset from the original box (or left, if the value is negative).
2. The second length value is the **vertical offset** β the distance downwards that the shadow is offset from the original box (or upwards, if the value is negative).
3. The third length value is the **blur radius** β the amount of blurring applied to the shadow.
4. The color value is the **base color** of the shadow.
You can use any length and color units that would make sense to do so to define these values.
### Multiple box shadows
You can also specify multiple box shadows in a single `box-shadow` declaration, by separating them with commas:
```
<article class="multiple">
<p>
<strong>Warning</strong>: The thermostat on the cosmic transcender has
reached a critical level.
</p>
</article>
```
```css
p {
margin: 0;
}
article {
max-width: 500px;
padding: 10px;
background-color: red;
background-image: linear-gradient(
to bottom,
rgb(0 0 0 / 0%),
rgb(0 0 0 / 25%)
);
}
.multiple {
box-shadow: 1px 1px 1px black,
2px 2px 1px black,
3px 3px 1px red,
4px 4px 1px red,
5px 5px 1px black,
6px 6px 1px black;
}
```
Now we get this result:
We've done something fun here by creating a raised box with multiple colored layers, but you could use it in any way you want, for example to create a more realistic look with shadows based on multiple light sources.
### Other box shadow features
Unlike `text-shadow`, `box-shadow` has an `inset` keyword available β putting this at the start of a shadow declaration causes it to become an inner shadow, rather than an outer shadow. Let's have a look and see what we mean.
First, we'll go with some different HTML for this example:
```html
<button>Press me!</button>
```
```css
button {
width: 150px;
font-size: 1.1rem;
line-height: 2;
border-radius: 10px;
border: none;
background-image: linear-gradient(to bottom right, #777, #ddd);
box-shadow:
1px 1px 1px black,
inset 2px 3px 5px rgb(0 0 0 / 30%),
inset -2px -3px 5px rgb(255 255 255 / 50%);
}
button:focus,
button:hover {
background-image: linear-gradient(to bottom right, #888, #eee);
}
button:active {
box-shadow:
inset 2px 2px 1px black,
inset 2px 3px 5px rgb(0 0 0 / 30%),
inset -2px -3px 5px rgb(255 255 255 / 50%);
}
```
This gives us the following result:
Here we've set up some button styling along with focus/hover/active states. The button has a simple black box shadow set on it by default, plus a couple of inset shadows, one light and one dark, placed on opposite corners of the button to give it a nice shading effect.
When the button is pressed in, the active state causes the first box shadow to be swapped for a very dark inset shadow, giving the appearance of the button being pressed in.
**Note:** There is another item that can be set in the `box-shadow` value β another length value can be optionally set just before the color value, which is a **spread radius**. If set, this causes the shadow to become bigger than the original box. It is not very commonly used, but worth mentioning.
Filters
-------
While you can't change the composure of an image using CSS, there are some creative things you can do. One very nice property, which can help you bring interest to your designs, is the `filter` property. This property enables Photoshop-like filters right from CSS.
In the example below we have used two different values for filter. The `first` is `blur()` β this function can be passed a value to indicate how much the image should be blurred.
The second is `grayscale()`; by using a percentage we are setting how much color we want to be removed.
**Play with the percentage and pixel parameters in the live example to see how the images change. You could also swap the values for some others. Try `contrast(200%)`, `invert(100%)` or `hue-rotate(20deg)` on the live example above. Take a look at the MDN page for `filter` for many other options you could try.**
You can apply filters to any element and not just images. Some of the filter options available do very similar things to other CSS features, for example `drop-shadow()` works in a very similar way and gives a similar effect to `box-shadow` or `text-shadow`. The really nice thing about filters however, is that they work on the exact shapes of the content inside the box, not just the box itself as one big chunk, so it is worth knowing the difference.
In this next example we are applying our filter to a box, and comparing it to a box shadow. As you can see, the drop-shadow filter follows the exact shape of the text and border dashes. The box shadow just follows the square of the box.
Blend modes
-----------
CSS blend modes allow us to add blend modes to elements that specify a blending effect when two elements overlap β the final color shown for each pixel will be the result of a combination of the original pixel color, and that of the pixel in the layer underneath it. Blend modes are again very familiar to users of graphics applications like Photoshop.
There are two properties that use blend modes in CSS:
* `background-blend-mode`, which blends together multiple background images and colors set on a single element.
* `mix-blend-mode`, which blends together the element it is set on with elements it is overlapping β both background and content.
You can find a lot more examples than are available here in our blend-modes.html example page (see source code), and on the `<blend-mode>` reference page.
**Note:** Blend modes are also very new, and slightly less well supported than filters. There is no support as yet in Edge, and Safari only supports some of the blend mode options.
### background-blend-mode
Again, let's look at some examples so we can understand this better. First, `background-blend-mode` β here we'll show a couple of simple `<div>`s, so you can compare the original with the blended version:
```html
<div></div>
<div class="multiply"></div>
```
Now some CSS β we are adding to the `<div>` one background image and a green background color:
```css
div {
width: 250px;
height: 130px;
padding: 10px;
margin: 10px;
display: inline-block;
background: url(colorful-heart.png) no-repeat center 20px;
background-color: green;
}
.multiply {
background-blend-mode: multiply;
}
```
The result we get is this β you can see the original on the left, and the multiply blend mode on the right:
### mix-blend-mode
Now let's look at `mix-blend-mode`. Here we'll present the same two `<div>`s, but each one is now sat on top of a simple `<div>` with a purple background, to show how the elements will blend together:
```html
<article>
No mix blend mode
<div></div>
<div></div>
</article>
<article>
Multiply mix
<div class="multiply-mix"></div>
<div></div>
</article>
```
Here's the CSS we'll style this with:
```css
article {
width: 280px;
height: 180px;
margin: 10px;
position: relative;
display: inline-block;
}
div {
width: 250px;
height: 130px;
padding: 10px;
margin: 10px;
}
article div:first-child {
position: absolute;
top: 10px;
left: 0;
background: url(colorful-heart.png) no-repeat center 20px;
background-color: green;
}
article div:last-child {
background-color: purple;
position: absolute;
bottom: -10px;
right: 0;
z-index: -1;
}
.multiply-mix {
mix-blend-mode: multiply;
}
```
This gives us the following results:
You can see here that the multiply mix blend has blended together not only the two background images, but also the color from the `<div>` below it too.
**Note:** Don't worry if you don't understand some of the layout properties above, like `position`, `top`, `bottom`, `z-index`, etc. We will cover these in detail in our CSS Layout module.
CSS shapes
----------
While it is true that everything in CSS is a rectangular box, and images are a physical rectangular box, we can make it look as if our content flows around non-rectangular things by using CSS Shapes.
The CSS Shapes specification enables the wrapping of text around a non-rectangular shape. It's especially useful when working with an image which has some white-space you might want to float text around.
In the image below we have a pleasingly round balloon. The actual file is rectangular, but by floating the image (shapes only apply to floated elements) and using the `shape-outside` property with a value of `circle(50%)`, we can give the effect of the text following the line of the balloon.
The shape in this example is not reacting to the content of the image file. Instead, the circle function is taking its center point from the center of the image file, as if we had put a compass in the middle of the file and drawn a circle that fits inside the file. It is that circle that the text flows around.
**Note:** In Firefox you can use the DevTools Shapes Inspector to inspect Shapes.
The `circle()` function is just one of a few basic shapes that are defined, however there are a number of different ways to create shapes. For more information and example code for CSS Shapes see the Guides to CSS Shapes on MDN.
-webkit-background-clip: text
-----------------------------
Another feature we thought we'd mention briefly is the `text` value for `background-clip`. When used along with the proprietary `-webkit-text-fill-color: transparent;` feature, this allows you to clip background images to the shape of the element's text, making for some nice effects. This is not an official standard, but has been implemented across multiple browsers, as it is popular, and used fairly widely by developers. When used in this context, both of the properties would require a `-webkit-` vendor prefix, even for Non-Webkit/Chrome-based browsers:
```css
.text-clip {
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
```
So why have other browsers implemented a `-webkit-` prefix? Mainly for browser compatibility β so many web developers have started implementing websites with `-webkit-` prefixes that it started to look like the other browsers were broken, whereas in actual fact they were following the standards. So they were forced to implement a few such features. This highlights the danger of using non-standard and/or prefixed CSS features in your work β not only do they cause browser compatibility issues, but they are also subject to change, so your code could break at any time. It is much better to stick to the standards.
If you do want to use such features in your production work, make sure to test across browsers thoroughly and check that, where these features don't work, the site is still usable.
**Note:** For a full `-webkit-background-clip: text` code example, see background-clip-text.html (see also the source code).
Summary
-------
We hope this article was fun β playing with shiny toys generally is, and it is always interesting to see what kinds of advanced styling tools are becoming available in modern browsers. |
Debugging CSS - Learn web development | Debugging CSS
=============
* Previous
* Overview: Building blocks
* Next
Sometimes when writing CSS you will encounter an issue where your CSS doesn't seem to be doing what you expect. Perhaps you believe that a certain selector should match an element, but nothing happens, or a box is a different size than you expected. This article will give you guidance on how to go about debugging a CSS problem, and show you how the DevTools included in all modern browsers can help you to find out what is going on.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: |
To learn the basics of what browser DevTools are, and how to do simple
inspection and editing of CSS.
|
How to access browser DevTools
------------------------------
The article What are browser developer tools is an up-to-date guide explaining how to access the tools in various browsers and platforms. While you may choose to mostly develop in a particular browser, and therefore will become most familiar with the tools included in that browser, it is worth knowing how to access them in other browsers. This will help if you are seeing different rendering between multiple browsers.
You will also find that browsers have chosen to focus on different areas when creating their DevTools. For example, in Firefox there are some excellent tools for working visually with CSS Layout, allowing you to inspect and edit Grid Layouts, Flexbox, and Shapes. However, all of the different browsers have similar fundamental tools, e.g., for inspecting the properties and values applied to elements on your page, and making changes to them from the editor.
In this lesson we will look at some useful features of the Firefox DevTools for working with CSS. In order to do so I'll be using an example file. Load this up in a new tab if you want to follow along, and open up your DevTools as described in the article linked above.
The DOM versus view source
--------------------------
Something that can trip up newcomers to DevTools is the difference between what you see when you view the source of a webpage, or look at the HTML file you put on the server, and what you can see in the HTML Pane of the DevTools. While it looks roughly similar to what you can see via View Source there are some differences.
In the rendered DOM the browser may have normalized the HTML, for example by correcting some badly-written HTML for you. If you incorrectly closed an element, for instance by opening an `<h2>` but closing with an `</h3>`, the browser will figure out what you were meaning to do and the HTML in the DOM will correctly close the open `<h2>` with an `</h2>`. The DOM will also show any changes made by JavaScript.
View Source, in comparison, is the HTML source code as stored on the server. The HTML tree in your DevTools shows exactly what the browser is rendering at any given time, so it gives you an insight into what is really going on.
Inspecting the applied CSS
--------------------------
Select an element on your page, either by right/ctrl-clicking on it and selecting *Inspect*, or selecting it from the HTML tree on the left of the DevTools display. Try selecting the element with the class of `box1`; this is the first element on the page with a bordered box drawn around it.
![The example page for this tutorial with DevTools open.](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/inspecting1.png)
If you look at the Rules view to the right of your HTML, you should be able to see the CSS properties and values applied to that element. You will see the rules directly applied to class `box1` and also the CSS that is being inherited by the box from its ancestors, in this case from `<body>`. This is useful if you are seeing some CSS being applied that you didn't expect. Perhaps it is being inherited from a parent element and you need to add a rule to overwrite it in the context of this element.
Also useful is the ability to expand out shorthand properties. In our example the `margin` shorthand is used.
**Click on the little arrow to expand the view, showing the different longhand properties and their values.**
**You can toggle values in the Rules view on and off when that panel is active β if you hold your mouse over it, checkboxes will appear. Uncheck a rule's checkbox, for example `border-radius`, and the CSS will stop applying.**
You can use this to do an A/B comparison, deciding if something looks better with a rule applied or not, and also to help debug it β for example, if a layout is going wrong and you are trying to work out which property is causing the problem.
The following video provides some useful tips on debugging CSS using the Firefox DevTools:
Editing values
--------------
In addition to turning properties on and off, you can edit their values. Perhaps you want to see if another color looks better, or wish to tweak the size of something? DevTools can save you a lot of time editing a stylesheet and reloading the page.
**With `box1` selected, click on the swatch (the small colored circle) that shows the color applied to the border. A color picker will open up and you can try out some different colors; these will update in real time on the page. In a similar fashion, you could change the width or style of the border.**
![DevTools Styles Panel with a color picker open.](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/inspecting2-color-picker.png)
Adding a new property
---------------------
You can add properties using the DevTools. Perhaps you have realized that you don't want your box to inherit the `<body>` element's font size, and want to set its own specific size? You can try this out in DevTools before adding it to your CSS file.
**You can click the closing curly brace in the rule to start entering a new declaration into it, at which point you can start typing the new property and DevTools will show you an autocomplete list of matching properties. After selecting `font-size`, enter the value you want to try. You can also click the + button to add an additional rule with the same selector, and add your new rules there.**
![The DevTools Panel, adding a new property to the rules, with the autocomplete for font- open](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/inspecting3-font-size.png)
**Note:** There are other useful features in the Rules view too, for example declarations with invalid values are crossed out. You can find out more at Examine and edit CSS.
Understanding the box model
---------------------------
In previous lessons we have discussed the Box Model, and the fact that we have an alternate box model that changes how the size of elements are calculated based on the size you give them, plus the padding and borders. DevTools can really help you to understand how the size of an element is being calculated.
The Layout view shows you a diagram of the box model on the selected element, along with a description of the properties and values that change how the element is laid out. This includes a description of properties that you may not have explicitly used on the element, but which do have initial values set.
In this panel, one of the detailed properties is the `box-sizing` property, which controls what box model the element uses.
**Compare the two boxes with classes `box1` and `box2`. They both have the same width applied (400px), however `box1` is visually wider. You can see in the layout panel that it is using `content-box`. This is the value that takes the size you give the element and then adds on the padding and border width.**
The element with a class of `box2` is using `border-box`, so here the padding and border is subtracted from the size that you have given the element. This means that the space taken up on the page by the box is the exact size that you specified β in our case `width: 400px`.
![The Layout section of the DevTools](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/inspecting4-box-model.png)
**Note:** Find out more in Examining and Inspecting the Box Model.
Solving specificity issues
--------------------------
Sometimes during development, but in particular when you need to edit the CSS on an existing site, you will find yourself having a hard time getting some CSS to apply. No matter what you do, the element just doesn't seem to take the CSS. What is generally happening here is that a more specific selector is overriding your changes, and here DevTools will really help you out.
In our example file there are two words that have been wrapped in an `<em>` element. One is displaying as orange and the other hotpink. In the CSS we have applied:
```css
em {
color: hotpink;
font-weight: bold;
}
```
Above that in the stylesheet however is a rule with a `.special` selector:
```css
.special {
color: orange;
}
```
As you will recall from the lesson on cascade and inheritance where we discussed specificity, class selectors are more specific than element selectors, and so this is the value that applies. DevTools can help you find such issues, especially if the information is buried somewhere in a huge stylesheet.
**Inspect the `<em>` with the class of `.special` and DevTools will show you that orange is the color that applies, and also that the `color` property applied to the `<em>` is crossed out. You can now see that the class selector is overriding the element selector.**
![Selecting an em and looking at DevTools to see what is over-riding the color.](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/inspecting5-specificity.png)
Find out more about the Firefox DevTools
----------------------------------------
There is a lot of information about the Firefox DevTools here on MDN. Take a look at the main DevTools section, and for more detail on the things we have briefly covered in this lesson see The How To Guides.
Debugging problems in CSS
-------------------------
DevTools can be a great help when solving CSS problems, so when you find yourself in a situation where CSS isn't behaving as you expect, how should you go about solving it? The following steps should help.
### Take a step back from the problem
Any coding problem can be frustrating, especially CSS problems because you often don't get an error message to search for online to help with finding a solution. If you are becoming frustrated, take a step away from the issue for a while β go for a walk, grab a drink, chat to a co-worker, or work on some other thing for a while. Sometimes the solution magically appears when you stop thinking about the problem, and even if not, working on it when feeling refreshed will be much easier.
### Do you have valid HTML and CSS?
Browsers expect your CSS and HTML to be correctly written, however browsers are also very forgiving and will try their best to display your webpages even if you have errors in the markup or stylesheet. If you have mistakes in your code the browser needs to make a guess at what you meant, and it might make a different decision to what you had in mind. In addition, two different browsers might cope with the problem in two different ways. A good first step, therefore, is to run your HTML and CSS through a validator, to pick up and fix any errors.
* CSS Validator
* HTML validator
### Are the property and value supported by the browser you are testing in?
Browsers ignore CSS they don't understand. If the property or value you are using is not supported by the browser you are testing in then nothing will break, but that CSS won't be applied. DevTools will generally highlight unsupported properties and values in some way. In the screenshot below the browser does not support the subgrid value of `grid-template-columns`.
![Image of browser DevTools with the grid-template-columns: subgrid crossed out as the subgrid value is not supported.](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/no-support.png)
You can also take a look at the Browser compatibility tables at the bottom of each property page on MDN. These show you browser support for that property, often broken down if there is support for some usage of the property and not others. See the compatibility table for the `shape-outside` property.
### Is something else overriding your CSS?
This is where the information you have learned about specificity will come into much use. If you have something more specific overriding what you are trying to do, you can enter into a very frustrating game of trying to work out what. However, as described above, DevTools will show you what CSS is applying and you can work out how to make the new selector specific enough to override it.
### Make a reduced test case of the problem
If the issue isn't solved by the steps above, then you will need to do some more investigating. The best thing to do at this point is to create something known as a reduced test case. Being able to "reduce an issue" is a really useful skill. It will help you find problems in your own code and that of your colleagues, and will also enable you to report bugs and ask for help more effectively.
A reduced test case is a code example that demonstrates the problem in the simplest possible way, with unrelated surrounding content and styling removed. This will often mean taking the problematic code out of your layout to make a small example which only shows that code or feature.
To create a reduced test case:
1. If your markup is dynamically generated β for example via a CMS β make a static version of the output that shows the problem. A code sharing site like CodePen is useful for hosting reduced test cases, as then they are accessible online and you can easily share them with colleagues. You could start by doing View Source on the page and copying the HTML into CodePen, then grab any relevant CSS and JavaScript and include it too. After that, you can check whether the issue is still evident.
2. If removing the JavaScript does not make the issue go away, don't include the JavaScript. If removing the JavaScript *does* make the issue go away, then remove as much JavaScript as you can, leaving in whatever causes the issue.
3. Remove any HTML that does not contribute to the issue. Remove components or even main elements of the layout. Again, try to get down to the smallest amount of code that still shows the issue.
4. Remove any CSS that doesn't impact the issue.
In the process of doing this, you may discover what is causing the problem, or at least be able to turn it on and off by removing something specific. It is worth adding some comments to your code as you discover things. If you need to ask for help, they will show the person helping you what you have already tried. This may well give you enough information to be able to search for likely problems and workarounds.
If you are still struggling to fix the problem then having a reduced test case gives you something to ask for help with, by posting to a forum, or showing to a co-worker. You are much more likely to get help if you can show that you have done the work of reducing the problem and identifying exactly where it happens, before asking for help. A more experienced developer might be able to quickly spot the problem and point you in the right direction, and even if not, your reduced test case will enable them to have a quick look and hopefully be able to offer at least some help.
In the instance that your problem is actually a bug in a browser, then a reduced test case can also be used to file a bug report with the relevant browser vendor (e.g. on Mozilla's bugzilla site).
As you become more experienced with CSS, you will find that you get faster at figuring out issues. However, even the most experienced of us sometimes find ourselves wondering what on earth is going on. Taking a methodical approach, making a reduced test case, and explaining the issue to someone else will usually result in a fix being found.
Summary
-------
So there we have it: an introduction to debugging CSS, which should give you some useful skills to count on when you start to debug CSS and other types of code later on in your career.
In the last article of this module, we'll take a look at how to organize your CSS.
* Previous
* Overview: Building blocks
* Next |
Backgrounds and borders - Learn web development | Backgrounds and borders
=======================
* Previous
* Overview: Building blocks
* Next
In this lesson, we will take a look at some of the creative things you can do with CSS backgrounds and borders. From adding gradients, background images, and rounded corners, backgrounds and borders are the answer to a lot of styling questions in CSS.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: | To learn how to style the background and border of boxes. |
Styling backgrounds in CSS
--------------------------
The CSS `background` property is a shorthand for a number of background longhand properties that we will meet in this lesson. If you discover a complex background property in a stylesheet, it might seem a little hard to understand as so many values can be passed in at once.
```css
.box {
background:
linear-gradient(
105deg,
rgb(255 255 255 / 20%) 39%,
rgb(51 56 57 / 100%) 96%
) center center / 400px 200px no-repeat,
url(big-star.png) center no-repeat,
rebeccapurple;
}
```
We'll return to how the shorthand works later in the tutorial, but first let's have a look at the different things you can do with backgrounds in CSS, by looking at the individual background properties.
### Background colors
The `background-color` property defines the background color on any element in CSS. The property accepts any valid `<color>`. A `background-color` extends underneath the content and padding box of the element.
In the example below, we have used various color values to add a background color to the box, a heading, and a `<span>` element.
**Play around with these, using any available <color> value.**
### Background images
The `background-image` property enables the display of an image in the background of an element. In the example below, we have two boxes β one has a background image which is larger than the box (balloons.jpg), the other has a small image of a single star (star.png).
This example demonstrates two things about background images. By default, the large image is not scaled down to fit the box, so we only see a small corner of it, whereas the small image is tiled to fill the box.
**If you specify a background color in addition to a background image then the image displays on top of the color. Try adding a `background-color` property to the example above to see that in action.**
#### Controlling background-repeat
The `background-repeat` property is used to control the tiling behavior of images. The available values are:
* `no-repeat` β stop the background from repeating altogether.
* `repeat-x` β repeat horizontally.
* `repeat-y` β repeat vertically.
* `repeat` β the default; repeat in both directions.
**Try these values out in the example below. We have set the value to `no-repeat` so you will only see one star. Try out the different values β `repeat-x` and `repeat-y` β to see what their effects are.**
#### Sizing the background image
The *balloons.jpg* image used in the initial background images example, is a large image that was cropped due to being larger than the element it is a background of. In this case we could use the `background-size` property, which can take `<length>` or `<percentage>` values, to size the image to fit inside the background.
You can also use keywords:
* `cover` β the browser will make the image just large enough so that it completely covers the box area while still retaining its aspect ratio. In this case, part of the image is likely to end up outside the box.
* `contain` β the browser will make the image the right size to fit inside the box. In this case, you may end up with gaps on either side or on the top and bottom of the image, if the aspect ratio of the image is different from that of the box.
In the example below I have used the *balloons.jpg* image along with length units to size it inside the box. You can see this has distorted the image.
Try the following.
* Change the length units used to modify the size of the background.
* Remove the length units and see what happens when you use `background-size: cover` or `background-size: contain`.
* If your image is smaller than the box, you can change the value of `background-repeat` to repeat the image.
#### Positioning the background image
The `background-position` property allows you to choose the position in which the background image appears on the box it is applied to. This uses a coordinate system in which the top-left-hand corner of the box is `(0,0)`, and the box is positioned along the horizontal (`x`) and vertical (`y`) axes.
**Note:** The default `background-position` value is `(0,0)`.
The most common `background-position` values take two individual values β a horizontal value followed by a vertical value.
You can use keywords such as `top` and `right` (look up the others on the `background-position` page):
```css
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: top center;
}
```
And `lengths`, and `percentages`:
```css
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: 20px 10%;
}
```
You can also mix keyword values with lengths or percentages, in which case the first value must refer to the horizontal position or offset and the second vertical. For example:
```css
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: 20px top;
}
```
Finally, you can also use a 4-value syntax in order to indicate a distance from certain edges of the box β the length unit, in this case, is an offset from the value that precedes it. So in the CSS below we are positioning the background 20px from the top and 10px from the right:
```css
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: top 20px right 10px;
}
```
**Use the example below to play around with these values and move the star around inside the box.**
**Note:** `background-position` is a shorthand for `background-position-x` and `background-position-y`, which allow you to set the different axis position values individually.
### Gradient backgrounds
A gradient β when used for a background β acts just like an image and is also set by using the `background-image` property.
You can read more about the different types of gradients and things you can do with them on the MDN page for the `<gradient>` data type. A fun way to play with gradients is to use one of the many CSS Gradient Generators available on the web, such as this one. You can create a gradient then copy and paste out the source code that generates it.
Try some different gradients in the example below. In the two boxes respectively, we have a linear gradient that is stretched over the whole box, and a radial gradient with a set size, which therefore repeats.
### Multiple background images
It is also possible to have multiple background images β you specify multiple `background-image` values in a single property value, separating each one with a comma.
When you do this you may end up with background images overlapping each other. The backgrounds will layer with the last listed background image at the bottom of the stack, and each previous image stacking on top of the one that follows it in the code.
**Note:** Gradients can be happily mixed with regular background images.
The other `background-*` properties can also have comma-separated values in the same way as `background-image`:
```css
background-image: url(image1.png), url(image2.png), url(image3.png),
url(image4.png);
background-repeat: no-repeat, repeat-x, repeat;
background-position:
10px 20px,
top right;
```
Each value of the different properties will match up to the values in the same position in the other properties. Above, for example, `image1`'s `background-repeat` value will be `no-repeat`. However, what happens when different properties have different numbers of values? The answer is that the smaller numbers of values will cycle β in the above example there are four background images but only two `background-position` values. The first two position values will be applied to the first two images, then they will cycle back around again β `image3` will be given the first position value, and `image4` will be given the second position value.
**Let's play. In the example below I have included two images. To demonstrate the stacking order, try switching which background image comes first in the list. Or play with the other properties to change the position, size, or repeat values.**
### Background attachment
Another option we have available for backgrounds is specifying how they scroll when the content scrolls. This is controlled using the `background-attachment` property, which can take the following values:
* `scroll`: causes the element's background to scroll when the page is scrolled. If the element content is scrolled, the background does not move. In effect, the background is fixed to the same position on the page, so it scrolls as the page scrolls.
* `fixed`: causes an element's background to be fixed to the viewport so that it doesn't scroll when the page or element content is scrolled. It will always remain in the same position on the screen.
* `local`: fixes the background to the element it is set on, so when you scroll the element, the background scrolls with it.
The `background-attachment` property only has an effect when there is content to scroll, so we've made a demo to demonstrate the differences between the three values β have a look at background-attachment.html (also see the source code here).
### Using the background shorthand property
As I mentioned at the beginning of this lesson, you will often see backgrounds specified using the `background` property. This shorthand lets you set all of the different properties at once.
If using multiple backgrounds, you need to specify all of the properties for the first background, then add your next background after a comma. In the example below we have a gradient with a size and position, then an image background with `no-repeat` and a position, then a color.
There are a few rules that need to be followed when writing background image shorthand values, for example:
* A `background-color` may only be specified after the final comma.
* The value of `background-size` may only be included immediately after `background-position`, separated with the '/' character, like this: `center/80%`.
Take a look at the MDN page for `background` to see all of the considerations.
### Accessibility considerations with backgrounds
When placing text on top of a background image or color, you should take care that you have enough contrast for the text to be legible for your visitors. If specifying an image, and if text will be placed on top of that image, you should also specify a `background-color` that will allow the text to be legible if the image does not load.
Screen readers cannot parse background images; therefore, they should be purely decoration. Any important content should be part of the HTML page and not contained in a background.
Borders
-------
When learning about the Box Model, we discovered how borders affect the size of our box. In this lesson we will look at how to use borders creatively. Typically when we add borders to an element with CSS we use a shorthand property that sets the color, width, and style of the border in one line of CSS.
We can set a border for all four sides of a box with `border`:
```css
.box {
border: 1px solid black;
}
```
Or we can target one edge of the box, for example:
```css
.box {
border-top: 1px solid black;
}
```
The individual properties for these shorthands would be:
```css
.box {
border-width: 1px;
border-style: solid;
border-color: black;
}
```
And for the longhands:
```css
.box {
border-top-width: 1px;
border-top-style: solid;
border-top-color: black;
}
```
**Note:** These top, right, bottom, and left border properties also have mapped *logical* properties that relate to the writing mode of the document (e.g. left-to-right or right-to-left text, or top-to-bottom). We'll be exploring these in the next lesson, which covers handling different text directions.
There are a variety of styles that you can use for borders. In the example below, we have used two different border styles for the box and two different border styles for the heading. Play with the border style, width, and color to see how borders work.
### Rounded corners
Rounding corners on a box is achieved by using the `border-radius` property and associated longhands which relate to each corner of the box. Two lengths or percentages may be used as a value, the first value defining the horizontal radius, and the second the vertical radius. In a lot of cases, you will only pass in one value, which will be used for both.
For example, to make all four corners of a box have a 10px radius:
```css
.box {
border-radius: 10px;
}
```
Or to make the top right corner have a horizontal radius of 1em, and a vertical radius of 10%:
```css
.box {
border-top-right-radius: 1em 10%;
}
```
We have set all four corners in the example below and then changed the values for the top right corner to make it different. You can play with the values to change the corners. Take a look at the property page for `border-radius` to see the available syntax options.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Backgrounds and borders.
Summary
-------
We have covered quite a lot here, and you can see that there is quite a lot to adding a background or a border to a box. Do explore the different property pages if you want to find out more about any of the features we have discussed. Each page on MDN has more examples of usage for you to play with and enhance your knowledge.
In the next article, we'll find out how the Writing Mode of your document interacts with your CSS. What happens when the text does not flow from left to right?
* Previous
* Overview: Building blocks
* Next |
Cascade layers - Learn web development | Cascade layers
==============
* Previous
* Overview: Building blocks
* Next
This lesson aims to introduce you to cascade layers, a more advanced feature that builds on the fundamental concepts of the CSS cascade and CSS specificity.
If you are new to CSS, working through this lesson may seem less relevant immediately and a little more academic than some other parts of the course. However, knowing the basics of what cascade layers are should you encounter them in your projects is helpful. The more you work with CSS, understanding cascade layers and knowing how to leverage their power will save you from a lot of pain managing a code base with CSS from different parties, plugins, and development teams.
Cascade layers are most relevant when you're working with CSS from multiple sources when there are conflicting CSS selectors and competing specificities, or when you're considering using `!important`.
| | |
| --- | --- |
| Prerequisites: |
An idea of how CSS works, including cascade and specificity (study
CSS first steps and Cascade, specificity, and inheritance).
|
| Objective: | To learn how cascade layers work. |
For each CSS property applied to an element, there can only be one value. You can view all the property values applied to an element by inspecting the element in your browser's developer tools. The tool's "Styles" panel shows all the property values applied to the element being inspected, along with the matched selector and the CSS source file. The selector from the origin with precedence has its values applied to the matching element.
In addition to the applied styles, the Styles panel displays crossed-out values that matched the selected element but were not applied due to the cascade, specificity, or source order. Crossed-out styles may come from the same origin with precedence but with lower specificity, or with matching origin and specificity, but were found earlier in the code base. For any applied property value, there may be several declarations crossed out from many different sources. If you see a style crossed out that has a selector with greater specificity it means the value is lacking in origin or importance.
Often, as the complexity of a site increases, the number of stylesheets increases, which makes the source order of the stylesheets both more important and more complex. Cascade layers simplify maintaining stylesheets across such code bases. Cascade layers are explicit specificity containers providing simpler and greater control over the CSS declarations that ultimately get applied, enabling web developers to prioritize sections of CSS without having to fight specificity.
To understand cascade layers, you must understand the CSS cascade well. The sections below provide a quick recap of the important cascade concepts.
Review of the cascade concept
-----------------------------
The C in CSS stands for "Cascading". It is the method by which styles cascade together. The user agent runs through several clearly defined steps to determine the values assigned to every property for every element. We will briefly list these steps here and then dig deeper into step 4, **Cascade layers**, which is what you came here to learn:
1. **Relevance:** Find all the declaration blocks with a selector match for each element.
2. **Importance:** Sort rules based on whether they are normal or important. Important styles are those that have the `!important` flag set.
3. **Origin:** Within each of the two importance buckets, sort rules by author, user, or user-agent origin.
4. **Cascade layers:** Within each of the six origin importance buckets, sort by cascade layer. The layer order for normal declarations is from the first layer created to the last, followed by unlayered normal styles. This order is inverted for important styles, with unlayered important styles having the lowest precedence.
5. **Specificity:** For competing styles in the origin layer with precedence, sort declarations by specificity.
6. **Scoping proximity**: When two selectors in the origin layer with precedence have the same specificity, the property value within scoped rules with the smallest number of hops up the DOM hierarchy to the scope root wins. See How `@scope` conflicts are resolved for more details and an example.
7. **Order of appearance:** When two selectors in the origin layer with precedence have the same specificity and scope proximity, the property value from the last declared selector with the highest specificity wins.
For each step, only the declarations "still in the running" move on to "compete" in the next step. If only one declaration is in the running, it "wins", and the subsequent steps are moot.
### Origin and cascade
There are three cascade origin types: user-agent stylesheets, user stylesheets, and author stylesheets. The browser sorts each declaration into six origin buckets by origin and importance. There are eight levels of precedence: the six origin buckets, properties that are transitioning, and properties that are animating. The order of precedence goes from normal user-agent styles, which have the lowest precedence, to styles within currently applied animations, to important user-agent styles, and then styles being transitioned, which have the highest precedence:
1. user-agent normal styles
2. user normal styles
3. author normal styles
4. styles being animated
5. author important styles
6. user important styles
7. user-agent important styles
8. styles being transitioned
The "user-agent" is the browser. The "user" is the site visitor. The "author" is you, the developer. Styles declared directly on an element with the `<style>` element are author styles. Not including animating and transitioning styles, user-agent normal styles have the lowest precedence; user-agent important styles have the highest.
### Origin and specificity
For each property, the declaration that "wins" is the one from the origin with precedence based on the weight (normal or important). Ignoring layers for the moment, the value from the origin with the highest precedence gets applied. If the winning origin has more than one property declaration for an element, the specificity of the selectors for those competing property values are compared. Specificity is never compared between selectors from different origins.
In the example below, there are two links. The first has no author styles applied, so only user-agent styles are applied (and your personal user styles, if any). The second has `text-decoration` and `color` set by author styles even though the selector in the author stylesheet has a specificity of `0-0-0`. The reason why author styles "win" is because when there are conflicting styles from different origins, the rules from the origin with precedence are applied, irrespective of the specificity in the origin that doesn't have precedence.
The "competing" selector in the user-agent stylesheet at the time of this writing is `a:any-link`, which has a specificity weight of `0-1-1`. While this is greater than the `0-0-0` selector in the author stylesheet, even if the selector in your current user agent is different, it doesn't matter: the specificity weights from author and user-agent origins are never compared. Learn more about how specificity weight is calculated.
Origin precedence always wins over selector specificity. If an element property is styled with a normal style declaration in multiple origins, the author style sheet will always override the redundant normal properties declared in a user or user-agent stylesheet. If the style is important, the user-agent stylesheet will always win over author and user styles. Cascade origin precedence ensures specificity conflicts between origins never happen.
One last thing to note before moving on: the order of appearance becomes relevant only when competing declarations in the origin of precedence have the same specificity.
Overview of cascade layers
--------------------------
We now understand "cascade origin precedence", but what is "cascade layer precedence"? We will answer that question by addressing what cascade layers are, how they are ordered, and how styles are assigned to cascade layers. We'll cover regular layers, nested layers, and anonymous layers. Let's first discuss what cascade layers are and what issues they solve.
### Cascade layer precedence order
Similar to how we have six levels of priority based on origin and importance, cascade layers enable us to create sub-origin level of priority within any of those origins.
Within each of the six origin buckets, there can be multiple cascade layers. The order of layer creation matters a lot. It is the order of creation that sets the precedence order among layers within an origin.
In normal origin buckets, layers are sorted in the order of each layer's creation. The order of precedence is from the first layer created to the last, followed by unlayered normal styles.
This order is inverted for important styles. All unlayered important styles cascade together into an implicit layer having precedence over all non-transitioning normal styles. The unlayered important styles have lower precedence than any important layered styles. The important styles in earlier declared layers have precedence over important styles in subsequent declared layers within the same origin.
For the rest of this tutorial, we will limit our discussion to author styles, but keep in mind that layers can also exist in user and user-agent stylesheets.
### Issues cascade layers can solve
Large code bases can have styles coming from multiple teams, component libraries, frameworks, and third parties. No matter how many stylesheets are included, all these styles cascade together in a single origin: the *author* style sheet.
Having styles from many sources cascade together, especially from teams that aren't working together, can create problems. Different teams may have different methodologies; one may have a best practice of reducing specificity, while another may have a standard of including an `id` in each selector.
Specificity conflicts can escalate quickly. A web developer may create a "quick fix" by adding an `!important` flag. While this may feel like an easy solution, it often just moves the specificity war from normal to important declarations.
In the same way that cascade origins provide a balance of power between user, user-agents, and author styles, cascade layers provide a structured way to organize and balance concerns within a single origin as if each layer in an origin were a sub-origin. A layer can be created for each team, component, and third party, with style precedence based on layer order.
Rules within a layer cascade together, without competing with style rules outside the layer. Cascade layers enable the prioritizing of entire stylesheets over other stylesheets, without having to worry about specificity between these sub-origins.
Layer precedence always beats selector specificity. Styles in layers with precedence "win" over layers with less precedence. The specificity of a selector in a losing layer is irrelevant. Specificity still matters for competing property values within a layer, but there are no specificity concerns between layers because only the highest-priority layer for each property is considered.
### Issues nested cascade layers can solve
Cascade layers allow the creation of nested layers. Each cascade layer can contain nested layers.
For example, a component library may be imported into a `components` layer. A regular cascade layer will add the component library to the author origin, removing any specificity conflicts with other author styles. Within the `components` layer, a developer can choose to define various themes, each as a separate nested layer. The order of these nested theme layers can be defined based on media queries (see the Layer creation and media queries section below), such as viewport size or orientation. These nested layers provide a way to create themes that don't conflict based on specificity.
The ability to nest layers is very useful for anybody who works on developing component libraries, frameworks, third-party widgets, and themes.
The ability to create nested layers also removes the worry of having conflicting layer names. We'll cover this in the nested layer section.
>
> "Authors can create layers to represent element defaults, third-party libraries, themes, components, overrides, and other styling concernsβand are able to re-order the cascade of layers in an explicit way, without altering selectors or specificity within each layer, or relying on order of appearance to resolve conflicts across layers."
>
>
> βCascading and Inheritance specification.
>
>
>
Creating cascade layers
-----------------------
Layers can be created using any one of the following methods:
* The `@layer` statement at-rule, declaring layers using `@layer` followed by the names of one or more layers. This creates named layers without assigning any styles to them.
* The `@layer` block at-rule, in which all styles within a block are added to a named or unnamed layer.
* The `@import` rule with the `layer` keyword or `layer()` function, which assigns the contents of the imported file into that layer.
All three methods create a layer if a layer with that name has not already been initialized. If no layer name is provided in the `@layer` at-rule or `@import` with `layer()`, a new anonymous (unnamed) layer is created.
**Note:** The order of precedence of layers is the order in which they are created. Styles not in a layer, or "unlayered styles", cascade together into a final implicit label.
Let's cover the three ways of creating a layer in a little more detail before discussing nested layers.
### The @layer statement at-rule for named layers
The order of layers is set by the order in which the layers appear in your CSS. Declaring layers using `@layer` followed by the names of one or more layers without assigning any styles is one way to define the layer order.
The `@layer` CSS at-rule is used to declare a cascade layer and to define the order of precedence when there are multiple cascade layers. The following at-rule declares three layers, in the order listed:
```css
@layer theme, layout, utilities;
```
You will often want to have your first line of CSS be this `@layer` declaration (with layer names that make sense for your site, of course) to have full control over layer ordering.
If the above statement is the first line of a site's CSS, the layer order will be `theme`, `layout`, and `utilities`. If some layers were created prior to the above statement, as long as layers with these names don't already exist, these three layers will be created and added to the end of the list of existing layers. However, if a layer with the same name already exists, then the above statement will create only two new layers. For example, if `layout` already existed, only `theme` and `utilities` will be created, but the order of layers, in this case, will be `layout`, `theme`, and `utilities`.
### The @layer block at-rule for named and anonymous layers
Layers can be created using the block `@layer` at-rule. If an `@layer` at-rule is followed by an identifier and a block of styles, the identifier is used to name the layer, and the styles in this at-rule are added to the layer's styles. If a layer with the specified name does not already exist, a new layer will be created. If a layer with the specified name already exists, the styles are added to the previously existing layer. If no name is specified while creating a block of styles using `@layer`, the styles in the at-rule will be added to a new anonymous layer.
In the example below, we've used four block and one inline `@layer` at-rules. This CSS does the following in the order listed:
1. Creates a named `layout` layer
2. Creates an unnamed, anonymous layer
3. Declares a list of three layers and creates only two new layers, `theme` and `utilities`, because `layout` already exists
4. Adds additional styles to the already existing `layout` layer
5. Creates a second unnamed, anonymous layer
```css
/\* file: layers1.css \*/
/\* unlayered styles \*/
body {
color: #333;
}
/\* creates the first layer: `layout` \*/
@layer layout {
main {
display: grid;
}
}
/\* creates the second layer: an unnamed, anonymous layer \*/
@layer {
body {
margin: 0;
}
}
/\* creates the third and fourth layers: `theme` and `utilities` \*/
@layer theme, layout, utilities;
/\* adds styles to the already existing `layout` layer \*/
@layer layout {
main {
color: #000;
}
}
/\* creates the fifth layer: an unnamed, anonymous layer \*/
@layer {
body {
margin: 1vw;
}
}
```
In the above CSS, we created five layers: `layout`, `<anonymous(01)>`, `theme`, `utilities`, and `<anonymous(02)>` β in that order - with a sixth, implicit layer of unlayered styles contained in the `body` style block. The layer order is the order in which the layers are created, with the implicit layer of unlayered styles always being last. There is no way to change the layer order once created.
We assigned some styles to the layer named `layout`. If a named layer doesn't already exist, then specifying the name in an `@layer` at-rule, with or without assigning styles to the layer, creates the layer; this adds the layer to the end of the series of existing layer names. If the named layer already exists, all styles within the named block get appended to styles in the previously existing layer β specifying styles in a block by reusing an existing layer name does not create a new layer.
Anonymous layers are created by assigning styles to a layer without naming the layer. Styles can be added to an unnamed layer only at the time of its creation.
**Note:** Subsequent use of `@layer` with no layer name creates additional unnamed layers; it does not append styles to a previously existing unnamed layer.
The `@layer` at-rule creates a layer, named or not, or appends styles to a layer if the named layer already exists. We called the first anonymous layer `<anonymous(01)>` and the second `<anonymous(02)>`, this is just so we can explain them. These are actually unnamed layers. There is no way to reference them or add additional styles to them.
All styles declared outside of a layer are joined together in an implicit layer. In the example code above, the first declaration set the `color: #333` property on `body`. This was declared outside of any layer. Normal unlayered declarations take precedence over normal layered declarations even if the unlayered styles have a lower specificity and come first in the order of appearance. This explains why even though the unlayered CSS was declared first in the code block, the implicit layer containing these unlayered styles takes precedence as if it was the last declared layer.
In the line `@layer theme, layout, utilities;`, in which a series of layers were declared, only the `theme` and `utilities` layers were created; `layout` was already created in the first line. Note that this declaration does not change the order of already created layers. There is currently no way to re-order layers once declared.
In the following interactive example, we assign styles to two layers, creating them and naming them in the process. Because they already exist, being created when first used, declaring them on the last line does nothing.
Try moving the last line, `@layer site, page;`, to make it the first line. What happens?
#### Layer creation and media queries
If you define a layer using media or feature queries, and the media is not a match or the feature is not supported, the layer is not created. The example below shows how changing the size of your device or browser may change the layer order. In this example, we create the `site` layer only in wider browsers. We then assign styles to the `page` and `site` layers, in that order.
In wide screens, the `site` layer is declared in the first line, meaning `site` has less precedence than `page`. Otherwise, `site` has precedence over `page` because it is declared later on narrow screens. If that doesn't work, try changing the `50em` in the media query to `10em` or `100em`.
### Importing style sheets into named and anonymous layers with @import
The `@import` rule allows users to import style rules from other style sheets either directly into a CSS file or into a `<style>` element.
When importing stylesheets, the `@import` statement must be defined before any CSS styles within the stylesheet or `<style>` block. The `@import` statement must come first, before any styles, but can be preceded by an `@layer` at-rule that creates one or more layers without assigning any styles to the layers. (`@import` can also be preceded by an `@charset` rule.)
You can import a stylesheet into a named layer, a nested named layer, or an anonymous layer. The following layer imports the style sheets into a `components` layer, a nested `dialog` layer within the `components` layer, and an un-named layer, respectively:
```css
@import url("components-lib.css") layer(components);
@import url("dialog.css") layer(components.dialog);
@import url("marketing.css") layer();
```
You can import more than one CSS file into a single layer. The following declaration imports two separate files into a single `social` layer:
```css
@import url(comments.css) layer(social);
@import url(sm-icons.css) layer(social);
```
You can import styles and create layers based on specific conditions using media queries and feature queries. The following imports a style sheet into an `international` layer only if the browser supports `display: ruby`, and the file being imported is dependent on the width of the screen.
```css
@import url("ruby-narrow.css") layer(international) supports(display: ruby) and
(width < 32rem);
@import url("ruby-wide.css") layer(international) supports(display: ruby) and
(width >= 32rem);
```
**Note:** There is no equivalent of the `<link>` method of linking stylesheets. Use `@import` to import a stylesheet into a layer when you can't use `@layer` within the stylesheet.
Overview of nested cascade layers
---------------------------------
Nested layers are layers within a named or an anonymous layer. Each cascade layer, even an anonymous one, can contain nested layers. Layers imported into another layer become nested layers within that layer.
### Advantages of nesting layers
The ability to nest layers enables teams to create cascade layers without worrying about whether other teams will import them into a layer. Similarly, nesting enables you to import third-party style sheets into a layer without worrying if that style sheet itself has layers. Because layers can be nested, you don't have to worry about having conflicting layer names between external and internal style sheets.
### Creating nested cascade layers
Nested layers can be created using the same methods as described for regular layers. For example, they can be created using `@layer` at-rule followed by the names of one or more layers, using a dot notation. Multiple dots and layer names signify multiple nesting.
If you nest a block `@layer` at-rule inside another block `@layer` at-rule, with or without a name, the nested block becomes a nested layer. Similarly, when a style sheet is imported with an `@import` declaration containing the `layer` keyword or `layer()` function, the styles get assigned to that named or anonymous layer. If the `@import` statement contains layers, those layers become nested layers within that anonymous or named layer.
Let's look at the following example:
```css
@import url("components-lib.css") layer(components);
@import url("narrowtheme.css") layer(components.narrow);
```
In the first line, we import `components-lib.css` into the `components` layer. If that file contains any layers, named or not, those layers become nested layers within the `components` layer.
The second line imports `narrowtheme.css` into the `narrow` layer, which is a sub-layer of `components`. The nested `components.narrow` gets created as the last layer within the `components` layer, unless `components-lib.css` already contains a `narrow` layer, in which case, the contents of `narrowtheme.css` would be appended to the `components.narrow` nested layer. Additional nested named layers can be added to the `components` layer using the pattern `components.<layerName>`. As mentioned before, unnamed layers can be created but they cannot be accessed subsequently.
Let's look at another example, where we import `layers1.css` into a named layer using the following statement:
```css
@import url(layers1.css) layer(example);
```
This will create a single layer named `example` containing some declarations and five nested layers - `example.layout`, `example.<anonymous(01)>`, `example.theme`, `example.utilities`, and `example.<anonymous(02)>`.
To add styles to a named nested layer, use the dot notation:
```css
@layer example.layout {
main {
width: 50vw;
}
}
```
Determining the precedence based on the order of layers
-------------------------------------------------------
The order of layers determines their order of precedence. Therefore, the order of layers is very important. In the same way as the cascade sorts by origin and importance, the cascade sorts each CSS declaration by origin layer and importance.
### Precedence order of regular cascade layers
```css
@import url(A.css) layer(firstLayer);
@import url(B.css) layer(secondLayer);
@import url(C.css);
```
The above code creates two named layers (C.css styles get appended to the implicit layer of unlayered styles). Let us assume that the three files (`A.css`, `B.css`, and `C.css`) do not contain any additional layers within them. The following list shows where styles declared inside and outside of these files will be sorted from least (1) precedence to highest (10).
1. `firstLayer` normal styles (`A.css`)
2. `secondLayer` normal styles (`B.css`)
3. unlayered normal styles (`C.css`)
4. inline normal styles
5. animating styles
6. unlayered important styles (`C.css`)
7. `secondLayer` important styles (`B.css`)
8. `firstLayer` important styles (`A.css`)
9. inline important styles
10. transitioning styles
Normal styles declared inside layers receive the lowest priority and are sorted by the order in which the layers were created. Normal styles in the first created layer have the lowest precedence, and normal styles in the layer created last have the highest precedence among the layers. In other words, normal styles declared within `firstLayer` will be overridden by any subsequent stylings on the list if any conflicts exist.
Next up are any styles declared outside of layers. The styles in `C.css` were not imported into a layer and will override any conflicting styles from `firstLayer` and `secondLayer`. Styles not declared in a layer always have higher precedence than styles that *are* declared inside a layer (with the exception of important styles).
Inline styles are declared using the `style` attribute. Normal styles declared in this way will take precedence over normal styles found in the unlayered and layered style sheets (`firstLayer β A.css`, `secondLayer β B.css`, and `C.css`).
Animating styles have higher precedence than all normal styles, including inline normal styles.
Important styles, that is, property values that include the `!important` flag, take precedence over any styles previously mentioned in our list. They are sorted in reverse order of normal styles. Any important styles declared outside of a layer have less precedence than those declared within a layer. Important styles found within layers are also sorted in order of layer creation. For important styles, the last created layer has the lowest precedence, and the first created layer has the highest precedence among declared layers.
Inline important styles again have higher precedence than important styles declared elsewhere.
Transitioning styles have the highest precedence. When a normal property value is being transitioned, it takes precedence over all other property value declarations, even inline important styles; but only while transitioning.
In this example, there are two inline layers `A` and `B` without styles, a block of unlayered styles, and two blocks of styles in named layers `A` and `B`.
The inline styles added on the `h1` element using the `style` attribute, set a normal `color` and an important `background-color`. Normal inline styles override all layered and unlayered normal styles. Important inline styles override all layered and unlayered normal and important author styles. There is no way for author styles to override important inline styles.
The normal `text-decoration` and important `box-shadow` are not part of the `style` inline styles and can therefore be overridden. For normal non-inline styles, unlayered styles have precedence. For important styles, layer order matters too. While normal unlayered styles override all normal styles set in a layer, with important styles, the precedence order is reversed; unlayered important styles have lower precedence than layered styles.
The two styles declared only within layers are `font-style`, with normal importance, and `font-weight` with an `!important` flag. For normal styles, the `B` layer, declared last, overrides styles in the earlier declared layer `A`. For normal styles, later layers have precedence over earlier layers. The order of precedence is reversed for important styles. For the important `font-weight` declarations, layer `A`, being declared first, has precedence over the last declared layer `B`.
You can reverse the layer order by changing the first line from `@layer A, B;` to `@layer B, A;`. Try that. Which styles get changed by this, and which stay the same? Why?
The order of layers is set by the order in which the layers appear in your CSS. In our first line, we declared layers without assigning any styles using `@layer` followed by the names of our layers, ending with a semi-colon. Had we omitted this line, the results would have been the same. Why? We assigned style rules in named `@layer` blocks in the order A then B. The two layers were created in that first line. Had they not been, these rule blocks would have created them, in that order.
We included that first line for two reasons: first so you could easily edit the line and switch the order, and second because often you'll find declaring the order layer up front to be the best practice for your layer order management.
To summarize:
* The order of precedence of layers is the order in which the layers are created.
* Once created, there is no way to change the layer order.
* Layer precedence for normal styles is the order in which the layers are created.
* Unlayered normal styles have precedence over normal layered styles.
* Layer precedence for important styles is reversed, with earlier created layers having precedence.
* All layered important styles have precedence over unlayered important (and normal) styles.
* Normal inline styles take precedence over all normal styles, layered or not.
* Important inline styles take precedence over all other styles, with the exception of styles being transitioned.
* There is no way for author styles to override important inline styles (other than transitioning them, which is temporary).
### Precedence order of nested cascade layers
The cascade precedence order for nested layers is similar to that of regular layers, but contained within the layer. The precedence order is based on the order of nested layer creation. Non-nested styles in a layer have precedence over nested normal styles, with the precedence order reversed for important styles. Specificity weight between nested layers does not matter, though it does matter for conflicting styles within a nested layer.
The following creates and adds styles to the `components` layer and `components.narrow` nested layer and creates and appends styles to a new `components.wide` layer:
```css
@import url("components-lib.css") layer(components);
@import url("narrowtheme.css") layer(components.narrow);
@layer components {
:root {
--theme: red;
font-family: serif !important;
}
}
@layer components.narrow {
:root {
--theme: blue;
font-family: sans-serif !important;
}
}
@layer components.wide {
:root {
--theme: purple;
font-family: cursive !important;
}
}
```
Because unlayered normal styles have precedence over layered normal styles, and within a layer, non-nested styles have precedence over normal nested styles, `red` wins over the other `theme` colors.
With important styles, layered styles take precedence over unlayered styles, with important styles in earlier declared layers having precedence over later declared layers. In this example, the order of nested layer creation is `components.narrow`, then `components.wide`, so important styles in `components.narrow` have precedence over important styles in `components.wide`, meaning `sans-serif` wins.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: The Cascade, Task 2.
Summary
-------
If you understood most of this article, then well done β you're now familiar with the fundamental mechanics of CSS cascade layers. Next up, we'll look at the box model in detail.
* Previous
* Overview: Building blocks
* Next |
Sizing items in CSS - Learn web development | Sizing items in CSS
===================
* Previous
* Overview: Building blocks
* Next
In the various lessons so far, you have come across a number of ways to size items on a web page using CSS. Understanding how big the different features in your design will be is important. So, in this lesson we will summarize the various ways elements get a size via CSS and define a few terms about sizing that will help you in the future.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: | To understand the different ways we can size things in CSS. |
The natural or intrinsic size of things
---------------------------------------
HTML Elements have a natural size, set before they are affected by any CSS. A straightforward example is an image. An image file contains sizing information, described as its **intrinsic size**. This size is determined by the image *itself*, not by any formatting we happen to apply.
If you place an image on a page and do not change its height or width, either by using attributes on the `<img>` tag or else by CSS, it will be displayed using that intrinsic size. We have given the image in the example below a border so that you can see the extent of its size as defined in its file.
An empty `<div>`, on the other hand, has no size of its own. If you add a `<div>` to your HTML with no content, then give it a border as we did with the image, you will see a line on the page. This is the collapsed border on the element β there is no content to hold it open. In our example below, that border stretches to the width of the container, because it is a block level element, a behavior that should be starting to become familiar to you. It has no height (or size in the block dimension) because there is no content.
In the example above, try adding some text inside the empty element. The border now contains that text because the height of the element is defined by the content. Therefore the size of this `<div>` in the block dimension comes from the size of the content. Again, this is the intrinsic size of the element β its size is defined by its content.
Setting a specific size
-----------------------
We can, of course, give elements in our design a specific size. When a size is given to an element (the content of which then needs to fit into that size) we refer to it as an **extrinsic size**. Take our `<div>` from the example above β we can give it specific `width` and `height` values, and it will now have that size no matter what content is placed into it. As we discovered in our previous lesson on overflow, a set height can cause content to overflow if there is more content than the element has space to fit inside it.
Due to this problem of overflow, fixing the height of elements with lengths or percentages is something we need to do very carefully on the web.
### Using percentages
In many ways, percentages act like length units, and as we discussed in the lesson on values and units, they can often be used interchangeably with lengths. When using a percentage you need to be aware what it is a percentage *of*. In the case of a box inside another container, if you give the child box a percentage width it will be a percentage of the width of the parent container.
This is because percentages resolve against the size of the containing block. With no percentage applied, our `<div>` would take up 100% of the available space, as it is a block level element. If we give it a percentage width, this becomes a percentage of the space it would normally fill.
### Percentage margins and padding
If you set `margins` and `padding` as a percentage, you may notice some strange behavior. In the below example we have a box. We have given the inner box a `margin` of 10% and a `padding` of 10%. The padding and margin on the top and bottom of the box are the same size as the padding and margin on the left and right.
You might expect for example the percentage top and bottom margins to be a percentage of the element's height, and the percentage left and right margins to be a percentage of the element's width. However, this is not the case!
When you use margin and padding set in percentages, the value is calculated from the **inline size** of the containing block β therefore the width when working in a horizontal language. In our example, all of the margins and padding are 10% of the width. This means you can have equal-sized margins and padding all around the box. This is a fact worth remembering if you do use percentages in this way.
min- and max- sizes
-------------------
In addition to giving things a fixed size, we can ask CSS to give an element a minimum or a maximum size. If you have a box that might contain a variable amount of content, and you always want it to be *at least* a certain height, you could set the `min-height` property on it. The box will always be at least this height, but will then grow taller if there is more content than the box has space for at its minimum height.
In the example below you can see two boxes, both with a defined `min-height` of 150 pixels. The box on the left is 150 pixels tall; the box on the right has content that needs more room, and so it has grown taller than 150 pixels.
This is very useful for dealing with variable amounts of content while avoiding overflow.
A common use of `max-width` is to cause images to scale down if there is not enough space to display them at their intrinsic width while making sure they don't become larger than that width.
As an example, if you were to set `width: 100%` on an image, and its intrinsic width was smaller than its container, the image would be forced to stretch and become larger, causing it to look pixelated.
If you instead use `max-width: 100%`, and its intrinsic width is smaller than its container, the image will not be forced to stretch and become larger, thus preventing pixelation.
In the example below, we have used the same image three times. The first image has been given `width: 100%` and is in a container which is larger than it, therefore it stretches to the container width. The second image has `max-width: 100%` set on it and therefore does not stretch to fill the container. The third box contains the same image again, also with `max-width: 100%` set; in this case you can see how it has scaled down to fit into the box.
This technique is used to make images *responsive*, so that when viewed on a smaller device they scale down appropriately. You should, however, not use this technique to load really large images and then scale them down in the browser. Images should be appropriately sized to be no larger than they need to be for the largest size they are displayed in the design. Downloading overly large images will cause your site to become slow, and it can cost users more money if they are on a metered connection.
**Note:** Find out more about responsive image techniques.
Viewport units
--------------
The viewport β which is the visible area of your page in the browser you are using to view a site β also has a size. In CSS we have units which relate to the size of the viewport β the `vw` unit for viewport width, and `vh` for viewport height. Using these units you can size something relative to the viewport of the user.
`1vh` is equal to 1% of the viewport height, and `1vw` is equal to 1% of the viewport width. You can use these units to size boxes, but also text. In the example below we have a box which is sized as 20vh and 20vw. The box contains a letter `A`, which has been given a `font-size` of 10vh.
**If you change the `vh` and `vw` values this will change the size of the box or font; changing the viewport size will also change their sizes because they are sized relative to the viewport. To see the example change when you change the viewport size you will need to load the example in a new browser window that you can resize (as the embedded `<iframe>` that contains the example shown above is its viewport). Open the example, resize the browser window, and observe what happens to the size of the box and text.**
Sizing things according to the viewport can be useful in your designs. For example, if you want a full-page hero section to show before the rest of your content, making that part of your page 100vh high will push the rest of the content below the viewport, meaning that it will only appear once the document is scrolled.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Sizing.
Summary
-------
This lesson has given you a rundown of some key issues that you might run into when sizing things on the web. When you move onto CSS Layout, sizing will become very important in mastering the different layout methods, so it is worth understanding the concepts here before moving on.
In the next article, we'll take a look at how images, media, and form elements are treated in CSS.
* Previous
* Overview: Building blocks
* Next |
Pseudo-classes and pseudo-elements - Learn web development | Pseudo-classes and pseudo-elements
==================================
* Previous
* Overview: Building blocks
* Next
The next set of selectors we will look at are referred to as **pseudo-classes** and **pseudo-elements**. There are a large number of these, and they often serve quite specific purposes. Once you know how to use them, you can look at the list to see if there is something which works for the task you are trying to achieve. Once again the relevant MDN page for each selector is helpful in explaining browser support.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps).
|
| Objective: | To learn about the pseudo-class and pseudo-element selectors. |
What is a pseudo-class?
-----------------------
A pseudo-class is a selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer. They tend to act as if you had applied a class to some part of your document, often helping you cut down on excess classes in your markup, and giving you more flexible, maintainable code.
Pseudo-classes are keywords that start with a colon. For example, `:hover` is a pseudo-class.
### Simple pseudo-class example
Let's look at a simple example. If we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add CSS to that class, as shown in the first example below:
However, this could be annoying to maintain β what if a new paragraph got added to the top of the document? We'd need to move the class over to the new paragraph. Instead of adding the class, we could use the `:first-child` pseudo-class selector β this will *always* target the first child element in the article, and we will no longer need to edit the HTML (this may not always be possible anyway, maybe due to it being generated by a CMS).
All pseudo-classes behave in this same kind of way. They target some bit of your document that is in a certain state, behaving as if you had added a class into your HTML. Take a look at some other examples on MDN:
* `:last-child`
* `:only-child`
* `:invalid`
**Note:** It is valid to write pseudo-classes and elements without any element selector preceding them. In the example above, you could write `:first-child` and the rule would apply to *any* element that is the first child of an `<article>` element, not just a paragraph first child β `:first-child` is equivalent to `*:first-child`. However, usually you want more control than that, so you need to be more specific.
### User-action pseudo classes
Some pseudo-classes only apply when the user interacts with the document in some way. These **user-action** pseudo-classes, sometimes referred to as **dynamic pseudo-classes**, act as if a class had been added to the element when the user interacts with it. Examples include:
* `:hover` β mentioned above; this only applies if the user moves their pointer over an element, typically a link.
* `:focus` β only applies if the user focuses the element by clicking or using keyboard controls.
What is a pseudo-element?
-------------------------
Pseudo-elements behave in a similar way. However, they act as if you had added a whole new HTML element into the markup, rather than applying a class to existing elements.
Pseudo-elements start with a double colon `::`. `::before` is an example of a pseudo-element.
**Note:** Some early pseudo-elements used the single colon syntax, so you may sometimes see this in code or examples. Modern browsers support the early pseudo-elements with single- or double-colon syntax for backwards compatibility.
For example, if you wanted to select the first line of a paragraph you could wrap it in a `<span>` element and use an element selector; however, that would fail if the number of words you had wrapped were longer or shorter than the parent element's width. As we tend not to know how many words will fit on a line β as that will change if the screen width or font-size changes β it is impossible to robustly do this by adding HTML.
The `::first-line` pseudo-element selector will do this for you reliably β if the number of words increases or decreases it will still only select the first line.
It acts as if a `<span>` was magically wrapped around that first formatted line, and updated each time the line length changed.
You can see that this selects the first line of both paragraphs.
Combining pseudo-classes and pseudo-elements
--------------------------------------------
If you wanted to make the first line of the first paragraph bold you could chain the `:first-child` and `::first-line` selectors together. Try editing the previous live example so it uses the following CSS. We are saying that we want to select the first line, of the first `<p>` element, which is inside an `<article>` element.
```css
article p:first-child::first-line {
font-size: 120%;
font-weight: bold;
}
```
Generating content with ::before and ::after
--------------------------------------------
There are a couple of special pseudo-elements, which are used along with the `content` property to insert content into your document using CSS.
You could use these to insert a string of text, such as in the live example below. Try changing the text value of the `content` property and see it change in the output. You could also change the `::before` pseudo-element to `::after` and see the text inserted at the end of the element instead of the beginning.
Inserting strings of text from CSS isn't really something we do very often on the web however, as that text is inaccessible to some screen readers and might be hard for someone to find and edit in the future.
A more valid use of these pseudo-elements is to insert an icon, for example the little arrow added in the example below, which is a visual indicator that we wouldn't want read out by a screen reader:
These pseudo-elements are also frequently used to insert an empty string, which can then be styled just like any element on the page.
In this next example, we have added an empty string using the `::before` pseudo-element. We have set this to `display: block` in order that we can style it with a width and height. We then use CSS to style it just like any element. You can play around with the CSS and change how it looks and behaves.
The use of the `::before` and `::after` pseudo-elements along with the `content` property is referred to as "Generated Content" in CSS, and you will often see this technique being used for various tasks. A great example is the site CSS Arrow Please, which helps you to generate an arrow with CSS. Look at the CSS as you create your arrow and you will see the `::before` and `::after` pseudo-elements in use. Whenever you see these selectors, look at the `content` property to see what is being added to the HTML element.
Summary
-------
In this article we've introduced CSS pseudo-classes and pseudo-elements, which are special types of selectors.
Pseudo-classes enable you to target an element when it's in a particular state, as if you had added a class for that state to the DOM. Pseudo-elements act as if you had added a whole new element to the DOM, and enable you to style that. The `::before` and `::after` pseudo-elements enable you to insert content into the document using CSS.
In the next article, we'll learn about combinators.
See also
--------
* Pseudo-classes reference
* Pseudo-elements reference
* Previous
* Overview: Building blocks
* Next |
Type, class, and ID selectors - Learn web development | Type, class, and ID selectors
=============================
* Previous
* Overview: Building blocks
* Next
In this lesson, we examine some of the simplest selectors, which you will probably use most frequently in your work.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: |
To learn about the different CSS selectors we can use to apply CSS to a
document.
|
Type selectors
--------------
A **type selector** is sometimes referred to as a *tag name selector* or *element selector* because it selects an HTML tag/element in your document. Type selectors are not case-sensitive. In the example below, we have used the `span`, `em` and `strong` selectors.
**Try adding a CSS rule to select the `<h1>` element and change its color to blue.**
The universal selector
----------------------
The universal selector is indicated by an asterisk (`*`). It selects everything in the document (or inside the parent element if it is being chained together with another element and a descendant combinator). In the following example, we use the universal selector to remove the margins on all elements. Instead of the default styling added by the browser β which spaces out headings and paragraphs with margins β everything is close together.
This kind of behavior can sometimes be seen in "reset stylesheets", which strip out all of the browser styling. Since the universal selector makes global changes, we use it for very specific situations, such as the one described below.
### Using the universal selector to make your selectors easier to read
One use of the universal selector is to make selectors easier to read and more obvious in terms of what they are doing. For example, if we wanted to select any descendant elements of an `<article>` element that are the first child of their parent, including direct children, and make them bold, we could use the `:first-child` pseudo-class. We will learn more about this in the lesson on pseudo-classes and pseudo-elements, as a descendant selector along with the `<article>` element selector:
```css
article :first-child {
font-weight: bold;
}
```
However, this selector could be confused with `article:first-child`, which will select any `<article>` element that is the first child of another element.
To avoid this confusion, we can add the universal selector to the `:first-child` pseudo-class, so it is more obvious what the selector is doing. It is selecting *any* element which is the first-child of an `<article>` element, or the first-child of any descendant element of `<article>`:
```css
article \*:first-child {
font-weight: bold;
}
```
Although both do the same thing, the readability is significantly improved.
Class selectors
---------------
The case-sensitive class selector starts with a dot (`.`) character. It will select everything in the document with that class applied to it. In the live example below we have created a class called `highlight`, and have applied it to several places in my document. All of the elements that have the class applied are highlighted.
### Targeting classes on particular elements
You can create a selector that will target specific elements with the class applied. In this next example, we will highlight a `<span>` with a class of `highlight` differently to an `<h1>` heading with a class of `highlight`. We do this by using the type selector for the element we want to target, with the class appended using a dot, with no white space in between.
This approach reduces the scope of a rule. The rule will only apply to that particular element and class combination. You would need to add another selector if you decided the rule should apply to other elements too.
### Target an element if it has more than one class applied
You can apply multiple classes to an element and target them individually, or only select the element when all of the classes in the selector are present. This can be helpful when building up components that can be combined in different ways on your site.
In the example below, we have a `<div>` that contains a note. The grey border is applied when the box has a class of `notebox`. If it also has a class of `warning` or `danger`, we change the `border-color`.
We can tell the browser that we only want to match the element if it has two classes applied by chaining them together with no white space between them. You'll see that the last `<div>` doesn't get any styling applied, as it only has the `danger` class; it needs `notebox` as well to get anything applied.
ID selectors
------------
The case-sensitive ID selector begins with a `#` rather than a dot character, but is used in the same way as a class selector. However, an ID can be used only once per page, and elements can only have a single `id` value applied to them. It can select an element that has the `id` set on it, and you can precede the ID with a type selector to only target the element if both the element and ID match. You can see both of these uses in the following example:
**Warning:** Using the same ID multiple times in a document may appear to work for styling purposes, but don't do this. It results in invalid code, and will cause strange behavior in many places.
**Note:** The ID selector has high `specificity`. This means styles applied based on matching an ID selector will overrule styles applied based on other selector, including class and type selectors. Because an ID can only occur once on a page and because of the high specificity of ID selectors, it is preferable to add a class to an element instead of an ID. If using the ID is the only way to target the element β perhaps because you do not have access to the markup and cannot edit it β consider using the ID within an attribute selector, such as `p[id="header"]`. Learn specificity.
Summary
-------
That wraps up Type, class, and ID selectors. We'll continue exploring selectors by looking at attribute selectors.
* Previous
* Overview: Building blocks
* Next |
Combinators - Learn web development | Combinators
===========
* Previous
* Overview: Building blocks
* Next
The final selectors we will look at are called combinators, because they combine other selectors in a way that gives them a useful relationship to each other and the location of content in the document.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: |
To learn about the different combinator selectors that can be used in
CSS.
|
Descendant combinator
---------------------
The **descendant combinator** β typically represented by a single space (" ") character β combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc.) element matching the first selector. Selectors that utilize a descendant combinator are called *descendant selectors*.
```css
body article p
```
In the example below, we are matching only the `<p>` element which is inside an element with a class of `.box`.
Child combinator
----------------
The **child combinator** (`>`) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Descendant elements further down the hierarchy don't match. For example, to select only `<p>` elements that are direct children of `<article>` elements:
```css
article > p
```
In this next example, we have an unordered list, nested inside of which is an ordered list. The child combinator selects only those `<li>` elements which are direct children of a `<ul>`, and styles them with a top border.
If you remove the `>` that designates this as a child combinator, you end up with a descendant selector and all `<li>` elements will get a red border.
Next-sibling combinator
-----------------------
The **next-sibling combinator** (`+`) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the next sibling element of the first selector. For example, to select all `<img>` elements that are immediately preceded by a `<p>` element:
```css
p + img
```
A common use case is to do something with a paragraph that follows a heading, as in the example below. In that example, we are looking for any paragraph which shares a parent element with an `<h1>`, and immediately follows that `<h1>`.
If you insert some other element such as a `<h2>` in between the `<h1>` and the `<p>`, you will find that the paragraph is no longer matched by the selector and so does not get the background and foreground color applied when the element is adjacent.
Subsequent-sibling combinator
-----------------------------
If you want to select siblings of an element even if they are not directly adjacent, then you can use the **subsequent-sibling combinator** (`~`). To select all `<img>` elements that come *anywhere* after `<p>` elements, we'd do this:
```css
p ~ img
```
In the example below we are selecting all `<p>` elements that come after the `<h1>`, and even though there is a `<div>` in the document as well, the `<p>` that comes after it is selected.
Creating complex selectors with nesting
---------------------------------------
The CSS nesting module allows you to write nested rules that use combinators to create complex selectors.
```css
p {
~ img {
}
}
/\* This is parsed by the browser as \*/
p ~ img {
}
```
The `&` nesting selector can also be used to create complex selectors.
```css
p {
& img {
}
}
/\* This is parsed by the browser as \*/
p img {
}
```
**Note:** In the example above, the `&` nesting selector is not required, but adding it helps to explicitly show that CSS nesting is being used.
Using combinators
-----------------
You can combine any of the selectors that we discovered in previous lessons with combinators in order to pick out part of your document. For example, to select list items with a class of "a" which are direct children of a `<ul>`, try the following:
```css
ul > li[class="a"] {
}
```
Take care, however, when creating big lists of selectors that select very specific parts of your document. It will be hard to reuse the CSS rules since you have made the selector very specific to the location of that element in the markup.
It is often better to create a simple class and apply that to the element in question. That said, your knowledge of combinators will be very useful if you need to style something in your document and are unable to access the HTML, perhaps due to it being generated by a CMS.
Test your skills!
-----------------
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on β see Test your skills: Selectors.
Summary
-------
This is the last section in our lessons on selectors. Next, we'll move on to another important part of CSS β the cascade, specificity, and inheritance.
* Previous
* Overview: Building blocks
* Next |
Test your skills: Selectors - Learn web development | Test your skills: Selectors
===========================
The aim of this skill test is to assess whether you understand CSS selectors.
**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our communication channels.
Task 1
------
In this task, use CSS to do the following things, without changing the HTML:
* Make `<h1>` headings blue.
* Give `<h2>` headings a blue background and white text.
* Cause text wrapped in a `<span>` to have a font-size of 200%.
Your final result should look like the image below:
![Text with the CSS applied for the solution to task 1.](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Selectors_Tasks/selectors1.jpg)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 2
------
In this task, we want you to make the following changes to the look of the content in this example, without changing the HTML:
* Give the element with an id of `special` a yellow background.
* Give the element with a class of `alert` a 1px grey border.
* If the element with a class of `alert` also has a class of `stop`, make the background red.
* If the element with a class of `alert` also has a class of `go`, make the background green.
Your final result should look like the image below:
![Text with the CSS applied for the solution to task 2.](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Selectors_Tasks/selectors2.jpg)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 3
------
In this task, we want you to make the following changes without adding to the HTML:
* Style links, making the link-state orange, visited links green, and remove the underline on hover.
* Make the first element inside the container font-size: 150% and the first line of that element red.
* Stripe every other row in the table by selecting these rows and giving them a background color of #333 and foreground of white.
Your final result should look like the image below:
![Text with the CSS applied for the solution to task 3.](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Selectors_Tasks/selectors3.jpg)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 4
------
In this task, we want you to do the following:
* Make any paragraph that directly follows an `<h2>` element red.
* Remove the bullets and add a 1px grey bottom border only to list items that are a direct child of the ul with a class of `list`.
Your final result should look like the image below:
![Text with the CSS applied for the solution to task 4.](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Selectors_Tasks/selectors4.jpg)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
Task 5
------
In this task, add CSS using attribute selectors to do the following:
* Target the `<a>` element with a `title` attribute and make the border pink (`border-color: pink`).
* Target the `<a>` element with an `href` attribute that contains the word `contact` somewhere in its value and make the border orange (`border-color: orange`).
* Target the `<a>` element with an `href` value starting with `https` and give it a green border (`border-color: green`).
Your final result should look like the image below:
![Four links with different color borders.](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Selectors_Tasks/selectors-attribute.png)
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor. |
Attribute selectors - Learn web development | Attribute selectors
===================
* Previous
* Overview: Building blocks
* Next
As you know from your study of HTML, elements can have attributes that give further detail about the element being marked up. In CSS you can use attribute selectors to target elements with certain attributes. This lesson will show you how to use these very useful selectors.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, HTML basics (study
Introduction to HTML), and an idea of how CSS works (study
CSS first steps.)
|
| Objective: | To learn what attribute selectors are and how to use them. |
Presence and value selectors
----------------------------
These selectors enable the selection of an element based on the presence of an attribute alone (for example `href`), or on various different matches against the value of the attribute.
| Selector | Example | Description |
| --- | --- | --- |
| `[*attr*]` | `a[title]` |
Matches elements with an *attr* attribute (whose name is the
value in square brackets).
|
| `[*attr*=*value*]` | `a[href="https://example.com"]` |
Matches elements with an *attr* attribute whose value is exactly
*value* β the string inside the quotes.
|
| `[*attr*~=*value*]` | `p[class~="special"]` |
Matches elements with an *attr* attribute whose value is
exactly *value*, or contains *value* in its (space
separated) list of values.
|
| `[*attr*|=*value*]` | `div[lang|="zh"]` |
Matches elements with an *attr* attribute whose value is exactly
*value* or begins with *value* immediately followed by a
hyphen.
|
In the example below you can see these selectors being used.
* By using `li[class]` we can match any list item with a class attribute. This matches all of the list items except the first one.
* `li[class="a"]` matches a selector with a class of `a`, but not a selector with a class of `a` with another space-separated class as part of the value. It selects the second list item.
* `li[class~="a"]` will match a class of `a` but also a value that contains the class of `a` as part of a whitespace-separated list. It selects the second and third list items.
Substring matching selectors
----------------------------
These selectors allow for more advanced matching of substrings inside the value of your attribute. For example, if you had classes of `box-warning` and `box-error` and wanted to match everything that started with the string "box-", you could use `[class^="box-"]` to select them both (or `[class|="box"]` as described in section above).
| Selector | Example | Description |
| --- | --- | --- |
| `[attr^=value]` | `li[class^="box-"]` | Matches elements with an *attr* attribute, whose value begins with *value*. |
| `[attr$=value]` | `li[class$="-box"]` | Matches elements with an *attr* attribute whose value ends with *value*. |
| `[attr*=value]` | `li[class*="box"]` | Matches elements with an *attr* attribute whose value contains *value* anywhere within the string. |
(Aside: It may help to note that `^` and `$` have long been used as *anchors* in so-called *regular expressions* to mean *begins with* and *ends with* respectively.)
The next example shows usage of these selectors:
* `li[class^="a"]` matches any attribute value which starts with `a`, so matches the first two list items.
* `li[class$="a"]` matches any attribute value that ends with `a`, so matches the first and third list item.
* `li[class*="a"]` matches any attribute value where `a` appears anywhere in the string, so it matches all of our list items.
Case-sensitivity
----------------
If you want to match attribute values case-insensitively you can use the value `i` before the closing bracket. This flag tells the browser to match ASCII characters case-insensitively. Without the flag the values will be matched according to the case-sensitivity of the document language β in HTML's case it will be case sensitive.
In the example below, the first selector will match a value that begins with `a` β it only matches the first list item because the other two list items start with an uppercase A. The second selector uses the case-insensitive flag and so matches all of the list items.
**Note:** There is also a newer value `s`, which will force case-sensitive matching in contexts where matching is normally case-insensitive, however this is less well supported in browsers and isn't very useful in an HTML context.
Summary
-------
Now that we are done with attribute selectors, you can continue on to the next article and read about pseudo-class and pseudo-element selectors.
* Previous
* Overview: Building blocks
* Next |
Getting started with CSS - Learn web development | Getting started with CSS
========================
* Previous
* Overview: First steps
* Next
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.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, and HTML basics (study
Introduction to HTML.)
|
| Objective: |
To understand the basics of linking a CSS document to an HTML file, and
be able to do simple text formatting with CSS.
|
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 `<head>` of the HTML document:
```html
<link rel="stylesheet" href="styles.css" />
```
This `<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.
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` 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 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.
**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 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>` (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?
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 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.
* Previous
* Overview: First steps
* Next |
How CSS works - Learn web development | How CSS works
=============
* Previous
* Overview: First steps
* Next
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.
| | |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
working with files, and HTML basics (study
Introduction to HTML.)
|
| Objective: |
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.
|
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 HTML into a 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.
![Rendering process overview](/en-US/docs/Learn/CSS/First_steps/How_CSS_works/rendering.svg)
About the DOM
-------------
A DOM has a tree-like structure. Each element, attribute, and piece of text in the markup language becomes a 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:
```
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:
```
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:
In our 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 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%;
}
```
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 you'll use your new knowledge to restyle an example, testing out some CSS in the process.
* Previous
* Overview: First steps
* Next |
Styling a biography page - Learn web development | Styling a biography page
========================
* Previous
* Overview: 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.
| | |
| --- | --- |
| Prerequisites: |
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
Introduction to HTML).
|
| Objective: | To have a play with some CSS and test your new-found knowledge. |
Starting point
--------------
You can work in the live editor below, or you can download the starting point file 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, JSFiddle, or Glitch.
If you get stuck, you can reach out to us in one of our 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.
* `font-family`
* `color`
* `border-bottom`
* `font-weight`
* `font-size`
* `font-style`
* `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 `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 `background-color` of `#eeeeee`, and a 5px solid purple `border`. Use some `padding` to push the content away from the border.
5. Make the links `green` on hover.
Hints and tips
--------------
* Use the W3C 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 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.
![Screenshot of how the example should look after completing the assessment.](/en-US/docs/Learn/CSS/First_steps/Styling_a_biography_page/learn-css-basics-assessment.png)
* Previous
* Overview: First steps |