Organizing your CSS - Learn web development

Organizing your CSS
===================

* Previous
* Overview: Building blocks
* Next

As you start to work on larger stylesheets and big projects you will discover that maintaining a huge CSS file can be challenging. In this article we will take a brief look at some best practices for writing your CSS to make it easily maintainable, and some of the solutions you will find in use by others to help improve maintainability.

|  |  |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
 working with files, HTML basics (study
 Introduction to HTML), and an idea of how CSS works (study
 CSS first steps.)
  |
| Objective: |
 To learn some tips and best practices for organizing stylesheets, and
 find out about some of the naming conventions and tools in common usage
 to help with CSS organization and team working.
  |

Tips to keep your CSS tidy
--------------------------

Here are some general suggestions for ways to keep your stylesheets organized and tidy.

### Does your project have a coding style guide?

If you are working with a team on an existing project, the first thing to check is whether the project has an existing style guide for CSS. The team style guide should always win over your own personal preferences. There often isn't a right or wrong way to do things, but consistency is important.

For example, have a look at the CSS guidelines for MDN code examples.

### Keep it consistent

If you get to set the rules for the project or are working alone, then the most important thing to do is to keep things consistent. Consistency can be applied in all sorts of ways, such as using the same naming conventions for classes, choosing one method of describing color, or maintaining consistent formatting. (For example, will you use tabs or spaces to indent your code? If spaces, how many spaces?)

Having a set of rules you always follow reduces the amount of mental overhead needed when writing CSS, as some of the decisions are already made.

### Formatting readable CSS

There are a couple of ways you will see CSS formatted. Some developers put all of the rules onto a single line, like so:

```css
.box {background-color: #567895; }
h2 {background-color: black; color: white; }
```

Other developers prefer to break everything onto a new line:

```css
.box {
  background-color: #567895;
}

h2 {
  background-color: black;
  color: white;
}
```

CSS doesn't mind which one you use. We personally find it is more readable to have each property and value pair on a new line.

### Comment your CSS

Adding comments to your CSS will help any future developer work with your CSS file, but will also help you when you come back to the project after a break.

```css
/\* This is a CSS comment
It can be broken onto multiple lines. \*/
```

A good tip is to add a block of comments between logical sections in your stylesheet too, to help locate different sections quickly when scanning it, or even to give you something to search for to jump right into that part of the CSS. If you use a string that won't appear in the code, you can jump from section to section by searching for it — below we have used `||`.

```css
/\* || General styles \*/

/\* … \*/

/\* || Typography \*/

/\* … \*/

/\* || Header and Main Navigation \*/

/\* … \*/
```

You don't need to comment every single thing in your CSS, as much of it will be self-explanatory. What you should comment are the things where you made a particular decision for a reason.

You may have used a CSS property in a specific way to get around older browser incompatibilities, for example:

```css
.box {
  background-color: red; /\* fallback for older browsers that don't support gradients \*/
  background-image: linear-gradient(to right, #ff0000, #aa0000);
}
```

Perhaps you followed a tutorial to achieve something, and the CSS isn't very self-explanatory or recognizable. In that case, you could add the URL of the tutorial to the comments. You will thank yourself when you come back to this project in a year or so and can vaguely remember that there was a great tutorial about that thing, but can't recall where it's from.

### Create logical sections in your stylesheet

It is a good idea to have all of the common styling first in the stylesheet. This means all of the styles which will generally apply unless you do something special with that element. You will typically have rules set up for:

* `body`
* `p`
* `h1`, `h2`, `h3`, `h4`, `h5`
* `ul` and `ol`
* The `table` properties
* Links

In this section of the stylesheet we are providing default styling for the type on the site, setting up a default style for data tables and lists and so on.

```css
/\* || GENERAL STYLES \*/

body {
  /\* … \*/
}

h1,
h2,
h3,
h4 {
  /\* … \*/
}

ul {
  /\* … \*/
}

blockquote {
  /\* … \*/
}
```

After this section, we could define a few utility classes, for example, a class that removes the default list style for lists we're going to display as flex items or in some other way. If you have a few styling choices you know you will want to apply to lots of different elements, they can be put in this section.

```css
/\* || UTILITIES \*/

.nobullets {
  list-style: none;
  margin: 0;
  padding: 0;
}

/\* … \*/
```

Then we can add everything that is used sitewide. That might be things like the basic page layout, the header, navigation styling, and so on.

```css
/\* || SITEWIDE \*/

.main-nav {
  /\* … \*/
}

.logo {
  /\* … \*/
}
```

Finally, we will include CSS for specific things, broken down by the context, page, or even component in which they are used.

```css
/\* || STORE PAGES \*/

.product-listing {
  /\* … \*/
}

.product-box {
  /\* … \*/
}
```

By ordering things in this way, we at least have an idea in which part of the stylesheet we will be looking for something that we want to change.

### Avoid overly-specific selectors

If you create very specific selectors, you will often find that you need to duplicate chunks of your CSS to apply the same rules to another element. For example, you might have something like the below selector, which applies the rule to a `<p>` with a class of `box` inside an `<article>` with a class of `main`.

```css
article.main p.box {
  border: 1px solid #ccc;
}
```

If you then wanted to apply the same rules to something outside of `main`, or to something other than a `<p>`, you would have to add another selector to these rules or create a whole new ruleset. Instead, you could use the selector `.box` to apply your rule to any element that has the class `box`:

```css
.box {
  border: 1px solid #ccc;
}
```

There will be times when making something more specific makes sense; however, this will generally be an exception rather than usual practice.

### Break large stylesheets into multiple smaller ones

In cases where you have very different styles for distinct parts of the site, you might want to have one stylesheet that includes all the global rules, as well as some smaller stylesheets that include the specific rules needed for those sections. You can link to multiple stylesheets from one page, and the normal rules of the cascade apply, with rules in stylesheets linked later coming after rules in stylesheets linked earlier.

For example, we might have an online store as part of the site, with a lot of CSS used only for styling the product listings and forms needed for the store. It would make sense to have those things in a different stylesheet, only linked to on store pages.

This can make it easier to keep your CSS organized, and also means that if multiple people are working on the CSS, you will have fewer situations where two people need to work on the same stylesheet at once, leading to conflicts in source control.

Other tools that can help
-------------------------

CSS itself doesn't have much in the way of in-built organization; therefore, the level of consistency in your CSS will largely depend on you. The web community has developed various tools and approaches that can help you to manage larger CSS projects. Since you are likely to come across these aids when working with other people, and since they are often of help generally, we've included a short guide to some of them.

### CSS methodologies

Instead of needing to come up with your own rules for writing CSS, you may benefit from adopting one of the approaches already designed by the community and tested across many projects. These methodologies are essentially CSS coding guides that take a very structured approach to writing and organizing CSS. Typically they tend to render CSS more verbosely than you might have if you wrote and optimized every selector to a custom set of rules for that project.

However, you do gain a lot of structure by adopting one. Since many of these systems are widely used, other developers are more likely to understand the approach you are using and be able to write their own CSS in the same way, rather than having to work out your own personal methodology from scratch.

#### OOCSS

Most of the approaches you will encounter owe something to the concept of Object Oriented CSS (OOCSS), an approach made popular by the work of Nicole Sullivan. The basic idea of OOCSS is to separate your CSS into reusable objects, which can be used anywhere you need on your site. The standard example of OOCSS is the pattern described as The Media Object. This is a pattern with a fixed size image, video or other element on one side, and flexible content on the other. It's a pattern we see all over websites for comments, listings, and so on.

If you are not taking an OOCSS approach you might create a custom CSS for the different places this pattern is used, for example, by creating two classes, one called `comment` with a bunch of rules for the component parts, and another called `list-item` with almost the same rules as the `comment` class except for some tiny differences. The differences between these two components are the list-item has a bottom border, and images in comments have a border whereas list-item images do not.

```css
.comment {
  display: grid;
  grid-template-columns: 1fr 3fr;
}

.comment img {
  border: 1px solid grey;
}

.comment .content {
  font-size: 0.8rem;
}

.list-item {
  display: grid;
  grid-template-columns: 1fr 3fr;
  border-bottom: 1px solid grey;
}

.list-item .content {
  font-size: 0.8rem;
}
```

In OOCSS, you would create one pattern called `media` that would have all of the common CSS for both patterns — a base class for things that are generally the shape of the media object. Then we'd add an additional class to deal with those tiny differences, thus extending that styling in specific ways.

```css
.media {
  display: grid;
  grid-template-columns: 1fr 3fr;
}

.media .content {
  font-size: 0.8rem;
}

.comment img {
  border: 1px solid grey;
}

.list-item {
  border-bottom: 1px solid grey;
}
```

