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