In your HTML, the comment would need both the `media` and `comment` classes applied:

```html
<div class="media comment">
  <img src="" alt="" />
  <div class="content"></div>
</div>
```

The list-item would have `media` and `list-item` applied:

```html
<ul>
  <li class="media list-item">
    <img src="" alt="" />
    <div class="content"></div>
  </li>
</ul>
```

The work that Nicole Sullivan did in describing this approach and promoting it means that even people who are not strictly following an OOCSS approach today will generally be reusing CSS in this way — it has entered our understanding as a good way to approach things in general.

#### BEM

BEM stands for Block Element Modifier. In BEM a block is a stand-alone entity such as a button, menu, or logo. An element is something like a list item or a title that is tied to the block it is in. A modifier is a flag on a block or element that changes the styling or behavior. You will be able to recognize code that uses BEM due to the extensive use of dashes and underscores in the CSS classes. For example, look at the classes applied to this HTML from the page about BEM Naming conventions:

```html
<form class="form form--theme-xmas form--simple">
  <label class="label form\_\_label" for="inputId"></label>
  <input class="form\_\_input" type="text" id="inputId" />

  <input
 class="form\_\_submit form\_\_submit--disabled"
 type="submit"
 value="Submit" />
</form>
```

The additional classes are similar to those used in the OOCSS example; however, they use the strict naming conventions of BEM.

BEM is widely used in larger web projects and many people write their CSS in this way. It is likely that you will come across examples, even in tutorials, that use BEM syntax, without mentioning why the CSS is structured in such a way.

Read more about this system BEM 101 on CSS Tricks.

#### Other common systems

There are a large number of these systems in use. Other popular approaches include Scalable and Modular Architecture for CSS (SMACSS), created by Jonathan Snook, ITCSS from Harry Roberts, and Atomic CSS (ACSS), originally created by Yahoo!. If you come across a project that uses one of these approaches, then the advantage is that you will be able to search and find many articles and guides to help you understand how to code in the same style.

The disadvantage of using such a system is that they can seem overly complex, especially for smaller projects.

### Build systems for CSS

Another way to organize CSS is to take advantage of some of the tooling that is available for front-end developers, which allows you to take a slightly more programmatic approach to writing CSS. There are a number of tools, which we refer to as *pre-processors* and *post-processors*. A pre-processor runs over your raw files and turns them into a stylesheet, whereas a post-processor takes your finished stylesheet and does something to it — perhaps to optimize it in order that it will load faster.

Using any of these tools will require that your development environment be able to run the scripts that do the pre- and post-processing. Many code editors can do this for you, or you can install command line tools to help.

The most popular pre-processor is Sass. This is not a Sass tutorial, so I will briefly explain a couple of the things that Sass can do, which are really helpful in terms of organization even if you don't use any of the other Sass features. If you want to learn a lot more about Sass, start with the Sass basics article, then move on to their other documentation.

#### Defining variables

CSS now has native custom properties, making this feature increasingly less important. However, one of the reasons you might use Sass is to be able to define all of the colors and fonts used in a project as settings, then to use that variable around the project. This means that if you realize you have used the wrong shade of blue, you only need change it in one place.

If we created a variable called `$base-color`, as in the first line below, we could then use it through the stylesheet anywhere that required that color.

```scss
$base-color: #c6538c;

.alert {
  border: 1px solid $base-color;
}
```

Once compiled to CSS, you would end up with the following CSS in the final stylesheet.

```css
.alert {
  border: 1px solid #c6538c;
}
```

#### Compiling component stylesheets

I mentioned above that one way to organize CSS is to break down stylesheets into smaller stylesheets. When using Sass you can take this to another level and have lots of very small stylesheets — even going as far as having a separate stylesheet for each component. By using the included functionality in Sass (partials), these can all be compiled together into one or a small number of stylesheets to actually link into your website.

So, for example, with partials, you could have several style files inside a directory, say `foundation/_code.scss`, `foundation/_lists.scss`, `foundation/_footer.scss`, `foundation/_links.scss`, etc. You could then use the Sass `@use` rule to load them into other stylesheets:

```scss
// foundation/\_index.scss
@use "code";
@use "lists";
@use "footer";
@use "links";
```

If the partials are all loaded into an index file, as implied above, you can then load that entire directory into another stylesheet in one go:

```scss
// style.scss
@use "foundation";
```

**Note:** A simple way to try out Sass is to use CodePen — you can enable Sass for your CSS in the Settings for a Pen, and CodePen will then run the Sass parser for you in order that you can see the resulting webpage with regular CSS applied. Sometimes you will find that CSS tutorials have used Sass rather than plain CSS in their CodePen demos, so it is handy to know a little bit about it.

#### Post-processing for optimization

If you are concerned about adding size to your stylesheets, for example, by adding a lot of additional comments and whitespace, then a post-processing step could be to optimize the CSS by stripping out anything unnecessary in the production version. An example of a post-processor solution for doing this would be cssnano.

Summary
-------

This is the final part of our building blocks module, and as you can see there are many ways in which your exploration of CSS can continue from this point — but now you can go on to testing yourself with our assessments: the first one is linked below.

To learn more about layout in CSS, see the CSS Layout module.

You should also now have the skills to explore the rest of the MDN CSS material. You can look up properties and values, explore our CSS Cookbook for patterns to use, or continue reading in some of the specific guides, such as our Guide to CSS Grid Layout.

* Previous
* Overview: Building blocks
* Next


Test your skills: Values and units - Learn web development

Test your skills: Values and units
==================================

The aim of this skill test is to assess whether you understand different types of values and units used in CSS properties.

**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.

If you get stuck, you can reach out to us in one of our communication channels.

Task 1
------

In this task, the first list item has been given a background color using a hex color code. Your task is to complete the CSS using the same color in different formats, plus a final list item where you should make the background semi-opaque.

* The second list item should use RGB color.
* The third should use HSL color.
* The fourth should use RGB color but with the alpha channel set to `0.6`.

You can find conversions for the hex color at this link. You need to figure out how to use the values in CSS. Your final result should look like the image below:

![Four list items. The first three with the same background color and the last with a lighter background.](/en-US/docs/Learn/CSS/Building_blocks/Values_tasks/mdn-value-color.png)

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Task 2
------

In this task, we want you to set the size of various items of text, as described below:

* The `<h1>` element should be 50 pixels.
* The `<h2>` element should be 2em.
* All `<p>` elements should be 16 pixels.
* A `<p>` element that is directly after an `<h1>` should be 120%.

Your final result should look like the image below:

![Some text at varying sizes.](/en-US/docs/Learn/CSS/Building_blocks/Values_tasks/mdn-value-length.png)

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Task 3
------

In this task, we want you to move the background image so that it is centered horizontally and is 20% from the top of the box.

Your final result should look like the image below:

![A stat centered horizontally in a box and a short distance from the top of the box.](/en-US/docs/Learn/CSS/Building_blocks/Values_tasks/mdn-value-position.png)

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.


Test your skills: Tables - Learn web development

Test your skills: Tables
========================

The aim of this skill test is to assess whether you understand how to style HTML tables in CSS.

**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.

If you get stuck, you can reach out to us in one of our communication channels.

Task
----

In the lesson on styling tables we styled up a table in a rather garish manner. In this task, we are going to style the same table, but using some good practices for table design as outlined in the external article Web Typography: designing tables to be read not looked at.

Our finished table will look like the image below. There are a number of ways that you can achieve this, but we suggest you follow similar patterns as used in the tutorial to do the following things:

* Add padding of `0.3em` to the table headings and data and align them at the top of their cells.
* Align headings and data for columns containing numbers right.
* Align headings and data for columns containing text left.
* Add a 1px top and bottom solid border with the hex color `#999`, plus a 1px solid border of the same color above the footer.
* Remove the default spacing between the table elements borders to get the expected result.
* Stripe every odd row of the main table with the hex color `#eee`.

![A table with striped rows.](/en-US/docs/Learn/CSS/Building_blocks/Tables_tasks/mdn-table-bands.png)

Try updating the live code below to recreate the finished example:

Additional question:

* What can you do to make the table layout behave a bit more predictably? Think of how table columns are sized by default and how we can change this behavior to size the columns according to the width of their headings.

Download the starting point for this task to work in your own editor or in an online editor.


CSS values and units - Learn web development

CSS values and units
====================

* Previous
* Overview: Building blocks
* Next

 CSS rules contain declarations, which in turn are composed of properties and values.
 Each property used in CSS has a **value type** that describes what kind of values it is allowed to have.
 In this lesson, we will take a look at some of the most frequently used value types, what they are, and how they work.

**Note:** Each CSS property page has a syntax section that lists the value types you can use with that property.

|  |  |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
 working with files, HTML basics (study
 Introduction to HTML), and an idea of how CSS works (study
 CSS first steps).
  |
| Objective: |
 To learn about the different types of values and units used in CSS
 properties.
  |

What is a CSS value?
--------------------

In CSS specifications and on the property pages here on MDN you will be able to spot value types as they will be surrounded by angle brackets, such as `<color>` or `<length>`. When you see the value type `<color>` as valid for a particular property, that means you can use any valid color as a value for that property, as listed on the `<color>` reference page.

**Note:** You'll see CSS value types referred to as *data types*. The terms are basically interchangeable — when you see something in CSS referred to as a data type, it is really just a fancy way of saying value type. The term *value* refers to any particular expression supported by a value type that you choose to use.

**Note:** CSS value types tend to be enclosed in angle brackets (`<`, `>`) to differentiate them from CSS properties.
 For example there is a `color` property and a `<color>` data type.
 This is not to be confused with HTML elements, as they also use angle brackets, but this is something to keep in mind that the context should make clear.

In the following example, we have set the color of our heading using a keyword, and the background using the `rgb()` function:

```css
h1 {
  color: black;
  background-color: rgb(197 93 161);
}
```

A value type in CSS is a way to define a collection of allowable values. This means that if you see `<color>` as valid you don't need to wonder which of the different types of color value can be used — keywords, hex values, `rgb()` functions, etc. You can use *any* available `<color>` values, assuming they are supported by your browser. The page on MDN for each value will give you information about browser support. For example, if you look at the page for `<color>` you will see that the browser compatibility section lists different types of color values and support for them.

Let's have a look at some of the types of values and units you may frequently encounter, with examples so that you can try out different possible values.

Numbers, lengths, and percentages
---------------------------------

There are various numeric value types that you might find yourself using in CSS. The following are all classed as numeric:

| Data type | Description |
| --- | --- |
| `<integer>` |
 An `<integer>` is a whole number such as
 `1024` or `-55`.
  |
| `<number>` |
 A `<number>` represents a decimal number — it may or may
 not have a decimal point with a fractional component. For
 example, `0.255`, `128`, or `-1.2`.
  |
| `<dimension>` |
 A `<dimension>` is a `<number>` with a
 unit attached to it. For example, `45deg`, `5s`,
 or `10px`. `<dimension>` is an umbrella
 category that includes the `<length>`, `<angle>`, `<time>`, and
 `<resolution>`
 types.
  |
| `<percentage>` |
 A `<percentage>` represents a fraction of some other
 value. For example, `50%`. Percentage values are always
 relative to another quantity. For example, an element's length is
 relative to its parent element's length.
  |

### Lengths

The numeric type you will come across most frequently is `<length>`. For example, `10px` (pixels) or `30em`. There are two types of lengths used in CSS — relative and absolute. It's important to know the difference in order to understand how big things will become.

#### Absolute length units

The following are all **absolute** length units — they are not relative to anything else, and are generally considered to always be the same size.

| Unit | Name | Equivalent to |
| --- | --- | --- |
| `cm` | Centimeters | 1cm = 37.8px = 25.2/64in |
| `mm` | Millimeters | 1mm = 1/10th of 1cm |
| `Q` | Quarter-millimeters | 1Q = 1/40th of 1cm |
| `in` | Inches | 1in = 2.54cm = 96px |
| `pc` | Picas | 1pc = 1/6th of 1in |
| `pt` | Points | 1pt = 1/72nd of 1in |
| `px` | Pixels | 1px = 1/96th of 1in |

Most of these units are more useful when used for print, rather than screen output. For example, we don't typically use `cm` (centimeters) on screen. The only value that you will commonly use is `px` (pixels).

#### Relative length units

Relative length units are relative to something else, perhaps the size of the parent element's font, or the size of the viewport. The benefit of using relative units is that with some careful planning you can make it so the size of text or other elements scales relative to everything else on the page. Some of the most useful units for web development are listed in the table below.

| Unit | Relative to |
| --- | --- |
| `em` |
 Font size of the parent, in the case of typographical properties like
 `font-size`, and font size of the element itself, in the case of other properties
 like `width`.
  |
| `ex` | x-height of the element's font. |
| `ch` | The advance measure (width) of the glyph "0" of the element's font. |
| `rem` | Font size of the root element. |
| `lh` | Line height of the element. |
| `rlh` | Line height of the root element. When used on the `font-size` or `line-height` properties of the root element, it refers to the properties' initial value. |
| `vw` | 1% of the viewport's width. |
| `vh` | 1% of the viewport's height. |
| `vmin` | 1% of the viewport's smaller dimension. |
| `vmax` | 1% of the viewport's larger dimension. |
| `vb` | 1% of the size of the initial containing block in the direction of the root element's block axis. |
| `vi` | 1% of the size of the initial containing block in the direction of the root element's inline axis. |
| `svw, svh` | 1% of the small viewport's width and height, respectively. |
| `lvw, lvh` | 1% of the large viewport's width and height, respectively. |
| `dvw, dvh` | 1% of the dynamic viewport's width and height, respectively. |

#### Exploring an example

In the example below, you can see how some relative and absolute length units behave. The first box has a `width` set in pixels. As an absolute unit, this width will remain the same no matter what else changes.

The second box has a width set in `vw` (viewport width) units. This value is relative to the viewport width, and so 10vw is 10 percent of the width of the viewport. If you change the width of your browser window, the size of the box should change. However this example is embedded into the page using an `<iframe>`, so this won't work. To see this in action you'll have to try the example after opening it in its own browser tab.

The third box uses `em` units. These are relative to the font size. I've set a font size of `1em` on the containing `<div>`, which has a class of `.wrapper`. Change this value to `1.5em` and you will see that the font size of all the elements increases, but only the last item will get wider, as its width is relative to that font size.

After following the instructions above, try playing with the values in other ways, to see what you get.

#### ems and rems

`em` and `rem` are the two relative lengths you are likely to encounter most frequently when sizing anything from boxes to text. It's worth understanding how these work, and the differences between them, especially when you start getting on to more complex subjects like styling text or CSS layout. The below example provides a demonstration.

The HTML illustrated below is a set of nested lists — we have two lists in total and both examples have the same HTML. The only difference is that the first has a class of *ems* and the second a class of *rems*.

To start with, we set 16px as the font size on the `<html>` element.

**To recap, the em unit means "my parent element's font-size"** in the case of typography. The `<li>` elements inside the `<ul>` with a `class` of `ems` take their sizing from their parent. So each successive level of nesting gets progressively larger, as each has its font size set to `1.3em` — 1.3 times its parent's font size.

**To recap, the rem unit means "The root element's font-size"** (rem stands for "root em"). The `<li>` elements inside the `<ul>` with a `class` of `rems` take their sizing from the root element (`<html>`). This means that each successive level of nesting does not keep getting larger.

However, if you change the `<html>` element's `font-size` in the CSS you will see that everything else changes relative to it — both `rem`- and `em`-sized text.

#### Line height units

`lh` and `rlh` are relative lengths units similar to `em` and `rem`. The difference between `lh` and `rlh` is that the first one is relative to the line height of the element itself, while the second one is relative to the line height of the root element, usually `<html>`.

Using these units, we can precisely align box decoration to the text. In this example, we use `lh` unit to create notepad-like lines using `repeating-linear-gradient()`. It doesn't matter what's the line height of the text, the lines will always start in the right place.
```

body {
  margin: 0;
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 24px;
  gap: 24px;
  background-color: floralwhite;
  font-family: sans-serif;
}

@supports not (height: 1lh) {
  body::before {
    grid-column: 1 / -1;
    padding: 8px;
    border-radius: 4px;
    background-color: tomato;
    color: white;
    content: "You browser doesn’t support lh unit just yet";
  }
}
```

```css
p {
  margin: 0;
  background-image: repeating-linear-gradient(
    to top,
    lightskyblue 0 2px,
    transparent 2px 1lh
  );
}
```

```html
<p style="line-height: 2em">
  Summer is a time for adventure, and this year was no exception. I had many
  exciting experiences, but two of my favorites were my trip to the beach and my
  week at summer camp.
</p>

<p style="line-height: 4em">
  At the beach, I spent my days swimming, collecting shells, and building
  sandcastles. I also went on a boat ride and saw dolphins swimming alongside
  us.
</p>
```

### Percentages

In a lot of cases, a percentage is treated in the same way as a length. The thing with percentages is that they are always set relative to some other value. For example, if you set an element's `font-size` as a percentage, it will be a percentage of the `font-size` of the element's parent. If you use a percentage for a `width` value, it will be a percentage of the `width` of the parent.

In the below example the two percentage-sized boxes and the two pixel-sized boxes have the same class names. The sets are 40% and 200px wide respectively.

The difference is that the second set of two boxes is inside a wrapper that is 400 pixels wide. The second 200px wide box is the same width as the first one, but the second 40% box is now 40% of 400px — a lot narrower than the first one!

**Try changing the width of the wrapper or the percentage value to see how this works.**

The next example has font sizes set in percentages. Each `<li>` has a `font-size` of 80%; therefore, the nested list items become progressively smaller as they inherit their sizing from their parent.

Note that, while many value types accept a length or a percentage, there are some that only accept length. You can see which values are accepted on the MDN property reference pages. If the allowed value includes `<length-percentage>` then you can use a length or a percentage. If the allowed value only includes `<length>`, it is not possible to use a percentage.

### Numbers

Some value types accept numbers, without any unit added to them. An example of a property which accepts a unitless number is the `opacity` property, which controls the opacity of an element (how transparent it is). This property accepts a number between `0` (fully transparent) and `1` (fully opaque).

**In the below example, try changing the value of `opacity` to various decimal values between `0` and `1` and see how the box and its contents become more or less opaque.**

**Note:** When you use a number in CSS as a value it should not be surrounded in quotes.

Color
-----

 Color values can be used in many places in CSS, whether you are specifying the color of text, backgrounds, borders, and lots more.
 There are many ways to set color in CSS, allowing you to control plenty of exciting properties.

The standard color system available in modern computers supports 24-bit colors, which allows displaying about 16.7 million distinct colors via a combination of different red, green, and blue channels with 256 different values per channel (256 x 256 x 256 = 16,777,216).

 In this section, we'll first look at the most commonly seen ways of specifying colors: using keywords, hexadecimal, and `rgb()` values.
 We'll also take a quick look at additional color functions, enabling you to recognize them when you see them or experiment with different ways of applying color.

 You will likely decide on a color palette and then use those colors — and your favorite way of specifying color — throughout your project.
 You can mix and match color models, but it's usually best if your entire project uses the same method of declaring colors for consistency!

### Color keywords

You will see the color keywords (or 'named colors') used in many MDN code examples. As the `<named-color>`s data type contains a very finite number of color values, these are not commonly used on production websites. As the keyword represents the color as a human-readable text value, named colors are used in code examples to clearly tell the user what color is expected so the learner can focus on the content being taught.

**Try playing with different color values in the live examples below, to get more of an idea how they work.**

### Hexadecimal RGB values

 The next type of color value you are likely to encounter is hexadecimal codes.
 Hexadecimal uses 16 characters from `0-9` and `a-f`, so the entire range is `0123456789abcdef`.
 Each hex color value consists of a hash/pound symbol (`#`) followed by three or six hexadecimal characters (`#fcc` or `#ffc0cb`, for example), with an optional one or two hexadecimal characters representing the alpha-transparency of the previous three or six character color values.

 When using hexadecimal to describe RGB values, each **pair** of hexadecimal characters is a decimal number representing one of the channels — red, green and blue — and allows us to specify any of the 256 available values for each (16 x 16 = 256).
 These values are less intuitive than keywords for defining colors, but they are a lot more versatile because you can represent any RGB color with them.

**Again, try changing the values to see how the colors vary.**

### RGB values

To create RGB values directly, the `rgb()` function takes three parameters representing **red**, **green**, and **blue** channel values of the colors, with an optional fourth value separated by a slash ('/') representing opacity, in much the same way as hex values. The difference with RGB is that each channel is represented not by two hex digits, but by a decimal number between 0 and 255 or a percent between 0% and 100% inclusive (but not a mixture of the two).

Let's rewrite our last example to use RGB colors:

You can pass a fourth parameter to `rgb()`, which represents the alpha channel of the color, which controls opacity. If you set this value to `0` it will make the color fully transparent, whereas `1` will make it fully opaque. Values in between give you different levels of transparency.

**Note:** Setting an alpha channel on a color has one key difference to using the `opacity` property we looked at earlier. When you use opacity you make the element and everything inside it opaque, whereas using RGB with an alpha parameter colors only makes the color you are specifying opaque.

In the example below, we have added a background image to the containing block of our colored boxes. We have then set the boxes to have different opacity values — notice how the background shows through more when the alpha channel value is smaller.

**In this example, try changing the alpha channel values to see how it affects the color output.**

**Note:** In older versions of CSS, the `rgb()` syntax didn't support an alpha parameter - you needed to use a different function called `rgba()` for that. These days you can pass an alpha parameter to `rgb()`, but for backwards compatibility with old websites, the `rgba()` syntax is still supported, and has exactly the same behavior as `rgb()`.

### Using hues to specify a color

 If you want to go beyond keywords, hexadecimal, and `rgb()` for colors, you might want to try using `<hue>`.
 Hue is the property that allows us to tell the difference or similarity between colors like red, orange, yellow, green, blue, etc.
 The key concept is that you can specify a hue in an `<angle>` because most of the color models describe hues using a color wheel.

 A great starting point for using hues in CSS is the `hsl()` function.
 Let's take a quick look at the parts you can specify:

* **Hue**: The base shade of the color. This takes a `<hue>` value between 0 and 360, representing the angles around a color wheel.
* **Saturation**: How saturated is the color? This takes a value from 0–100%, where 0 is no color (it will appear as a shade of grey), and 100% is full color saturation.
* **Lightness**: How light or bright is the color? This takes a value from 0–100%, where 0 is no light (it will appear completely black) and 100% is full light (it will appear completely white).

Similar to `rgb()`, the `hsl()` color value also has an optional fourth value, separated from the color with a slash (`/`), representing the alpha transparency.

Let's update the RGB example to use HSL colors instead:

Just like with `rgb()` you can pass an alpha parameter to `hsl()` to specify opacity:

**Note:** In older versions of CSS, the `hsl()` syntax didn't support an alpha parameter - you needed to use a different function called `hsla()` for that. These days you can pass an alpha parameter to `hsl()`, but for backwards compatibility with old websites, the `hsla()` syntax is still supported, and has exactly the same behavior as `hsl()`.

 There are other color functions available such as `hwb()` and `lch()` which also use `<hue>` component, and even functions such as `lab()` which let you work with colors based on what humans can see.
 If you want to find out more about these functions and color spaces, see the Applying color to HTML elements using CSS guide, the `<color>` reference that lists all the different ways you can use colors in CSS, and the CSS color module that provides an overview of all the color types in CSS and the properties that use color values.

Images
------

The `<image>` value type is used wherever an image is a valid value. This can be an actual image file pointed to via a `url()` function, or a gradient.

In the example below, we have demonstrated an image and a gradient in use as a value for the CSS `background-image` property.

**Note:** There are some other possible values for `<image>`, however these are newer and currently have poor browser support. Check out the page on MDN for the `<image>` data type if you want to read about them.

Position
--------

The `<position>` value type represents a set of 2D coordinates, used to position an item such as a background image (via `background-position`). It can take keywords such as `top`, `left`, `bottom`, `right`, and `center` to align items with specific bounds of a 2D box, along with lengths, which represent offsets from the top and left-hand edges of the box.

A typical position value consists of two values — the first sets the position horizontally, the second vertically. If you only specify values for one axis the other will default to `center`.

In the following example we have positioned a background image 40px from the top and to the right of the container using a keyword.

**Play around with these values to see how you can push the image around.**

Strings and identifiers
-----------------------

Throughout the examples above, we've seen places where keywords are used as a value (for example `<color>` keywords like `red`, `black`, `rebeccapurple`, and `goldenrod`). These keywords are more accurately described as *identifiers*, a special value that CSS understands. As such they are not quoted — they are not treated as strings.

There are places where you use strings in CSS. For example, when specifying generated content. In this case, the value is quoted to demonstrate that it is a string. In the example below, we use unquoted color keywords along with a quoted generated content string.

Functions
---------

 In programming, a function is a piece of code that does a specific task.
 Functions are useful because you can write code once, then reuse it many times instead of writing the same logic over and over.
 Most programming languages not only support functions but also come with convenient built-in functions for common tasks so you don't have to write them yourself from scratch.

 CSS also has functions, which work in a similar way to functions in other languages.
 In fact, we've already seen CSS functions in the Color section above with `rgb()` and `hsl()` functions.

 Aside from applying colors, you can use functions in CSS to do a lot of other things.
 For example Transform functions are a common way to move, rotate, and scale elements on a page.
 You might see `translate()` for moving something horizontally or vertically, `rotate()` to rotate something, or `scale()` to make something bigger or smaller.

### Math functions

 When you are creating styles for a project, you will probably start off with numbers like `300px` for lengths or `200ms` for durations.
 If you want to have these values change based on other values, you will need to do some math.
 You could calculate the percentage of a value or add a number to another number, then update your CSS with the result.

 CSS has support for Math functions, which allow us to perform calculations instead of relying on static values or doing the math in JavaScript.
 One of the most common math functions is `calc()` which lets you do operations like addition, subtraction, multiplication, and division.

 For example, let's say we want to set the width of an element to be 20% of its parent container plus 100px.
 We can't specify this width with a static value — if the parent uses a percentage width (or a relative unit like `em` or `rem`) then it will vary depending on the context it is used in, and other factors such as the user's device or browser window width.
 However, we can use `calc()` to set the width of the element to be 20% of its parent container plus 100px.
 The 20% is based on the width of the parent container (`.wrapper`) and if that width changes, the calculation will change too:

 There are many other math functions that you can use in CSS, such as `min()`, `max()`, and `clamp()`; respectively these let you pick the smallest, largest, or middle value from a set of values.
 You can also use Trigonometric functions like `sin()`, `cos()`, and `tan()` to calculate angles for rotating elements around a point, or choose colors that take a hue angle as a parameter.
 Exponential functions might also be used for animations and transitions, when you require very specific control over how something moves and looks.

Knowing about CSS functions is useful so you recognize them when you see them. You should start experimenting with them in your projects — they will help you avoid writing custom or repetitive code to achieve results that you can get with regular CSS.

Test your skills!
-----------------

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Values and units.

Summary
-------

This has been a quick run-through of the most common types of values and units you might encounter. You can have a look at all of the different types on the CSS Values and units reference page — you will encounter many of these in use as you work through these lessons.

The key thing to remember is that each property has a defined list of allowed value types, and each value type has a definition explaining what the values are. You can then look up the specifics here on MDN. For example, understanding that `<image>` also allows you to create a color gradient is useful but perhaps non-obvious knowledge to have!

In the next article, we'll take a look at how items are sized in CSS.

* Previous
* Overview: Building blocks
* Next


Advanced styling effects - Learn web development

Advanced styling effects
========================

This article acts as a box of tricks, providing an introduction to some interesting advanced styling features such as box shadows, blend modes, and filters.

|  |  |
| --- | --- |
| Prerequisites: |
 HTML basics (study
 Introduction to HTML) and an idea of how CSS works (study
 CSS first steps.)
  |
| Objective: |
 To get an idea about how to use some of the advanced styling effects
 available in modern browsers.
  |

Box shadows
-----------

`box-shadow` allows you to apply one or more drop shadows to an element's box. Like text shadows, box shadows are supported pretty well across browsers, including IE9+ and Edge. Users of older IE versions might just have to cope with no shadows, so just test your designs to make sure your content is legible without them.

You can find the examples in this section at box-shadow.html (see the source code too).

### A simple box shadow

Let's look at a simple example to get things started. First, some HTML:

```html
<article class="simple">
  <p>
    <strong>Warning</strong>: The thermostat on the cosmic transcender has
    reached a critical level.
  </p>
</article>
```

Now the CSS:

```css
p {
  margin: 0;
}

article {
  max-width: 500px;
  padding: 10px;
  background-color: red;
  background-image: linear-gradient(
    to bottom,
    rgb(0 0 0 / 0%),
    rgb(0 0 0 / 25%)
  );
}

.simple {
  box-shadow: 5px 5px 5px rgb(0 0 0 / 70%);
}
```

This gives us the following result:

You'll see that we've got four items in the `box-shadow` property value:

1. The first length value is the **horizontal offset** — the distance to the right the shadow is offset from the original box (or left, if the value is negative).
2. The second length value is the **vertical offset** — the distance downwards that the shadow is offset from the original box (or upwards, if the value is negative).
3. The third length value is the **blur radius** — the amount of blurring applied to the shadow.
4. The color value is the **base color** of the shadow.

You can use any length and color units that would make sense to do so to define these values.

### Multiple box shadows

You can also specify multiple box shadows in a single `box-shadow` declaration, by separating them with commas:
```

<article class="multiple">
  <p>
    <strong>Warning</strong>: The thermostat on the cosmic transcender has
    reached a critical level.
  </p>
</article>
```

```css
p {
  margin: 0;
}

article {
  max-width: 500px;
  padding: 10px;
  background-color: red;
  background-image: linear-gradient(
    to bottom,
    rgb(0 0 0 / 0%),
    rgb(0 0 0 / 25%)
  );
}

.multiple {
  box-shadow: 1px 1px 1px black,
              2px 2px 1px black,
              3px 3px 1px red,
              4px 4px 1px red,
              5px 5px 1px black,
              6px 6px 1px black;
}
```

Now we get this result:

We've done something fun here by creating a raised box with multiple colored layers, but you could use it in any way you want, for example to create a more realistic look with shadows based on multiple light sources.

### Other box shadow features

Unlike `text-shadow`, `box-shadow` has an `inset` keyword available — putting this at the start of a shadow declaration causes it to become an inner shadow, rather than an outer shadow. Let's have a look and see what we mean.

First, we'll go with some different HTML for this example:

```html
<button>Press me!</button>
```

```css
button {
  width: 150px;
  font-size: 1.1rem;
  line-height: 2;
  border-radius: 10px;
  border: none;
  background-image: linear-gradient(to bottom right, #777, #ddd);
  box-shadow:
    1px 1px 1px black,
    inset 2px 3px 5px rgb(0 0 0 / 30%),
    inset -2px -3px 5px rgb(255 255 255 / 50%);
}

button:focus,
button:hover {
  background-image: linear-gradient(to bottom right, #888, #eee);
}

button:active {
  box-shadow:
    inset 2px 2px 1px black,
    inset 2px 3px 5px rgb(0 0 0 / 30%),
    inset -2px -3px 5px rgb(255 255 255 / 50%);
}
```

This gives us the following result:

Here we've set up some button styling along with focus/hover/active states. The button has a simple black box shadow set on it by default, plus a couple of inset shadows, one light and one dark, placed on opposite corners of the button to give it a nice shading effect.

When the button is pressed in, the active state causes the first box shadow to be swapped for a very dark inset shadow, giving the appearance of the button being pressed in.

**Note:** There is another item that can be set in the `box-shadow` value — another length value can be optionally set just before the color value, which is a **spread radius**. If set, this causes the shadow to become bigger than the original box. It is not very commonly used, but worth mentioning.

Filters
-------

While you can't change the composure of an image using CSS, there are some creative things you can do. One very nice property, which can help you bring interest to your designs, is the `filter` property. This property enables Photoshop-like filters right from CSS.

In the example below we have used two different values for filter. The `first` is `blur()` — this function can be passed a value to indicate how much the image should be blurred.

The second is `grayscale()`; by using a percentage we are setting how much color we want to be removed.

**Play with the percentage and pixel parameters in the live example to see how the images change. You could also swap the values for some others. Try `contrast(200%)`, `invert(100%)` or `hue-rotate(20deg)` on the live example above. Take a look at the MDN page for `filter` for many other options you could try.**

You can apply filters to any element and not just images. Some of the filter options available do very similar things to other CSS features, for example `drop-shadow()` works in a very similar way and gives a similar effect to `box-shadow` or `text-shadow`. The really nice thing about filters however, is that they work on the exact shapes of the content inside the box, not just the box itself as one big chunk, so it is worth knowing the difference.

In this next example we are applying our filter to a box, and comparing it to a box shadow. As you can see, the drop-shadow filter follows the exact shape of the text and border dashes. The box shadow just follows the square of the box.

Blend modes
-----------

CSS blend modes allow us to add blend modes to elements that specify a blending effect when two elements overlap — the final color shown for each pixel will be the result of a combination of the original pixel color, and that of the pixel in the layer underneath it. Blend modes are again very familiar to users of graphics applications like Photoshop.

There are two properties that use blend modes in CSS:

* `background-blend-mode`, which blends together multiple background images and colors set on a single element.
* `mix-blend-mode`, which blends together the element it is set on with elements it is overlapping — both background and content.

You can find a lot more examples than are available here in our blend-modes.html example page (see source code), and on the `<blend-mode>` reference page.

**Note:** Blend modes are also very new, and slightly less well supported than filters. There is no support as yet in Edge, and Safari only supports some of the blend mode options.

### background-blend-mode

Again, let's look at some examples so we can understand this better. First, `background-blend-mode` — here we'll show a couple of simple `<div>`s, so you can compare the original with the blended version:

```html
<div></div>
<div class="multiply"></div>
```

Now some CSS — we are adding to the `<div>` one background image and a green background color:

```css
div {
  width: 250px;
  height: 130px;
  padding: 10px;
  margin: 10px;
  display: inline-block;
  background: url(colorful-heart.png) no-repeat center 20px;
  background-color: green;
}

.multiply {
  background-blend-mode: multiply;
}
```

The result we get is this — you can see the original on the left, and the multiply blend mode on the right:

### mix-blend-mode

Now let's look at `mix-blend-mode`. Here we'll present the same two `<div>`s, but each one is now sat on top of a simple `<div>` with a purple background, to show how the elements will blend together:

```html
<article>
  No mix blend mode
  <div></div>
  <div></div>
</article>

<article>
  Multiply mix
  <div class="multiply-mix"></div>
  <div></div>
</article>
```

Here's the CSS we'll style this with:

```css
article {
  width: 280px;
  height: 180px;
  margin: 10px;
  position: relative;
  display: inline-block;
}

div {
  width: 250px;
  height: 130px;
  padding: 10px;
  margin: 10px;
}

article div:first-child {
  position: absolute;
  top: 10px;
  left: 0;
  background: url(colorful-heart.png) no-repeat center 20px;
  background-color: green;
}

article div:last-child {
  background-color: purple;
  position: absolute;
  bottom: -10px;
  right: 0;
  z-index: -1;
}

.multiply-mix {
  mix-blend-mode: multiply;
}
```

This gives us the following results:

You can see here that the multiply mix blend has blended together not only the two background images, but also the color from the `<div>` below it too.

**Note:** Don't worry if you don't understand some of the layout properties above, like `position`, `top`, `bottom`, `z-index`, etc. We will cover these in detail in our CSS Layout module.

CSS shapes
----------

While it is true that everything in CSS is a rectangular box, and images are a physical rectangular box, we can make it look as if our content flows around non-rectangular things by using CSS Shapes.

The CSS Shapes specification enables the wrapping of text around a non-rectangular shape. It's especially useful when working with an image which has some white-space you might want to float text around.

In the image below we have a pleasingly round balloon. The actual file is rectangular, but by floating the image (shapes only apply to floated elements) and using the `shape-outside` property with a value of `circle(50%)`, we can give the effect of the text following the line of the balloon.

The shape in this example is not reacting to the content of the image file. Instead, the circle function is taking its center point from the center of the image file, as if we had put a compass in the middle of the file and drawn a circle that fits inside the file. It is that circle that the text flows around.

**Note:** In Firefox you can use the DevTools Shapes Inspector to inspect Shapes.

The `circle()` function is just one of a few basic shapes that are defined, however there are a number of different ways to create shapes. For more information and example code for CSS Shapes see the Guides to CSS Shapes on MDN.

-webkit-background-clip: text
-----------------------------

Another feature we thought we'd mention briefly is the `text` value for `background-clip`. When used along with the proprietary `-webkit-text-fill-color: transparent;` feature, this allows you to clip background images to the shape of the element's text, making for some nice effects. This is not an official standard, but has been implemented across multiple browsers, as it is popular, and used fairly widely by developers. When used in this context, both of the properties would require a `-webkit-` vendor prefix, even for Non-Webkit/Chrome-based browsers:

```css
.text-clip {
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
```

So why have other browsers implemented a `-webkit-` prefix? Mainly for browser compatibility — so many web developers have started implementing websites with `-webkit-` prefixes that it started to look like the other browsers were broken, whereas in actual fact they were following the standards. So they were forced to implement a few such features. This highlights the danger of using non-standard and/or prefixed CSS features in your work — not only do they cause browser compatibility issues, but they are also subject to change, so your code could break at any time. It is much better to stick to the standards.

If you do want to use such features in your production work, make sure to test across browsers thoroughly and check that, where these features don't work, the site is still usable.

**Note:** For a full `-webkit-background-clip: text` code example, see background-clip-text.html (see also the source code).

Summary
-------

We hope this article was fun — playing with shiny toys generally is, and it is always interesting to see what kinds of advanced styling tools are becoming available in modern browsers.


Debugging CSS - Learn web development

Debugging CSS
=============

* Previous
* Overview: Building blocks
* Next

Sometimes when writing CSS you will encounter an issue where your CSS doesn't seem to be doing what you expect. Perhaps you believe that a certain selector should match an element, but nothing happens, or a box is a different size than you expected. This article will give you guidance on how to go about debugging a CSS problem, and show you how the DevTools included in all modern browsers can help you to find out what is going on.

|  |  |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
 working with files, HTML basics (study
 Introduction to HTML), and an idea of how CSS works (study
 CSS first steps.)
  |
| Objective: |
 To learn the basics of what browser DevTools are, and how to do simple
 inspection and editing of CSS.
  |

How to access browser DevTools
------------------------------

The article What are browser developer tools is an up-to-date guide explaining how to access the tools in various browsers and platforms. While you may choose to mostly develop in a particular browser, and therefore will become most familiar with the tools included in that browser, it is worth knowing how to access them in other browsers. This will help if you are seeing different rendering between multiple browsers.

You will also find that browsers have chosen to focus on different areas when creating their DevTools. For example, in Firefox there are some excellent tools for working visually with CSS Layout, allowing you to inspect and edit Grid Layouts, Flexbox, and Shapes. However, all of the different browsers have similar fundamental tools, e.g., for inspecting the properties and values applied to elements on your page, and making changes to them from the editor.

In this lesson we will look at some useful features of the Firefox DevTools for working with CSS. In order to do so I'll be using an example file. Load this up in a new tab if you want to follow along, and open up your DevTools as described in the article linked above.

The DOM versus view source
--------------------------

Something that can trip up newcomers to DevTools is the difference between what you see when you view the source of a webpage, or look at the HTML file you put on the server, and what you can see in the HTML Pane of the DevTools. While it looks roughly similar to what you can see via View Source there are some differences.

In the rendered DOM the browser may have normalized the HTML, for example by correcting some badly-written HTML for you. If you incorrectly closed an element, for instance by opening an `<h2>` but closing with an `</h3>`, the browser will figure out what you were meaning to do and the HTML in the DOM will correctly close the open `<h2>` with an `</h2>`. The DOM will also show any changes made by JavaScript.

View Source, in comparison, is the HTML source code as stored on the server. The HTML tree in your DevTools shows exactly what the browser is rendering at any given time, so it gives you an insight into what is really going on.

Inspecting the applied CSS
--------------------------

Select an element on your page, either by right/ctrl-clicking on it and selecting *Inspect*, or selecting it from the HTML tree on the left of the DevTools display. Try selecting the element with the class of `box1`; this is the first element on the page with a bordered box drawn around it.

![The example page for this tutorial with DevTools open.](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/inspecting1.png)

If you look at the Rules view to the right of your HTML, you should be able to see the CSS properties and values applied to that element. You will see the rules directly applied to class `box1` and also the CSS that is being inherited by the box from its ancestors, in this case from `<body>`. This is useful if you are seeing some CSS being applied that you didn't expect. Perhaps it is being inherited from a parent element and you need to add a rule to overwrite it in the context of this element.

Also useful is the ability to expand out shorthand properties. In our example the `margin` shorthand is used.

**Click on the little arrow to expand the view, showing the different longhand properties and their values.**

**You can toggle values in the Rules view on and off when that panel is active — if you hold your mouse over it, checkboxes will appear. Uncheck a rule's checkbox, for example `border-radius`, and the CSS will stop applying.**

You can use this to do an A/B comparison, deciding if something looks better with a rule applied or not, and also to help debug it — for example, if a layout is going wrong and you are trying to work out which property is causing the problem.

The following video provides some useful tips on debugging CSS using the Firefox DevTools:

Editing values
--------------

In addition to turning properties on and off, you can edit their values. Perhaps you want to see if another color looks better, or wish to tweak the size of something? DevTools can save you a lot of time editing a stylesheet and reloading the page.

**With `box1` selected, click on the swatch (the small colored circle) that shows the color applied to the border. A color picker will open up and you can try out some different colors; these will update in real time on the page. In a similar fashion, you could change the width or style of the border.**

![DevTools Styles Panel with a color picker open.](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/inspecting2-color-picker.png)

Adding a new property
---------------------

You can add properties using the DevTools. Perhaps you have realized that you don't want your box to inherit the `<body>` element's font size, and want to set its own specific size? You can try this out in DevTools before adding it to your CSS file.

**You can click the closing curly brace in the rule to start entering a new declaration into it, at which point you can start typing the new property and DevTools will show you an autocomplete list of matching properties. After selecting `font-size`, enter the value you want to try. You can also click the + button to add an additional rule with the same selector, and add your new rules there.**

![The DevTools Panel, adding a new property to the rules, with the autocomplete for font- open](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/inspecting3-font-size.png)

**Note:** There are other useful features in the Rules view too, for example declarations with invalid values are crossed out. You can find out more at Examine and edit CSS.

Understanding the box model
---------------------------

In previous lessons we have discussed the Box Model, and the fact that we have an alternate box model that changes how the size of elements are calculated based on the size you give them, plus the padding and borders. DevTools can really help you to understand how the size of an element is being calculated.

The Layout view shows you a diagram of the box model on the selected element, along with a description of the properties and values that change how the element is laid out. This includes a description of properties that you may not have explicitly used on the element, but which do have initial values set.

In this panel, one of the detailed properties is the `box-sizing` property, which controls what box model the element uses.

**Compare the two boxes with classes `box1` and `box2`. They both have the same width applied (400px), however `box1` is visually wider. You can see in the layout panel that it is using `content-box`. This is the value that takes the size you give the element and then adds on the padding and border width.**

The element with a class of `box2` is using `border-box`, so here the padding and border is subtracted from the size that you have given the element. This means that the space taken up on the page by the box is the exact size that you specified — in our case `width: 400px`.

![The Layout section of the DevTools](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/inspecting4-box-model.png)

**Note:** Find out more in Examining and Inspecting the Box Model.

Solving specificity issues
--------------------------

Sometimes during development, but in particular when you need to edit the CSS on an existing site, you will find yourself having a hard time getting some CSS to apply. No matter what you do, the element just doesn't seem to take the CSS. What is generally happening here is that a more specific selector is overriding your changes, and here DevTools will really help you out.

In our example file there are two words that have been wrapped in an `<em>` element. One is displaying as orange and the other hotpink. In the CSS we have applied:

```css
em {
  color: hotpink;
  font-weight: bold;
}
```

Above that in the stylesheet however is a rule with a `.special` selector:

```css
.special {
  color: orange;
}
```

As you will recall from the lesson on cascade and inheritance where we discussed specificity, class selectors are more specific than element selectors, and so this is the value that applies. DevTools can help you find such issues, especially if the information is buried somewhere in a huge stylesheet.

**Inspect the `<em>` with the class of `.special` and DevTools will show you that orange is the color that applies, and also that the `color` property applied to the `<em>` is crossed out. You can now see that the class selector is overriding the element selector.**

![Selecting an em and looking at DevTools to see what is over-riding the color.](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/inspecting5-specificity.png)

Find out more about the Firefox DevTools
----------------------------------------

There is a lot of information about the Firefox DevTools here on MDN. Take a look at the main DevTools section, and for more detail on the things we have briefly covered in this lesson see The How To Guides.

Debugging problems in CSS
-------------------------

DevTools can be a great help when solving CSS problems, so when you find yourself in a situation where CSS isn't behaving as you expect, how should you go about solving it? The following steps should help.

### Take a step back from the problem

Any coding problem can be frustrating, especially CSS problems because you often don't get an error message to search for online to help with finding a solution. If you are becoming frustrated, take a step away from the issue for a while — go for a walk, grab a drink, chat to a co-worker, or work on some other thing for a while. Sometimes the solution magically appears when you stop thinking about the problem, and even if not, working on it when feeling refreshed will be much easier.

### Do you have valid HTML and CSS?

Browsers expect your CSS and HTML to be correctly written, however browsers are also very forgiving and will try their best to display your webpages even if you have errors in the markup or stylesheet. If you have mistakes in your code the browser needs to make a guess at what you meant, and it might make a different decision to what you had in mind. In addition, two different browsers might cope with the problem in two different ways. A good first step, therefore, is to run your HTML and CSS through a validator, to pick up and fix any errors.

* CSS Validator
* HTML validator
### Are the property and value supported by the browser you are testing in?

Browsers ignore CSS they don't understand. If the property or value you are using is not supported by the browser you are testing in then nothing will break, but that CSS won't be applied. DevTools will generally highlight unsupported properties and values in some way. In the screenshot below the browser does not support the subgrid value of `grid-template-columns`.

![Image of browser DevTools with the grid-template-columns: subgrid crossed out as the subgrid value is not supported.](/en-US/docs/Learn/CSS/Building_blocks/Debugging_CSS/no-support.png)

You can also take a look at the Browser compatibility tables at the bottom of each property page on MDN. These show you browser support for that property, often broken down if there is support for some usage of the property and not others. See the compatibility table for the `shape-outside` property.

### Is something else overriding your CSS?

This is where the information you have learned about specificity will come into much use. If you have something more specific overriding what you are trying to do, you can enter into a very frustrating game of trying to work out what. However, as described above, DevTools will show you what CSS is applying and you can work out how to make the new selector specific enough to override it.

### Make a reduced test case of the problem

If the issue isn't solved by the steps above, then you will need to do some more investigating. The best thing to do at this point is to create something known as a reduced test case. Being able to "reduce an issue" is a really useful skill. It will help you find problems in your own code and that of your colleagues, and will also enable you to report bugs and ask for help more effectively.

A reduced test case is a code example that demonstrates the problem in the simplest possible way, with unrelated surrounding content and styling removed. This will often mean taking the problematic code out of your layout to make a small example which only shows that code or feature.

To create a reduced test case:

1. If your markup is dynamically generated — for example via a CMS — make a static version of the output that shows the problem. A code sharing site like CodePen is useful for hosting reduced test cases, as then they are accessible online and you can easily share them with colleagues. You could start by doing View Source on the page and copying the HTML into CodePen, then grab any relevant CSS and JavaScript and include it too. After that, you can check whether the issue is still evident.
2. If removing the JavaScript does not make the issue go away, don't include the JavaScript. If removing the JavaScript *does* make the issue go away, then remove as much JavaScript as you can, leaving in whatever causes the issue.
3. Remove any HTML that does not contribute to the issue. Remove components or even main elements of the layout. Again, try to get down to the smallest amount of code that still shows the issue.
4. Remove any CSS that doesn't impact the issue.

In the process of doing this, you may discover what is causing the problem, or at least be able to turn it on and off by removing something specific. It is worth adding some comments to your code as you discover things. If you need to ask for help, they will show the person helping you what you have already tried. This may well give you enough information to be able to search for likely problems and workarounds.

If you are still struggling to fix the problem then having a reduced test case gives you something to ask for help with, by posting to a forum, or showing to a co-worker. You are much more likely to get help if you can show that you have done the work of reducing the problem and identifying exactly where it happens, before asking for help. A more experienced developer might be able to quickly spot the problem and point you in the right direction, and even if not, your reduced test case will enable them to have a quick look and hopefully be able to offer at least some help.

In the instance that your problem is actually a bug in a browser, then a reduced test case can also be used to file a bug report with the relevant browser vendor (e.g. on Mozilla's bugzilla site).

As you become more experienced with CSS, you will find that you get faster at figuring out issues. However, even the most experienced of us sometimes find ourselves wondering what on earth is going on. Taking a methodical approach, making a reduced test case, and explaining the issue to someone else will usually result in a fix being found.

Summary
-------

So there we have it: an introduction to debugging CSS, which should give you some useful skills to count on when you start to debug CSS and other types of code later on in your career.

In the last article of this module, we'll take a look at how to organize your CSS.

* Previous
* Overview: Building blocks
* Next


Backgrounds and borders - Learn web development

Backgrounds and borders
=======================

* Previous
* Overview: Building blocks
* Next

In this lesson, we will take a look at some of the creative things you can do with CSS backgrounds and borders. From adding gradients, background images, and rounded corners, backgrounds and borders are the answer to a lot of styling questions in CSS.

|  |  |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
 working with files, HTML basics (study
 Introduction to HTML), and an idea of how CSS works (study
 CSS first steps.)
  |
| Objective: | To learn how to style the background and border of boxes. |

Styling backgrounds in CSS
--------------------------

The CSS `background` property is a shorthand for a number of background longhand properties that we will meet in this lesson. If you discover a complex background property in a stylesheet, it might seem a little hard to understand as so many values can be passed in at once.

```css
.box {
  background:
    linear-gradient(
        105deg,
        rgb(255 255 255 / 20%) 39%,
        rgb(51 56 57 / 100%) 96%
      ) center center / 400px 200px no-repeat,
    url(big-star.png) center no-repeat,
    rebeccapurple;
}
```

We'll return to how the shorthand works later in the tutorial, but first let's have a look at the different things you can do with backgrounds in CSS, by looking at the individual background properties.

### Background colors

The `background-color` property defines the background color on any element in CSS. The property accepts any valid `<color>`. A `background-color` extends underneath the content and padding box of the element.

In the example below, we have used various color values to add a background color to the box, a heading, and a `<span>` element.

**Play around with these, using any available <color> value.**

### Background images

The `background-image` property enables the display of an image in the background of an element. In the example below, we have two boxes — one has a background image which is larger than the box (balloons.jpg), the other has a small image of a single star (star.png).

This example demonstrates two things about background images. By default, the large image is not scaled down to fit the box, so we only see a small corner of it, whereas the small image is tiled to fill the box.

**If you specify a background color in addition to a background image then the image displays on top of the color. Try adding a `background-color` property to the example above to see that in action.**

#### Controlling background-repeat

The `background-repeat` property is used to control the tiling behavior of images. The available values are:

* `no-repeat` — stop the background from repeating altogether.
* `repeat-x` — repeat horizontally.
* `repeat-y` — repeat vertically.
* `repeat` — the default; repeat in both directions.

**Try these values out in the example below. We have set the value to `no-repeat` so you will only see one star. Try out the different values — `repeat-x` and `repeat-y` — to see what their effects are.**

#### Sizing the background image

The *balloons.jpg* image used in the initial background images example, is a large image that was cropped due to being larger than the element it is a background of. In this case we could use the `background-size` property, which can take `<length>` or `<percentage>` values, to size the image to fit inside the background.

You can also use keywords:

* `cover` — the browser will make the image just large enough so that it completely covers the box area while still retaining its aspect ratio. In this case, part of the image is likely to end up outside the box.
* `contain` — the browser will make the image the right size to fit inside the box. In this case, you may end up with gaps on either side or on the top and bottom of the image, if the aspect ratio of the image is different from that of the box.

In the example below I have used the *balloons.jpg* image along with length units to size it inside the box. You can see this has distorted the image.

Try the following.

* Change the length units used to modify the size of the background.
* Remove the length units and see what happens when you use `background-size: cover` or `background-size: contain`.
* If your image is smaller than the box, you can change the value of `background-repeat` to repeat the image.

#### Positioning the background image

The `background-position` property allows you to choose the position in which the background image appears on the box it is applied to. This uses a coordinate system in which the top-left-hand corner of the box is `(0,0)`, and the box is positioned along the horizontal (`x`) and vertical (`y`) axes.

**Note:** The default `background-position` value is `(0,0)`.

The most common `background-position` values take two individual values — a horizontal value followed by a vertical value.

You can use keywords such as `top` and `right` (look up the others on the `background-position` page):

```css
.box {
  background-image: url(star.png);
  background-repeat: no-repeat;
  background-position: top center;
}
```

And `lengths`, and `percentages`:

```css
.box {
  background-image: url(star.png);
  background-repeat: no-repeat;
  background-position: 20px 10%;
}
```

You can also mix keyword values with lengths or percentages, in which case the first value must refer to the horizontal position or offset and the second vertical. For example:

```css
.box {
  background-image: url(star.png);
  background-repeat: no-repeat;
  background-position: 20px top;
}
```

Finally, you can also use a 4-value syntax in order to indicate a distance from certain edges of the box — the length unit, in this case, is an offset from the value that precedes it. So in the CSS below we are positioning the background 20px from the top and 10px from the right:

```css
.box {
  background-image: url(star.png);
  background-repeat: no-repeat;
  background-position: top 20px right 10px;
}
```

**Use the example below to play around with these values and move the star around inside the box.**

**Note:** `background-position` is a shorthand for `background-position-x` and `background-position-y`, which allow you to set the different axis position values individually.

### Gradient backgrounds

A gradient — when used for a background — acts just like an image and is also set by using the `background-image` property.

You can read more about the different types of gradients and things you can do with them on the MDN page for the `<gradient>` data type. A fun way to play with gradients is to use one of the many CSS Gradient Generators available on the web, such as this one. You can create a gradient then copy and paste out the source code that generates it.

Try some different gradients in the example below. In the two boxes respectively, we have a linear gradient that is stretched over the whole box, and a radial gradient with a set size, which therefore repeats.

### Multiple background images

It is also possible to have multiple background images — you specify multiple `background-image` values in a single property value, separating each one with a comma.

When you do this you may end up with background images overlapping each other. The backgrounds will layer with the last listed background image at the bottom of the stack, and each previous image stacking on top of the one that follows it in the code.

**Note:** Gradients can be happily mixed with regular background images.

The other `background-*` properties can also have comma-separated values in the same way as `background-image`:

```css
background-image: url(image1.png), url(image2.png), url(image3.png),
  url(image4.png);
background-repeat: no-repeat, repeat-x, repeat;
background-position:
  10px 20px,
  top right;
```

Each value of the different properties will match up to the values in the same position in the other properties. Above, for example, `image1`'s `background-repeat` value will be `no-repeat`. However, what happens when different properties have different numbers of values? The answer is that the smaller numbers of values will cycle — in the above example there are four background images but only two `background-position` values. The first two position values will be applied to the first two images, then they will cycle back around again — `image3` will be given the first position value, and `image4` will be given the second position value.

**Let's play. In the example below I have included two images. To demonstrate the stacking order, try switching which background image comes first in the list. Or play with the other properties to change the position, size, or repeat values.**

### Background attachment

Another option we have available for backgrounds is specifying how they scroll when the content scrolls. This is controlled using the `background-attachment` property, which can take the following values:

* `scroll`: causes the element's background to scroll when the page is scrolled. If the element content is scrolled, the background does not move. In effect, the background is fixed to the same position on the page, so it scrolls as the page scrolls.
* `fixed`: causes an element's background to be fixed to the viewport so that it doesn't scroll when the page or element content is scrolled. It will always remain in the same position on the screen.
* `local`: fixes the background to the element it is set on, so when you scroll the element, the background scrolls with it.

The `background-attachment` property only has an effect when there is content to scroll, so we've made a demo to demonstrate the differences between the three values — have a look at background-attachment.html (also see the source code here).

### Using the background shorthand property

As I mentioned at the beginning of this lesson, you will often see backgrounds specified using the `background` property. This shorthand lets you set all of the different properties at once.

If using multiple backgrounds, you need to specify all of the properties for the first background, then add your next background after a comma. In the example below we have a gradient with a size and position, then an image background with `no-repeat` and a position, then a color.

There are a few rules that need to be followed when writing background image shorthand values, for example:

* A `background-color` may only be specified after the final comma.
* The value of `background-size` may only be included immediately after `background-position`, separated with the '/' character, like this: `center/80%`.

Take a look at the MDN page for `background` to see all of the considerations.

### Accessibility considerations with backgrounds

When placing text on top of a background image or color, you should take care that you have enough contrast for the text to be legible for your visitors. If specifying an image, and if text will be placed on top of that image, you should also specify a `background-color` that will allow the text to be legible if the image does not load.

Screen readers cannot parse background images; therefore, they should be purely decoration. Any important content should be part of the HTML page and not contained in a background.

Borders
-------

When learning about the Box Model, we discovered how borders affect the size of our box. In this lesson we will look at how to use borders creatively. Typically when we add borders to an element with CSS we use a shorthand property that sets the color, width, and style of the border in one line of CSS.

We can set a border for all four sides of a box with `border`:

```css
.box {
  border: 1px solid black;
}
```

Or we can target one edge of the box, for example:

```css
.box {
  border-top: 1px solid black;
}
```

The individual properties for these shorthands would be:

```css
.box {
  border-width: 1px;
  border-style: solid;
  border-color: black;
}
```

And for the longhands:

```css
.box {
  border-top-width: 1px;
  border-top-style: solid;
  border-top-color: black;
}
```

**Note:** These top, right, bottom, and left border properties also have mapped *logical* properties that relate to the writing mode of the document (e.g. left-to-right or right-to-left text, or top-to-bottom). We'll be exploring these in the next lesson, which covers handling different text directions.

There are a variety of styles that you can use for borders. In the example below, we have used two different border styles for the box and two different border styles for the heading. Play with the border style, width, and color to see how borders work.

### Rounded corners

Rounding corners on a box is achieved by using the `border-radius` property and associated longhands which relate to each corner of the box. Two lengths or percentages may be used as a value, the first value defining the horizontal radius, and the second the vertical radius. In a lot of cases, you will only pass in one value, which will be used for both.

For example, to make all four corners of a box have a 10px radius:

```css
.box {
  border-radius: 10px;
}
```

Or to make the top right corner have a horizontal radius of 1em, and a vertical radius of 10%:

```css
.box {
  border-top-right-radius: 1em 10%;
}
```

We have set all four corners in the example below and then changed the values for the top right corner to make it different. You can play with the values to change the corners. Take a look at the property page for `border-radius` to see the available syntax options.

Test your skills!
-----------------

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Backgrounds and borders.

Summary
-------

We have covered quite a lot here, and you can see that there is quite a lot to adding a background or a border to a box. Do explore the different property pages if you want to find out more about any of the features we have discussed. Each page on MDN has more examples of usage for you to play with and enhance your knowledge.

In the next article, we'll find out how the Writing Mode of your document interacts with your CSS. What happens when the text does not flow from left to right?

* Previous
* Overview: Building blocks
* Next