Skip to content

Instantly share code, notes, and snippets.

@victorsharamet
Last active August 16, 2023 22:36
Show Gist options
  • Select an option

  • Save victorsharamet/d56c99baa0b2bf1b4927847c50af3df4 to your computer and use it in GitHub Desktop.

Select an option

Save victorsharamet/d56c99baa0b2bf1b4927847c50af3df4 to your computer and use it in GitHub Desktop.
Codeacademy || Learn CSS

Codeacademy || Learn CSS

Table of Contents


CSS, or Cascading Style Sheets, is a language that web developers use to style the HTML content on a web page.

<head>
	<link href="style.css" type="text/css" rel="stylesheet">
</head>

To style an HTML element, you can add the style attribute directly to the opening tag. After you add the attribute, you can set it equal to the CSS style(s) you'd like applied to that element.

<p style="color: red;">I'm learning to code!</p>

If you'd like to add more than one style with inline styles, simply keep adding to the style attribute. Make sure to end the styles with a semicolon (;).

<p style="color: red; font-size: 20px;">I'm learning to code!</p>

CSS can be written between opening and closing <style> tags. To use the <style> element, it must be placed inside of the <head>element.

<head>
  <style>
    p {
      color: red;
      font-size: 20px;
    }
  </style>
</head>

With a CSS file, you can write all the CSS code needed to style a page without sacrificing the readability and maintainability of your HTML file.

The <link> element must be placed within the head of the HTML file. It is a self-closing tag and requires the following three attributes:

  1. href — like the anchor element, the value of this attribute must be the address, or path, to the CSS file.
  2. type — this attribute describes the type of document that you are linking to (in this case, a CSS file). The value of this attribute should be set to text/css.
  3. rel — this attribute describes the relationship between the HTML file and the CSS file. Because you are linking to a stylesheet, the value should be set to stylesheet.
<link href="https://www.codecademy.com/stylesheets/style.css" type="text/css" rel="stylesheet">

If the CSS file is stored in the same directory as your HTML file, then you can specify a relative path instead of a URL, like so:

<link href="./style.css" type="text/css" rel="stylesheet">

A tag name is the word (or character) between HTML angle brackets. For example, in HTML, the tag for a paragraph element is <p>. The CSS syntax for selecting <p> elements is:

p {

}

In the example above, all paragraph elements will be selected using a CSS selector.

HTML elements can have more than just a tag name; they can also have attributes. One common attribute is the class attribute. It's also possible to select an element by its class attribute.

<p class="brand">Sole Shoe Company</p>

To select this element using CSS, we could use the following CSS selector:

.brand {

}

It's possible to add more than one class name to an HTML element's class attribute. We can add multiple classes to an HTML element's classattribute by separating them with a space. For instance, perhaps there's a heading element that needs to be green and bold. You could write two CSS rules like so:

.green {
  color: green;
}
.bold {
  font-weight: bold;
}

Then, you could include both of these classes on one HTML element like this:

<h1 class="green bold"> ... </h1>

If an HTML element needs to be styled uniquely (no matter what classes are applied to the element), we can add an ID to the element. To add an ID to an element, the element needs an id attribute:

<h1 id="large-title"> ... </h1>

Then, CSS can select HTML elements by their id attribute. To select an id element, CSS prepends the id name with a hashtag (#). For instance, if we wanted to select the HTML element in the example above, it would look like this:

#large-title {

}

The id name is large-title, therefore the CSS selector for it is #large-title. While classes are meant to be used many times, an ID is meant to style only one element. As we'll learn in the next exercise, IDs override the styles of tags and classes. Since IDs override class and tag styles, they should be used sparingly and only on elements that need to always appear the same.

Specificity is the order by which the browser decides which CSS styles will be displayed. A best practice in CSS is to style elements while using the lowest degree of specificity, so that if an element needs a new style, it is easy to override.

IDs are the most specific selector in CSS, followed by classes, and finally, tags. For example, consider the following HTML and CSS:

<h1 class="headline">Breaking News</h1>
h1 {
  color: red;
}
.headline {
  color: firebrick;
}

In the example code above, the color of the heading would be set to firebrick, as the class selector is more specific than the tag selector. If an ID attribute (and selector) were added to the code above, the styles within the ID selector's body would override all other styles for the heading. The only way to override an ID is to add another ID with additional styling.

When writing CSS rules, it's possible to require an HTML element to have two or more CSS selectors at the same time. This is done by combining multiple selectors, which we will refer to as chaining. For instance, if there was a .special class for h1elements, the CSS would look like:

h1.special {

}

The code above would select only the h1elements that have a class of special. If a pelement also had a class of special, the rule in the example would not style the paragraph.

<ul class='main-list'>
  <li> ... </li>
  <li> ... </li>
  <li> ... </li>
</ul>

The nested <li> elements are selected with the following CSS:

.main-list li {

}

In the example above, .main-list selects the .main-list element (the unordered list element). The nested <li> are selected by adding li to the selector, separated by a space, resulting in .main-list li as the final selector (note the space in the selector).

p {
  color: blue;
}
.main p {
  color: red;
}

Both of these CSS rules define what a pelement should look like. Since .main p has a class and a p tag as its selector, only the pelements inside the .main element will appear red. This occurs despite there being another more general rule that states p elements should be blue.

here is one thing that is even more specific than IDs: !important. !important can be applied to specific attributes instead of full rules. It will override any style no matter how specific it is. As a result, it should almost never be used. Once !important is used, it is very hard to override.

The syntax of !important in CSS looks like this:

p {
  color: blue !important;
}
.main p {
  color: red;
}

Since !important is used on the p selector’s color attribute, all p elements will appear blue, even though there is a more specific .main p selector that sets the color attribute to red.

If you ever see !important used (or are ever tempted to use it yourself) we strongly recommend reorganizing your CSS. Making your CSS more flexible will typically fix the immediate problem and make your code more maintainable in the long run.

In order to make CSS more concise, it's possible to add CSS styles to multiple CSS selectors all at once. This prevents writing repetitive code.

For instance, the following code has repetitive style attributes:

h1 {
  font-family: Georgia;
}
.menu {
  font-family: Georgia;
}

Instead of writing font-family: Georgia twice for two selectors, we can separate the selectors by a comma to apply the same style to both, like this:

h1, 
.menu {
  font-family: Georgia;
}

To style an HTML element using CSS, you need to write a CSS declaration inside the body of a CSS selector.

h1 {
  color: blue;
}

The example above selects the <h1> element. Inside of the selector's body, we typed color: blue. This line is referred to as a CSS declaration. CSS declarations consist of a property and a value.

Property — the property you'd like to style of that element (i.e., size, color, etc.).

Value — the value of the property (i.e., 18px for size, blue for color, etc.).

In the example above, the property is colorand the value is blue. The property and value are separated by a colon (:). A semicolon (;) should always be used at the end of a declaration.

Finally, the entire snippet of code in the example above is known as a CSS rule or rule set. A CSS rule consists of the selector (here, h1) and all declarations inside of the selector.

Font refers to the technical term typeface, or font family. To change the typeface of text on your web page, you can use the font-family property.

h1 {
  font-family: Garamond;
}

In the example above, the font family for all main heading elements has been set to Garamond.

When setting typefaces on a web page, keep the following points in mind:

  1. The font specified in a stylesheet must be installed on a user's computer in order for that font to display when a user visits the web page.
  2. The default typeface for all HTML elements is Times New Roman. You may be familiar with this typeface if you have ever used a formatted word processor. If no font-family attribute is defined, the page will appear in Times New Roman.
  3. It's a good practice to limit the number of typefaces used on a web page to 2 or 3. This helps the page load faster in some cases and is usually a good design decision.
  4. When the name of a typeface consists of more than one word, it's a best practice to enclose the typeface's name in quotes, like so:
h1 {
  font-family: "Courier New";
}

Changing the typeface isn't the only way to customize text. Often times, different sections of a web page are highlighted by modifying the font size.

To change the size of text on your web page, you can use the font-size property.

p {
  font-size: 18px;
}

In the example above, the font-size of all paragraphs was set to 18px. px means pixels and is a way to measure font size.

In CSS, the font-weight property controls how bold or thin text appears.

p {
  font-weight: bold;
}

In the example above, all paragraphs on the web page would appear bolded.

The font-weight property has a another value: normal. Why does it exist?

If we wanted all text on a web page to appear bolded, we could select all text elements and change their font weight to bold. If a certain section of text was required to appear normal, however, we could set the font weight of that particular element to normal, essentially shutting off bold for that element.

No matter how much styling is applied to text (typeface, size, weight, etc.), text always appears on the left side of the browser.

To align text we can use the text-alignproperty. The text-align property will align text to the element that holds it, otherwise known as its parent.

h1 {
  text-align: right;
}

The text-align property can be set to one of the following three values:

  1. left — aligns text to the left hand side of its parent element, which in this case is the browser.
  2. center — centers text inside of its parent element.
  3. right — aligns text to the right hand side of its parent element.

Color can affect the following design aspects:

  • Foreground color
  • Background color

Foreground color is the color that an element appears in. For example, when a heading is styled to appear green, the foreground color of the heading has been styled.

Conversely, when a heading is styled so that its background appears yellow, the background color of the heading has been styled.

In CSS, these two design aspects can be styled with the following two properties:

  • color: this property styles an element's foreground color
  • background-color: this property styles an element's background color
h1 {
  color: red;
  background-color: blue;
}

Opacity is the measure of how transparent an element is. It's measured from 0 to 1, with 1 representing 100%, or fully visible and opaque, and 0 representing 0%, or fully invisible.

Opacity can be used to make elements fade into others for a nice overlay effect. To adjust the opacity of an element, the syntax looks like this:

.overlay {
  opacity: 0.5;
}

In the example above, the .overlay element would be 50% visible, letting whatever is positioned behind it show through.

CSS has the ability to change the background of an element. One option is to make the background of an element an image. This is done through the CSS property background-image. Its syntax looks like this:

.main-banner {
  background-image: url("https://www.example.com/image.jpg");
}
  1. The background-image property will set the element's background to display an image.
  2. The value provided to background-image is a url. The url should be a url to an image. The url can be a file within your project, or it can be a link to an external site. To link to an image inside an existing project, you must provide a relative file path. If there was an image folder in the project, with an image named mountains.jpg, the relative file path would look like:
.main-banner {
  background-image: url("images/mountains.jpg");
}

Browsers load HTML elements with default position values. This often leads to an unexpected and unwanted user experience, while limiting the views you can create. All elements on a web page are interpreted by the browser as "living" inside of a box. This is what is meant by the box model. For example, when you change the background color of an element, you change the background color of its entire box.

The box model comprises the set of properties which define parts of an element that take up space on a web page. The model includes the content area's size (width and height) and the element's padding, border, and margin. The properties include:

  1. Width and height — specifies the width and height of the content area.
  2. Padding — specifies the amount of space between the content area and the border.
  3. Border — specifies the thickness and style of the border surrounding the content area and padding.
  4. Margin — specifies the amount of space between the border and the outside edge of the element.

The Box Model

An element's content has two dimensions: a height and a width. By default, the dimensions of an HTML box are set to hold the raw contents of the box.

The CSS height and width properties can be used to modify these default dimensions.

p {
  height: 80px;
  width: 240px;
}

In this example, the height and width of paragraph elements are set to 80 pixels and 240 pixels, respectively — the px in the code above stands for pixels.

A border is a line that surrounds an element, like a frame around a painting. Borders can be set with a specific width, style, and color.

  1. width — The thickness of the border. A border's thickness can be set in pixels or with one of the following keywords: thin, medium, or thick.
  2. style — The design of the border. Web browsers can render any of 10 different styles. Some of these styles include: none, dotted, and solid.
  3. color — The color of the border. Web browsers can render colors using a few different formats, including 140 built-in color keywords.
p {
  border: 3px solid coral;
}

In the example above, the border has a width of 3 pixels, a style of solid and a color of coral. All three properties are set in one line of code.

The default border is medium none color, where color is the current color of the element. If width, style, or color are not set in the CSS file, the web browser assigns the default value for that property.

p.content-header {
  height: 80px;
  width: 240px;
  border: solid coral;
}

In this example, the border style is set to solid and the color is set to coral. The width is not set, so it defaults to medium.

Ever since we revealed the borders of boxes, you may have noticed that the borders highlight the true shape of an element's box: square. Thanks to CSS, a border doesn't have to be square.

You can modify the corners of an element's border box with the border-radius property.

div.container {
  border: 3px solid rgb(22, 77, 100);
  border-radius: 5px;
}

The code in the example above will set all four corners of the border to a radius of 5 pixels (i.e. the same curvature that a circle with radius 5 pixels would have).

You can create a border that is a perfect circle by setting the radius equal to the height of the box, or to 100%.

div.container {
  height: 60px;
  width: 60px;
  border: 3px solid rgb(22, 77, 100);
  border-radius: 100%;
}

The code in the example above creates a <div>that is a perfect circle.

The space between the contents of a box and the borders of a box is known as padding. Padding is like the space between a picture and the frame surrounding it. In CSS, you can modify this space with the padding property.

p.content-header {
  border: 3px solid coral;
  padding: 10px;
}

The code in this example puts 10 pixels of space between the content of the paragraph (the text) and the borders, on all four sides.

The padding property is often used to expand the background color and make content look less cramped.

If you want to be more specific about the amount of padding on each side of a box's content, you can use the following properties:

  1. padding-top
  2. padding-right
  3. padding-bottom
  4. padding-left

Each property affects the padding on only one side of the box's content, giving you more flexibility in customization.

p.content-header {
  border: 3px solid fuschia;
  padding-bottom: 10px;
}

In the example above, only the bottom side of the paragraph's content will have a padding of 10 pixels.

Another implementation of the paddingproperty lets you specify exactly how much padding there should be on each side of the content in a single declaration.

p.content-header {
  border: 3px solid grey;
  padding: 6px 11px 4px 9px;
}

In the example above, the four values 6px 11px 4px 9px correspond to the amount of padding in a clockwise rotation. In order, it specifies the amount of padding on the top (6 pixels), right (11 pixels), bottom (4 pixels), and left (9 pixels) sides of the content.

When using this implementation of the padding property, we must specify a padding value for all four sides of the element.

However, if the top and bottom values for padding will equal each other, and the left and right values for padding will also equal each other, you can use the following shortcut:

p.content-header {
  padding: 5px 10px;
}

The first value, 5px, sets the padding value for the top and bottom sides of the content. The second value, 10px, sets the padding value for the left and right sides of the content.

So far you've learned about the following components of the box model: content, borders, and padding. The fourth and final component of the box model is margin.

Margin refers to the space directly outside of the box. The margin property is used to specify the size of this space.

p {
  border: 1px solid aquamarine;
  margin: 20px;
}

The code in the example above will place 20 pixels of space on the outside of the paragraph's box on all four sides. This means that other HTML elements on the page cannot come within 20 pixels of the paragraph's border.

If you want to be even more specific about the amount of margin on each side of a box, you can use the following properties:

  1. margin-top
  2. margin-right
  3. margin-bottom
  4. margin-left

Each property affects the margin on only one side of the box, providing more flexibility in customization.

p {
  border: 3px solid DarkSlateGrey;
  margin-right: 15px;
}

In the example above, only the right side of the paragraph's box will have a margin of 15 pixels. It's common to see margin values used for a specific side of an element.

A similar implementation of the margin property is used to specify exactly how much margin there should be on each side of the box in a single declaration.

p {
  margin: 6px 10px 5px 12px;
}

In the example above, the four values 6px 10px 5px 12px refer to the amount of margin around the box in a clockwise rotation. In order, it specifies the amount of margin on the top (6 pixels), right (10 pixels), bottom (5 pixels), and left (12 pixels) sides of the box.

When using this implementation of the margin property, the margin value must be specified for all four sides of the box.

Just like the padding shortcut, when you're certain that the top and bottom values for margin will equal each other, and that the left and right values for margin will also equal each other, you can use the following shortcut:

p {
  margin: 6px 12px;
}

The first value, 6px, sets a margin value for the top and bottom of the box. The second value, 12px, sets a margin value for the left and right sides of the box.

The margin property also lets you center content. However, you must follow a few syntax requirements. Take a look at the following example:

div {
  margin: 0 auto;
}

In the example above, margin: 0 auto; will center the divs in their containing elements. The 0 sets the top and bottom margins to 0 pixels. The auto value instructs the browser to adjust the left and right margins until the element is centered within its containing element.

The div elements in the example above should center within an element that fills the page, but this doesn't occur. Why?

In order to center an element, a width must be set for that element. Otherwise, the width of the div will be automatically set to the full width of its containing element, like the <body>, for example. It's not possible to center an element that takes up the full width of the page.

div.headline {
  width: 400px;
  margin: 0 auto;
}

In the example above, the width of the div is set to 400 pixels, which is less than the width of most screens. This will cause the div to center within a containing element that is greater than 400 pixels wide.

As you have seen, padding is space added inside an element's border, while margin is space added outside an element's border. One additional difference is that top and bottom margins, also called vertical margins, collapse, while top and bottom padding does not.

Horizontal margins (left and right), like padding, are always displayed and added together. For example, if two divs with ids #div-one and #div-two, are next to each other, they will be as far apart as the sum of their adjacent margins.

#img-one {
  margin-right: 20px;
}

#img-two {
  margin-left: 20px;
}

In this example, the space between the #img-one and #img-two borders is 40 pixels. The right margin of #img-one (20px) and the left margin of #img-two (20px) add to make a total margin of 40 pixels.

Unlike horizontal margins, vertical margins do not add. Instead, the larger of the two vertical margins sets the distance between adjacent elements.

#img-one {
  margin-bottom: 30px;
}

#img-two {
  margin-top: 20px;
}

In this example, the vertical margin between the #img-one and #img-two elements is 30 pixels. Although the sum of the margins is 50 pixels, the margin collapses so the spacing is only dependent on the #img-one bottom margin.

It may be helpful to think of collapsing vertical margins as a short person trying to push a taller person. The tall person has longer arms and can easily push the short person, while the person with short arms cannot reach the person with long arms.

Vertical Margins Collapse

Because a web page can be viewed through displays of differing screen size, the content on the web page can suffer from those changes in size. To avoid this problem, CSS offers two properties that can limit how narrow or how wide an element's box can be sized to.

  1. min-width — this property ensures a minimum width of an element's box.
  2. max-width — this property ensures a maximum width of an element's box.
p {
  min-width: 300px;
  max-width: 600px;
}

In the example above, the width of all paragraphs will not shrink below 300 pixels, nor will the width exceed 600 pixels.

Content, like text, can become difficult to read when a browser window is narrowed or expanded. These two properties ensure that content is legible by limiting the minimum and maximum widths of an element.

You can also limit the minimum and maximum height of an element.

  1. min-height — this property ensures a minimum height for an element's box.
  2. max-height — this property ensures a maximum height of an element's box.
p {
  min-height: 150px;
  max-height: 300px;
}

In the example above, the height of all paragraphs will not shrink below 150 pixels and the height will not exceed 300 pixels.

What will happen to the contents of an element's box if the max-height property is set too low? It's possible for the content to spill outside of the box, resulting in content that is not legible. You'll learn how to work around this issue in the next exercise.

All of the components of the box model comprise an element’s size. For example, an image that has the following dimensions is 364 pixels wide and 244 pixels tall.

  • 300 pixels wide
  • 200 pixels tall
  • 10 pixels padding on the left and right
  • 10 pixels padding on the top and bottom
  • 2 pixels border on the left and right
  • 2 pixels border on the top and bottom
  • 20 pixels margin on the left and right
  • 10 pixels margin on the top and bottom

The total dimensions (364px by 244px) are calculated by adding all of the vertical dimensions together and all of the horizontal dimensions together. Sometimes, these components result in an element that is larger than the parent's containing area.

How can we ensure that we can view all of an element that is larger than its parent's containing area?

The overflow property controls what happens to content that spills, or overflows, outside its box. It can be set to one of the following values:

  • hidden - when set to this value, any content that overflows will be hidden from view.
  • scroll - when set to this value, a scrollbar will be added to the element's box so that the rest of the content can be viewed by scrolling.
  • visible - when set to this value, the overflow content will be displayed outside of the containing element. Note, this is the default value.
p {
  overflow: scroll; 
}

In the example above, if any of the paragraph content overflows (perhaps a user resizes their browser window), a scrollbar will appear so that users can view the rest of the content.

The overflow property is set on a parent element to instruct a web browser how to render child elements. For example, if a div’s overflow property is set to scroll, all children of this div will display overflowing content with a scroll bar.

All major web browsers have a default stylesheet they use in the absence of an external stylesheet. These default stylesheets are known as user agent stylesheets. In this case, the term "user agent" is a technical term for the browser.

User agent stylesheets often have default CSS rules that set default values for padding and margin. This affects how the browser displays HTML elements, which can make it difficult for a developer to design or style a web page.

Many developers choose to reset these default values so that they can truly work with a clean slate.

* {
  margin: 0;
  padding: 0;
}

The code in the example above resets the default margin and padding values of all HTML elements. It is often the first CSS rule in an external stylesheet.

Note that both properties are both set to 0. When these properties are set to 0, they do not require a unit of measurement.

Elements can be hidden from view with the visibility property.

The visibility property can be set to one of the following values:

  1. hidden — hides an element.
  2. visible — displays an element.
<ul>
  <li>Explore</li>
  <li>Connect</li>
  <li class="future">Donate</li>
<ul>
.future {
  visibility: hidden;
}

In the example above, the list item with a class of future will be hidden from view in the browser.

Keep in mind, however, that users can still view the contents of the list item (e.g., Donate) by viewing the source code in their browser. Furthermore, the web page will only hide the contents of the element. It will still leave an empty space where the element is intended to display.

Note: What's the difference between display: none and visibility: hidden? An element with display: none will be completely removed from the web page. An element with visibility: hidden, however, will not be visible on the web page, but the space reserved for it will.

The box model, however, has an awkward limitation regarding box dimensions. This limitation is best illustrated with an example.

<h1>Hello World</h1>
h1 {
  border: 1px solid black;
  height: 200px;
  width: 300px;
  padding: 10px;
}

In the example above, a heading element's box has solid, black, 1 pixel thick borders. The height of the box is 200 pixels, while the width of the box is 300 pixels. A padding of 10 pixels has also been set on all four sides of the box's content.

Unfortunately, under the current box model, the border thickness and the padding will affect the dimensions of the box.

The 10 pixels of padding increases the height of the box to 220 pixels and the width to 320 pixels. Next, the 1-pixel thick border increases the height to 222 pixels and the width to 322 pixels.

Under this box model, the border thickness and padding are added to the overall dimensions of the box. This makes it difficult to accurately size a box. Over time, this can also make all of a web page's content difficult to position and manage.

Actual Rendered Width

Many properties in CSS have a default value and don't have to be explicitly set in the stylesheet.

For example, the default font-weight of text is normal, but this property-value pair is not typically specified in a stylesheet.

The same can be said about the box model that browsers assume. In CSS, the box-sizingproperty controls the type of box model the browser should use when interpreting a web page.

The default value of this property is content-box. This is the same box model that is affected by border thickness and padding.

Fortunately, we can reset the entire box model and specify a new one: border-box.

* {
  box-sizing: border-box;
}

The code in the example above resets the box model to border-box for all HTML elements. This new box model avoids the dimensional issues that exist in the former box model you learned about.

In this box model, the height and width of the box will remain fixed. The border thickness and padding will be included inside of the box, which means the overall dimensions of the box do not change.

<h1>Hello World</h1>
* {
  box-sizing: border-box;
}

h1 {
  border: 1px solid black;
  height: 200px;
  width: 300px;
  padding: 10px;
}

In the example above, the height of the box would remain at 200 pixels and the width would remain at 300 pixels. The border thickness and padding would remain entirely inside of the box.

It's that simple! In the example above, the universal selector (*) targets all elements on the web page and sets their box model to the border-box model.

Width Property

Introduction

All HTML elements are boxes made up of four components: a content container, padding, border, and margin. In our Box Model Lesson we introduce these four properties and use them to position elements on a website. If you have not taken this lesson, we recommend you do so now, before continuing.

In this article, we will introduce how Google Chrome's DevTools can be used to view the box around each element on a web page.

1. View Box Model Dimensions with DevTools

You can use Google Chrome's DevTools to view the box around every element on a web page. To do this, click View > Developer > Developer Tools and navigate to the Elements tab.

Elements Tab

In this tab you can view all of the elements on the current page. From this view, you can select the element of interest, which will open a new column on the right side of DevTools. Select the tab labeled Computed on the top of the rightmost column.

Computed Tab

The selected element's box should appear at the top of the pane. Hovering over each property of the box will cause the property to be highlighted in the web page.

If you know the element you want to inspect, going through all of the steps listed above is unnecessary. Instead, you can right click the element you want to observe and select the Inspect button. This will display DevTools on the right side of the browser with the element selected in the Elements tab. To view the element's box, you can select the Computed tab.

Exercise I: View a Website's Box Model Dimensions

Complete the following steps within the current web browser view.

  1. In a new tab navigate to the Codecademy Wikipedia page.
  2. Right click (or Ctrl and click simultaneously) the Contents navigation box displayed in the image below:

Dropdown image

  1. Select Inspect.
  2. Select the Computed tab at the top of the rightmost column.
  3. Hover over the different properties of the logo's box. The corresponding space on the web page should be highlighted when you do this.

2. Modify Box Dimensions

Now that you know how to view the box of an element we'll modify the box's values with DevTools.

To modify the values of the box double click the property value, assign it a new number, and press enter. You can also adjust the value incrementally by double clicking the value and using the up or down arrow keys.

Selecting Values

In the image above, the border on each side is set to 1 and the padding is set to 7. These values can be changed by double clicking the values in the box and assigning them new numbers, or using the up or down arrow keys on your keyboard.

Note: If you inspect an element and find that the border is set to -, adding a numerical value will not make a border appear. The border color, style, and width must be set in the CSS document in order to see the border.

Exercise II: Modify a Website's Box Model Dimensions

Pick up where you left off in Exercise 1.

  1. Double click the top padding of the element.
  2. Use the up and down arrows to adjust the element's padding. Observe how the appearance changes on the web page.
  3. Change the left margin to 200. Observe how the element's appearance changes.

Remember the changes you make in DevTools are not saved. If you are using DevTools to make adjustments to a personal project, make sure to adjust values in the HTML and CSS documents.

VIDEO ON YOUTUBE

A browser will render the elements of an HTML document that has no CSS from left to right, top to bottom, in the same order as they exist in the document. This is called the flow of elements in HTML.

In addition to the properties that it provides to style HTML elements, CSS includes properties that change how a browser positionselements. These properties specify where an element is located on a page, if the element can share lines with other elements, and other related attributes.

In this lesson, you will learn five properties for adjusting the position of HTML elements in the browser:

  • position
  • display
  • z-index
  • float
  • clear

Each of these properties will allow us to position and view elements on a web page. They can be used in conjunction with any other styling properties you may know.

Take a look at the block-level elements in the image below:

Block-level

Block-level elements like these boxes create a block the full width of their parent elements, and they prevent other elements from appearing in the same horizontal space. The boxes in the image above were created with the following CSS:

.boxes {
  width: 120px;
  height: 70px;
}

and the following HTML:

<div class="boxes"></div>
<div class="boxes"></div>

Notice the block-level elements in the image above take up their own line of space and therefore don't overlap each other. In the browser to the right you can see block-level elements also consistently appear on the left side of the browser. This is the default positionfor block-level elements.

The default position of an element can be changed by setting its position property. The position property can take one of four values:

  1. static - the default value (it does not need to be specified)
  2. relative
  3. absolute
  4. fixed

In the next few exercises, you'll learn about the values in items 2, 3, and 4 above. For now, it's important to understand that if you favor the default position of an HTML element, you don't need to set its position property.

One way to modify the default position of an element is by setting its position property to relative.

This value allows you to position an element relative to its default static position on the web page.

.box-bottom {
  background-color: DeepSkyBlue;
  position: relative;
}

Although the code in the example above instructs the browser to expect a relative positioning of the div, it does not specify where the div should be positioned on the page.

.box-bottom {
  background-color: DeepSkyBlue;
  position: relative;
  top: 20px;
  left: 50px;
}

In the example above, the <div> has been positioned using two of the four offset properties. The valid offset properties are:

  1. top - moves the element down.
  2. bottom - moves the element up.
  3. left - moves the element right.
  4. right - moves the element left.

In the example above, the <div> will be moved down 20 pixels and to the right 50 pixels from its default static position. The image below displays the new position of the box. The dotted line represents where the statically positioned (default) box was positioned.

New Box Position

Units for offset properties can be specified in pixels, ems, or percentages. Note that offset properties will not work if the value of the element's position property is the default static.

Another way of modifying the position of an element is by setting its position to absolute.

When an element's position is set to absolute all other elements on the page will ignore the element and act like it is not present on the page. The element will be positioned relative to its closest positioned parent element.

.box-bottom {
  background-color: DeepSkyBlue;
  position: absolute;
  top: 20px;
  left: 50px;
}

In the example above, the .box-bottom <div> will be moved down and right from the top left corner of the view. If offset properties weren't specified, the top box would be entirely covered by the bottom box. Take a look at the gif below:

GIF

The bottom box in this image (colored blue) is displaced from the top left corner of its container. It is 20 pixels lower and 50 pixels to the right of the top box.

In the next exercise, we will compare the scrolling of absolute elements with fixed elements.

When an element's position is set to absolute, as in the last exercise, the element will scroll with the rest of the document when a user scrolls.

We can fix an element to a specific position on the page (regardless of user scrolling) by setting its position to fixed.

.box-bottom {
  background-color: DeepSkyBlue;
  position: fixed;
  top: 20px;
  left: 50px;
}

In the example above, the .box-bottom <div> will remain fixed to its position no matter where the user scrolls on the page, like in the image below:

GIF

This technique is often used for navigation bars on a web page.

When boxes on a web page have a combination of different positions, the boxes (and therefore, their content) can overlap with each other, making the content difficult to read or consume.

.box-top {
  background-color: Aquamarine;
}

.box-bottom {
  background-color: DeepSkyBlue;
  position: absolute;
  top: 20px;
  left: 50px;
}

In the example above, the .box-bottom <div> ignores the .box-top <div> and overlaps it as a user scrolls.

The z-index property controls how far "back" or how far "forward" an element should appear on the web page when elements overlap. This can be thought of the depth of elements, with deeper elements appearing behind shallower elements.

The z-index property accepts integer values. Depending on their values, the integers instruct the browser on the order in which elements should be displayed on the web page.

.box-top {
  background-color: Aquamarine;
  position: relative;
  z-index: 2;
}

.box-bottom {
  background-color: DeepSkyBlue;
  position: absolute;
  top: 20px;
  left: 50px;
  z-index: 1;
}

In the example above, we set the .box-top position to relative and the z-index to 2. We changed position to relative, because the z-index property does not work on static elements. The z-index of 2 moves the .box-top element forward, because it is greater than the .box-bottom z-index, 1. See the example image below:

Z-index Example

In the image above, you can see the top box is moved in front of the bottom box.

Every HTML element has a default display value that dictates if it can share horizontal space with other elements. Some elements fill the entire browser from left to right regardless of the size of their content. Other elements only take up as much horizontal space as their content requires and can be directly next to other elements.

In this lesson, we’ll cover three values for the display property: inline, block, and inline-block.

The default display for some tags, such as <em>, <strong>, and <a> is called inline.

Inline elements have a box that wraps tightly around their content, only taking up the amount of space necessary to display their content and not requiring a new line after each element. The height and width of these elements cannot be specified in the CSS document. For example, the text of an anchor tag (<a>) will, by default, be displayed on the same line as the surrounding text, and it will only be as wide as necessary to contain its content. Inline elements cannot be altered in size with the height or width CSS properties.

To learn more about <em>inline</em> elments, read <a href="#">MDN documentation</a>.

In the example above, the <em> element is inline, because it displays its content on the same line as the content surrounding it, including the anchor tag. This example will display:

To learn more about inline elements, click MDN documentation.

The CSS display property provides the ability to make any element an inline element. This includes elements that are not inline by default such as paragraphs, divs, and headings.

h1 {
  display: inline;
}

The CSS in the example above will change the display of all <h1> elements to inline. The browser will render <h1> elements on the same line as other inline elements immediately before or after them (if there are any).

Some elements are not displayed in the same line as the content around them. These are called block-level elements. These elements fill the entire width of the page by default, but their width property can also be set. Unless otherwise specified, they are the height necessary to accommodate their content.

Elements that are block-level by default include all levels of heading elements (<h1> through <h6>), <p>, <div> and <footer>. For a complete list of block level elements, visit the MDN documentation.

strong {
  display: block;
}

In the example above, all <strong> elements will be displayed on their own line, with no content directly on either side of them even though their contents may not fill the width of most computer screens.

The third value for the display property is inline-block. Inline-block display combines features of both inline and block elements. Inline-block elements can appear next to each other and we can specify their dimensions using the width and height properties. Images are the best example of default inline-block elements.

For example, <div>s in the CSS below will be displayed on the same line and with the specified dimensions:

<div class="rectangle">
  <p>I’m a rectangle!</p>
</div>
<div class="rectangle">
  <p>So am I!</p>
</div>
<div class="rectangle">
  <p>Me three!</p>
</div>
.rectangle {
  display: inline-block;
  width: 200px;
  height: 300px;
}

In the example above, there are three rectangular divs that each contain a paragraph of text. The .rectangle <div>s will all appear inline (provided there is enough space from left to right) with a width of 200 pixels and height of 300 pixels, even though the text inside of them may not require 200 pixels by 300 pixels of space.

So far, you've learned how to specify the exact position of an element using offset properties. If you're simply interested in moving an element as far left or as far right as possible on the page, you can use the float property.

The float property can be set to one of two values:

  1. left - this value will move, or float, elements as far left as possible.
  2. right - this value will move elements as far right as possible.
.boxes {
  width: 120px;
  height: 70px;
}

.box-bottom {
  background-color: DeepSkyBlue;
  float: right;
}

In the example above, we float the .box-bottom element to the right. This works for static and relative positioned elements. See the result of the code below:

Float Example

Floated elements must have a width specified, as in the example above. Otherwise, the element will assume the full width of its containing element, and changing the float value will not yield any visible results.

The float property can also be used to float multiple elements at once. However, when multiple floated elements have different heights, it can affect their layout on the page. Specifically, elements can "bump" into each other and not allow other elements to properly move to the left or right.

The clear property specifies how elements should behave when they bump into each other on the page. It can take on one of the following values:

  1. left — the left side of the element will not touch any other element within the same containing element.
  2. right — the right side of the element will not touch any other element within the same containing element.
  3. both — neither side of the element will touch any other element within the same containing element.
  4. none — the element can touch either side.
div {
  width: 200px;
  float: left;
}

div.special {
  clear: left;
}

In the example above, all <div>s on the page are floated to the left side. The element with class special did not move all the way to the left because a taller <div> blocked its positioning. By setting its clear property to left, the special <div> will be moved all the way to the left side of the page.

CSS supports a wide variety of colors. These include named colors, like blue, black, and LimeGreen, along with colors described by a numeric value. Using a numeric system allows us to take advantage of the whole spectrum of colors that browsers support. In this lesson, we're going to explore all the color options CSS offers.

Colors in CSS can be described in three different ways:

  • Named colors — English words that describe colors, also called keyword colors
  • RGB — numeric values that describe a mix of red, green, and blue
  • HSL — numeric values that describe a mix of hue, saturation, and lightness

Before discussing the specifics of color, it's important to make two distinctions about color. Color can affect the following design aspects:

  1. The foreground color
  2. The background color

Foreground color is the color that an element appears in. For example, when a heading is styled to appear green, the foreground colorof the heading has been styled.

Conversely, when a heading is styled so that its background appears yellow, thebackground color of the heading has been styled

In CSS, these two design aspects can be styled with the following two properties:

  1. color - this property styles an element's foreground color.
  2. background-color - this property styles an element's background color.

One syntax that we can use to specify colors is called hexadecimal. Colors specified using this system are called hex colors. A hex color begins with a hash character (#) which is followed by three or six characters. The characters represent values for red, blue and green.

The hexadecimal number system has 16 digits (0-15) instead of 10 (0-9) like you are used to. To represent 10-15, we use A-F. Here is a list of many different colors and their hex values.

Notice that Black, White, and Aqua are all represented with both three characters and six characters. This can be done with hex colors whose number pairs are the same characters.

Aqua can be represented as #0FF because both of the first two characters are 0 and the second and third pairs of characters are both Fs. Keep in mind that all three character hex colors can be represented with six characters (by repeating each character twice) but the same is not true in reverse.

You can include hex colors just as you would include named colors: background-color: #9932cc;.

There is another syntax for representing RGB values that uses decimal numbers. It looks like this:

.roasting p {
  color: rgb(160, 82, 45);
  text-align: center;
  line-height: 24px;
  font-family: 'Raleway', sans-serif;
  font-size: 16px;
  font-weight: 400;
}

Here, each of the three values represents a color component, and each can have a decimal number value from 0 to 255. The first number represents the amount of red, the second is green, and the third is blue. These colors are exactly the same as hex, but with a different syntax and a different number system.

In general, hex and decimal color representations are equivalent. Which you choose is a matter of personal taste. That said, it's good to choose one and be consistent throughout your CSS, because it's easier to compare hex to hex and decimal to decimal.

The hexadecimal and RGB color system can represent many more colors than the small set of CSS named colors. We can use this new set of colors to refine our web page's style.

In both hex and decimal, we have three values, one for each color. Each can be one of 256 values. Specifically, 256 * 256 * 256 = 16,777,216. That is the amount of colors we can now represent. Compare that to the 147 named CSS colors!

Recall that we started with named colors, converted them to hex, and then converted some of the hex colors to decimal. Unless we made a mistake, all of the colors should still be the same, visually.

The RGB color scheme is convenient because it's very close to how computers represent colors internally. There's another equally powerful system in CSS called the hue-saturation-lightness color scheme, abbreviated as HSL.

The syntax for HSL is similar to the decimal form of RGB, though it differs in important ways. The first number represents the degree of the hue, and can be between 0 and 360. The second and third numbers are percentages representing saturation and lightness respectively.

HSL

Saturation refers to the intensity or purity of the color. If you imagine a line segment drawn from the center of the color wheel to the perimeter, the saturation is a point on that line segment. If you spin that line segment to different angles, you'll see how that saturation looks for different hues. The saturation increases towards 100% as the point gets closer to the edge (the color becomes more rich). The saturation decreases towards 0% as the point gets closer to the center (the color becomes more gray).

Lightness refers to how light or dark the color is. Halfway, or 50%, is normal lightness. Imagine a sliding dimmer on a light switch that starts halfway. Sliding the dimmer up towards 100% makes the color lighter, closer to white. Sliding the dimmer down towards 0% makes the color darker, closer to black.

HSL is convenient for adjusting colors. In RGB, making the color a little darker may affect all three color components. In HSL, that's as easy as changing the lightness value. HSL is also useful for making a set of colors that work well together by selecting various colors that have the same lightness and saturation but different hues.

All of the colors we've seen so far have been opaque, or non-transparent. When we overlap two opaque elements, nothing from the bottom element shows through the top element. In this exercise, we'll change the opacity, or the amount of transparency, of some colors so that some or all of the bottom elements are visible through a covering element.

To use opacity in the HSL color scheme, use hsla instead of hsl, and four values instead of three. For example:

.midground {
  background-color: hsla(225, 100%, 25%, 0.4);
}

The first three values work the same as hsl. The fourth value (which we have not seen before) is the alpha. This last value is sometimes called the opacity.

Alpha is a decimal number from zero to one. If alpha is zero, the color will be completely transparent. If alpha is one, the color will be opaque. The value for half transparent would be 0.5.

You can think of the alpha value as, "the amount of the background to mix with the foreground". When a color's alpha is below one, any color behind it will be blended in. The blending happens for each pixel; no blurring occurs.

The RGB color scheme has a similar syntax for opacity, rgba. Again, the first three values work the same as rgb and the last value is the alpha.

Alpha can only be used with HSL and RGB colors; we cannot add the alpha value to color: green color: #FFFFF.

There is, however, a named color keyword for zero opacity, transparent. It's equivalent to rgba(0, 0, 0, 0).

There are four ways to represent color in CSS:

  • Named colors — there are 147 named colors, which you can review here.
  • Hexadecimal or hex colors
    • Hexadecimal is a number system with has sixteen digits, 0 to 9 followed by "A" to "F".
    • Hex values always begin with # and specify values of red, blue and green using hexademical numbers such as #23F41A.
  • RGB
    • RGB colors use the rgb() syntax with one value for red, one value for blue and one value for green.
    • RGB values range from 0 to 255 and look like this: rgb(7, 210, 50).
  • HSL
    • HSL stands for hue (the color itself), saturation (the intensity of the color), and lightness (how light or dark a color is).
    • Hue ranges from 0 to 360 and saturation and lightness are both represented as percentages like this: hsl(200, 20%, 50%).
  • You can add opacity to color in RGB and HSL by adding a fourth value, a, which is represented as a percentage.

If you've ever used a formatted word processor, chances are that you probably also used a feature that allowed you change the "type of font" you were typing in. The phrase "type of font" refers to the technical term typeface, or font family.

To change the typeface of text on your web page, you can use the font-family property.

h1 {
  font-family: Garamond;
}

In the example above, the font family for all main heading elements has been set to Garamond.

When setting typefaces on a web page, keep the following points in mind:

  1. The font specified in a stylesheet must be installed on a user's computer in order for that font to display when a user visit the web page. We'll learn how to work around this issue in a later exercise.
  2. You've probably noticed that we haven't been specifying a typeface in previous exercises of this course. How exactly does the browser know what typeface to use when displaying the web page? The default typeface for all most browsers is Times New Roman. You may be familiar with this typeface if you have ever used a formatted word processor.
  3. It's a good practice to limit the number of typefaces used on a web page to 2 or 3.
  4. When the name of a typeface consists of more than one word, it must be enclosed in double quotes (otherwise it will not be recognized), like so:
h1 {
  font-family: "Courier New";
}

You've probably noticed bold text in websites you use, especially in news or text-heavy sites. It's common to bold important headings or keywords. In CSS, we can style bold text with the font-weight property.

If we want to bold text in a web page, we can set the font-weight to bold.

p {
  font-weight: bold;
}

If we want to ensure that text is not bold, we can set the font-weight to normal.

p {
  font-weight: normal;
}

By default, the font-weight of most text elements is set to normal. Some elements, like headers, have built-in bold styling. A good approach is to check to see if the the text element has any default styling, and use the font-weight property accordingly.

The font-weight property can also be assigned a number value to style text on a numeric scale ranging from 100 to 900. Valid values are multiples of 100 within this range such as 200 or 500.

When using numeric weights, there are a number of default font weights that we can use:

  1. 400 is the default font-weight of most text.
  2. 700 signifies a bold font-weight.
  3. 300 signifies a light font-weight.

Let's take a look at an example of how numeric fonts are used.

header {
  font-weight: 800;
}
footer {
  font-weight: 200;
}

Here, the header would appear as a deep bold, while the footer would appear rather light.

It's important to note that not all fonts can be assigned a numeric font-weight. You can look up the font you are using to see which font-weight values are available.

You can also italicize text with the font-styleproperty.

h3 {
  font-style: italic;
}

The italic value causes text to appear in italics. The font-style property also has a normal value which is the default.

You can also increase the spacing between words in a body of text, technically known as word spacing.

To do so, you can use the word-spacing property:

h1 {
  word-spacing: 0.3em;
}

The default amount of space between words is usually 0.25em. In the example above, the word spacing is set to 0.3em, which represents an increase of only .05em in word spacing.

It's not common to increase the spacing between words, but it may help enhance the readability of bolded or enlarged text. Note, again, that the preferred unit is ems.

You've learned how to increase the spacing between lines of text and words, but it's possible to get even more detailed: increasing the spacing between individual letters.

The technical term for adjusting the spacing between letters is called "kerning". Kerning can be adjusted with the letter-spacingproperty in CSS.

h1 {
  letter-spacing: 0.3em;
}

Like word spacing, it's not common to increase the kerning in text, but sometimes it enhances the readability of uppercase text.

Text can also be styled to appear in either all uppercase or lowercase with the text-transform property.

h1 {
  text-transform: uppercase;
}

The code in the example above formats all <h1> elements to appear in uppercase, regardless of the case used for the heading within the HTML code. Alternatively, the lowercase value could be used to format text in all lowercase.

Since text can be directly typed in all uppercase or lowercase within an HTML file, what is the point of a CSS rule that allows you to format letter case?

Depending on the type of content a web page displays, it may make sense to always style a specific element in all uppercase or lowercase letters. For example, a website that reports breaking news may decide to format all <h1>heading elements such that they always appear in all uppercase, as in the example above. It would also avoid uppercase text in the HTML file, which could make code difficult to read.

No matter how much styling is applied to text (typeface, size, weight, etc.), text always appears on the left side of the browser.

To move, or align, text, we can use the text-align property.

h1 {
  text-align: right;
}

The text-align property can be set to one of the following three values:

  1. left - aligns text to the left hand side of the browser.
  2. center - centers text.
  3. right - aligns text to the right hand side of the browser.

Later in the course, you'll learn exactly how the browser positions HTML elements by default, which will help you understand how the browser "aligns" text, since "align" is a relative term. For now, it's enough to know that text can be moved to the left, center, or right side of the web page.

Another property that we can set for text is line-height. This property modifies the leading of text.

Line Height

We often modify line-height to make text on a web page easier to read. When text is styled to appear larger, the vertical spacing between lines of text can decrease, creating text that is difficult to read, particularly in paragraphs.

We can use the line-height property to set how tall we want the line containing our text to be, regardless of the height of the text. Line heights can take one of several values:

  1. A unitless number, such as 1.2. This number is an absolute value that will compute the line height as a ratio of the font size.
  2. A number specified by unit, such as 12px. This number can be any valid CSS unit, such as pixels, percents, ems, or rems.

Generally, the unitless ratio value is the preferred method, since it is responsive and based exclusively on the current font size. In other words, if we change the font size, a unitless line-height would automatically readjust, whereas the pixel value would remain static.

p {
  line-height: 1.4;
}
  1. Serif — fonts that have extra details on the ends of each letter. Examples include fonts like Times New Roman or Georgia, among others.
  2. Sans-Serif — fonts that do not have extra details on the ends of each letter. Instead, letters have straight, flat edges, like Arial or Helvetica.

Serif and Sans Serif

What happens when a stylesheet requires a font that is not installed on a user's computer? Most computers have a small set of typefaces pre-installed. This small set includes serif fonts like Times New Roman and sans-serif fonts like Arial.

These pre-installed fonts serve as fallback fonts if the stylesheet specifies a font which is not installed on a user's computer.

To use fallback fonts, the following syntax is required:

h1 {
  font-family: "Garamond", "Times", serif;
}

The CSS rule above says:

  1. Use the Garamond font for all <h1>elements on the web page.
  2. If Garamond is not available, use the Times font.
  3. If Garamond and Times are not available, use any serif font pre-installed on the user's computer.

The fonts specified after Garamond are the fallback fonts (Times, serif). Fallback fonts help ensure a consistent experience for the diverse audience of users that visit a site.

With the number of fonts available with modern typography, it is unrealistic to expect users to have all fonts installed on their computers. New fonts are often centralized in directories made available for public use. We refer to these fonts as non-user fonts.

Google Fonts is one such directory of thousands of open-source fonts, available for free use. Google Fonts gives us a way to retrieve the link for a single font, multiple fonts, or multiple fonts with the font-weightand font-style properties.

VIDEO

When we have the link to the font of our choice, we can add the font to the <head> section of the HTML document, using the <link> tag and the href.

Let's take a look at a few examples:

  1. A single linked font, using Droid Serif as an example:
<head>
  <link href="https://fonts.googleapis.com/css?family=Droid+Serif" type="text/css" rel="stylesheet">
</head>
  1. Multiple linked fonts, using the Droid Serif and Playfair Display fonts as an example:
<head>
  <link href="https://fonts.googleapis.com/css?family=Droid+Serif|Playfair+Display" type="text/css" rel="stylesheet">
</head>
  1. Multiple linked fonts, along with weights and styles. Here Droid Serifhas font weights of 400, 700, and 700i, while Playfair Display has font weights of 400, 700, and 900i:
<head>
  <link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700,700i|Playfair+Display:400,700,900i" rel="stylesheet">
</head>

Once a font is linked, we can create CSS selectors to target elements, just as we do with other fonts.

There are other ways to link non-user fonts that don't require the use of the <link> tag in the HTML document. CSS offers a way to import fonts directly into stylesheets with the @font-face property.

To load fonts with the @font-face property:

  1. Instead of using the font's link in the HTML document, enter the link into the URL bar in the browser.
  2. The browser will load the CSS rules. You will need to focus on the rules that are directly labeled as /* latin */. Some of the latin rules are on separate lines. You will need each of these.
  3. Copy each of the CSS rules labeled latin, and paste the rules from the browser to the top of style.css.

It is important to stress the need to copy the @font-face rules to the top of the stylesheet for the font to load correctly in the project.

VIDEO

We can then use the fonts in the stylesheets as you would use any other font. Let's practice loading an external font in our stylesheets using the @font-face property, and using the font to style our page.

@font-face {
  font-family: "Glegoo";
  src: url(../fonts/Glegoo-Regular.ttf) format('truetype');
}

@font-face {
  font-family: 'Space Mono';
  font-style: normal;
  font-weight: 400;
  src: local('Space Mono'), local('SpaceMono-Regular'), url(https://fonts.gstatic.com/s/spacemono/v1/adVweg3BJhE6r8jYmXseHQzyDMXhdD8sAj6OAJTFsBI.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}

While Google Fonts and other resources can broaden font selection, you may wish to use an entirely different font or abstain from using a font from an external service.

We can modify our @font-face rule to use local font files as well. We can supply the user with the desired font family and host it along with our site instead of depending on a different site.

@font-face {
  font-family: "Roboto";
  src: url(fonts/Roboto.woff2) format('woff2'),
       url(fonts/Roboto.woff) format('woff'),
       url(fonts/Roboto.tff) format('truetype');
}

Here, you'll notice:

  1. The main difference is the use of a relative filepath instead of a web URL.
  2. We add a format for each file to specify which font to use. Different browsers support different font types, so providing multiple font file options will support more browsers.

As of now .woff2 appears to be the way of the future, due to greatly reduced file sizes and improved performance, but many browsers still don’t support it. There are lots of great sources to find fonts to use locally, such as Font Squirrel.

Using CSS, you can elegantly lay out elements on a web page. There is no simple answer for how best to do this — depending on what content you are trying to display, multiple different techniques can work well. Codecademy's lessons on the box model, Flexbox, and CSS display and positioning properties explain three possible ways to approach layout.

In this lesson, we introduce a new, powerful tool called CSS Grid. The grid can be used to lay out entire web pages. Whereas Flexbox is mostly useful for positioning items in a one-dimensional layout, CSS grid is most useful for two-dimensional layouts, providing many tools for aligning and moving elements across both rows and columns.

By the end of this lesson, you will understand how to use these properties to create grid layouts:

  • grid-template-columns
  • grid-template-rows
  • grid-template
  • grid-template-area
  • grid-gap
  • grid-row-start / grid-row-end
  • grid-column-start / grid-column-end
  • grid-area

That's a lot to learn. But by the end, you'll be a master at grid positioning. Let's start learning!

Note: CSS Grid is supported in the most recent versions of many browsers, but it is not supported universally. To make sure that you can get the most out of this course, check your browser version and see if it supports CSS Grid. If CSS Grid is not supported in your browser, you should switch or update to a supported browser and version.

To set up a grid, you need to have both a grid container and grid items. The grid container will be a parent element that contains grid items as children and applies overarching styling and positioning to them.

To turn an HTML element into a grid container, you must set the element's displayproperty to grid (for a block-level grid) or inline-grid (for an inline grid). Then, you can assign other properties to lay out the grid.

By default, grids contain only one column. If you were to start adding items, each item would be put on a new row; that's not much of a grid! To change this, we need to explicitly define the number of rows and columns in our grid.

We can define the columns of our grid by using the CSS property grid-template-columns. Below is an example of this property in action:

.grid {
  display: grid;
  width: 500px;
  grid-template-columns: 100px 200px;
}

This property creates two changes. First, it defines the number of columns in the grid; in this case, there are two. Second, it sets the width of each column. The first column will be 100 pixels wide and the second column will be 200 pixels wide.

We can also define the size of our columns as a percentage of the entire grid's width.

.grid {
  display: grid;
  width: 1000px;
  grid-template-columns: 20% 50%;
}

In this example, the grid is 1000 pixels wide. Therefore, the first column will be 200 pixels wide because it is set to be 20% of the grid's width. The second column will be 500 pixels wide.

We can also mix and match these two units. In the example below, there are three columns of width 20 pixels, 40 pixels, and 60 pixels:

.grid {
  display: grid;
  width: 100px;
  grid-template-columns: 20px 40% 60px;
}

Notice that in this example, the total width of our columns (120 pixels) exceeds the width of the grid (100 pixels). This might make our grid cover other elements on the page! In a later exercise we will discuss how to avoid overflow.

We've learned how to define the number of columns in our grid explicitly. To specify the number and size of the rows, we are going to use the property grid-template-rows.

This property is almost identical to grid-template-columns. Take a look at the code below to see both properties in action.

.grid {
  display: grid;
  width: 1000px;
  height: 500px;
  grid-template-columns: 100px 200px;
  grid-template-rows: 10% 20% 600px;
}

This grid has two columns and three rows. grid-template-rows defines the number of rows and sets each row's height. In this example, the first row is 50 pixels tall (10% of 500), the second row is 100 pixels tall (20% of 500), and the third row is 600 pixels tall.

When using percentages in these two properties, remember that rows are defined as a percentage of the grid's height, and columns are defined as a percentage of its width.

The property grid-template can replace the previous two CSS properties. Both grid-template-rows and grid-template-columns are nowhere to be found in the following code!

.grid {
  display: grid;
  width: 1000px;
  height: 500px;
  grid-template: 200px 300px / 20% 10% 70%;
}

When using grid-template, the values before the slash will determine the size of each row. The values after the slash determine the size of each column. In this example, we've made two rows and three columns of varying sizes.

The same rules from before apply; when using percentages to set rows, each row will be a percentage of the grid's total height. Columns are still a percentage of the total width.

You may already be familiar with several types of responsive units such as percentages (%), ems and rems. CSS Grid introduced a new relative sizing unit — fr, like fraction.

By using the fr unit, we can define the size of columns and rows as a fraction of the grid's length and width. This unit was specifically created for use in CSS Grid. Using fr makes it easier to prevent grid items from overflowing the boundaries of the grid. Consider the code below:

css .grid { display: grid; width: 1000px; height: 400px; grid-template: 2fr 1fr 1fr / 1fr 3fr 1fr; }

In this example, the grid will have three rows and three columns. The rows are splitting up the available 400 pixels of height into four parts. The first row gets two of those parts, the second row gets one, and the third row gets one. Therefore the first row is 200 pixels tall, and the second and third rows are 100 pixels tall.

Each column's width is a fraction of the available space. In this case, the available space is split into five parts. The first column gets one-fifth of the space, the second column gets three-fifths, and the last column gets one-fifth. Since the total width is 1000 pixels, this means that the columns will have widths of 200 pixels, 600 pixels, and 200 pixels respectively.

It is possible to use fr with other units as well. When this happens, each fr represents a fraction of the available space.

css .grid { display: grid; width: 100px; grid-template-columns: 1fr 60px 1fr; }

In this example, 60 pixels are taken up by the second column. Therefore the first and third columns have 40 available to split between them. Since each gets one fraction of the total, they both end up being 20 pixels wide.

The properties that define the number of rows and columns in a grid can take a function as a value. repeat() is one of these functions. The repeat() function was created specifically for CSS Grid.

.grid {
  display: grid;
  width: 300px;
  grid-template-columns: repeat(3, 100px);
}```

The repeat function will duplicate the specifications for rows or columns a given number of times. In the example above, using the repeat function will make the grid have three columns that are each 100 pixels wide. It is the same as writing:
```css
grid-template-columns: 100px 100px 100px;

Repeat is particularly useful with fr. For example, repeat(5, 1fr) would split your table into five equal rows or columns.

Finally, the second parameter of repeat() can have multiple values.

grid-template-columns: repeat(2, 20px 50px)

This code will create four columns where the first and third columns will be 20 pixels wide and the second and fourth will be 50 pixels wide.

So far, all of the grids that we have worked with have been a fixed size. The grid in our example has been 400 pixels wide and 500 pixels tall. But sometimes you might want a grid to resize based on the size of your web browser.

In these situations, you might want to prevent a row or column from getting too big or too small. For example, if you have a 100-pixel wide image in your grid, you probably don't want its column to get thinner than 100 pixels! The minmax() function can help us solve this problem.

.grid {
  display: grid;
  grid-template-columns: 100px minmax(100px, 500px) 100px;
}

In this example, the first and third columns will always be 100 pixels wide, no matter the size of the grid. The second column, however, will vary in size as the overall grid resizes. The second column will always be between 100 and 500 pixels wide.

In all of our grids so far, there hasn't been any space between the items in our grid. The CSS properties grid-row-gap and grid-column-gap will put blank space between every row and column in the grid.

css .grid { display: grid; width: 320px; grid-template-columns: repeat(3, 1fr); grid-column-gap: 10px; }

It is important to note that grid-gap does not add space at the beginning or end of the grid. In the example code, our grid will have three columns with two ten-pixel gaps between them.

Let's quickly calculate how wide these columns are. Remember that using fr considers all of the available space. The grid is 320 pixels wide and 20 of those pixels are taken up by the two grid gaps. Therefore each column takes a piece of the 300 available pixels. Each column gets 1fr, so the columns are evenly divided into thirds (or 100 pixels each).

Finally, there is a CSS property grid-gap that can set the row and column gap at the same time. grid-gap: 20px 10px; will set the distance between rows to 20 pixels and the distance between columns to 10 pixels. Unlike other CSS grid properties, this shorthand does not take a / between values! If only one value is given, it will set the column gap and the row gap to that value.

In this lesson, we have learned how to define a grid container. When explicitly defining a grid, you have to declare the quantity of rows and columns and their respective sizes.

In all of our examples, the items placed in the grid have always taken up exactly one square. This does not always need to be the case; we can drastically change the look of our grid by making grid items take up more than one row and one column. You can see this in the diagram to the right. Items A, B, C, and E span more than one row!

Grid Items

In the following exercises, you will learn CSS properties that will affect the size of the grid items and where they are displayed on the page. By manipulating both the parent and the child elements, we can create beautiful layouts with ease.

Let's start exploring grid items!

Using the CSS properties grid-row-start and grid-row-end, we can make single grid items take up multiple rows. Remember, we are no longer applying CSS to the outer grid container; we're adding CSS to the elements sitting inside the grid!

.item {
  grid-row-start: 1;
  grid-row-end: 3;
}

In this example, the HTML element of class item will take up two rows in the grid, rows 1 and 2. The values that grid-row-start and grid-row-end accept are grid lines.

Row grid lines and column grid lines start at 1 and end at a value that is 1 greater than the number of rows or columns the grid has. For example, if a grid has 5 rows, the grid row lines range from 1 to 6. If a grid has 8 columns, the grid row lines range from 1 to 9.

The value for grid-row-start should be the row at which you want the grid item to begin. The value for grid-row-end should be one greater than the row at which you want the grid item to end. An element that covers rows 2, 3, and 4 should have these declarations: grid-row-start: 2 and grid-row-end: 5.

It is possible for the value of grid-row-start to be greater than that of grid-row-end. Both properties can also each have negative values. Consult the documentation to learn more about how to use these features.

We can use the property grid-row as shorthand for grid-row-start and grid-row-end. The following two code blocks will produce the same output:

.item {
  grid-row-start: 4;
  grid-row-end: 6;
}
.item {
  grid-row: 4 / 6;
}

This code should look similar to the way grid-template is shorthand for grid-template-rowsand grid-template-columns. In this case, the starting row goes before the "/" and the ending row goes after it. Again, the ending row is exclusive; this grid item will occupy rows four and five.

When an item spans multiple rows or columns using these properties, it will also include the grid-gap if any exists. For example, if an item spans two rows of height 100 pixels and there is a ten-pixel grid-gap, then the item will have a total height of 210 pixels.

The previous three properties also exist for columns. grid-column-start, grid-column-endand grid-column work identically to the row properties. These properties allow a grid item to span multiple columns.

When using these properties, we can use the keyword span to start or end a column or row relative to its other end. Look at how span is used in the code below:

.item {
  grid-column: 4 / span 2;
}

This is telling the item element to begin in column four and take up two columns of space. So item would occupy columns four and five. It produces the same result as the following code blocks:

.item {
  grid-column: 4 / 6;
}
.item {
  grid-column-start: 4;
  grid-column-end: span 2;
}
.item {
  grid-column-start: span 2;
  grid-column-end: 6;
}

span is a useful keyword, because it avoids off-by-one errors (miscalculating the ending grid line) you might make when determining the ending grid line of an element. If you know where you want your grid item to start and how long it should be, use span!

We've already been able to use grid-row and grid-column as shorthand for properties like grid-row-start and grid-row-end. We can refactor even more using the property grid-area. This property will set the starting and ending positions for both the rows and columns of an item.

.item {
  grid-area: 2 / 3 / 4 / span 5;
}

grid-area takes four values separated by slashes. The order is important! This is how grid-area will interpret those values.

  1. grid-row-start
  2. grid-column-start
  3. grid-row-end
  4. grid-column-end

In the above example, the item will occupy rows two and three and columns three through eight.

Using grid-area is an easy way to place items exactly where you want them in a grid.

  • grid-template-columns defines the number and sizes of the columns of the grid
  • grid-template-rows defines the number and sizes of the rows of the grid
  • grid-template is a shorthand for defining both grid-template-columns and grid-template-rows in one line
  • grid-gap puts blank space between rows and/or columns of the grid
  • grid-row-start and grid-row-end makes elements span certain rows of the grid
  • grid-column-start and grid-column-endmakes elements span certain columns of the grid
  • grid-area is a shorthand for grid-row-start, grid-column-start, grid-row-end, and grid-column-end, all in one line

In the previous lesson, you learned all the foundational properties necessary to create a two-dimensional grid-based layout for your web pages! In this lesson, you'll learn the following additional properties that you can use to harness the power of CSS Grid Layout:

  • grid-template-areas
  • justify-items
  • justify-content
  • justify-self
  • align-items
  • align-content
  • align-self
  • grid-auto-rows
  • grid-auto-columns
  • grid-auto-flow

You will also learn about the explicit and implicit grids and grid axes.

The grid-template-areas property allows you to name sections of your web page to use as values in the grid-row-start, grid-row-end, grid-col-start,grid-col-end, and grid-area properties.

<div class="container">
  <header>Welcome!</header>
  <nav>Links!</nav>
  <section class="info">Info!</section>
  <section class="services">Services!</section>
  <footer>Contact us!</footer>
</div>
.container {
  display: grid;
  max-width: 900px;
  position: relative;
  margin: auto;
  grid-template-areas: "head head"
                       "nav nav" 
                       "info services"
                       "footer footer";
  grid-template-rows: 300px 120px 800px 120px;
  grid-template-columns: 1fr 3fr; 
}
header {
  grid-area: head;
}
nav {
  grid-area: nav;
}
.info {
  grid-area: info;
}
.services {
  grid-area: services;
}
footer {
  grid-area: footer;
}

You may want to expand this section of the website to view the code above more clearly.

  1. In the example above, the HTML creates a web page with five distinct parts.
  2. The grid-template-areas declaration in the .container rule set creates a 2-column, 4-row layout.
  3. The grid-template-rows declaration specifies the height of each of the four rows from top to bottom: 300 pixels, 120 pixels, 800 pixels, and 120 pixels.
  4. The grid-template-columns declaration uses the fr value to cause the left column to use one fourth of the available space on the page and the right column to use three-fourths of the available space on the page.
  5. In each rule set below .container, we use the grid-area property to tell that section to cover the portion of the page specified. The header element spans the first row and both columns. The nav element spans the second row and both columns. The element with class .info spans the third row and left column. The element with class .services spans the third row and right column. The footer element spans the bottom row and both columns.
  6. That's it! An entire page laid out in 40 lines of code.

This property is declared on grid containers.

You can see what you'll be building in this exercise here.

Another powerful feature of CSS Grid Layout is the ability to easily overlap elements.

When overlapping elements, it is generally easiest to use grid line names and the grid-areaproperty.

<div class="container">
  <div class="info">Info!</div> 
  <img src="#" />
  <div class="services">Services!</div>
</div>
.info {
  grid-area: 1 / 1 / 9 / 4;
}
.services {
  grid-area: 1 / 4 / 9 / 7;
}
img {
  grid-area: 2 / 3 / 5 / 5;
  z-index: 5;
}

In the example above, there is a grid container with eight rows and six columns. There are three grid items within the container — a <div>with the class info, a <div> with the class services, and an image.

The info section covers all eight rows and the first three columns. The services section covers all eight rows and the last three columns.

The image spans the 2nd, 3rd, and 4th rows and the 3rd and 4th columns.

The z-index property tells the browser to render the image element on top of the services and info sections so that it is visible.

We have referred to "two-dimensional grid-based layout" several times throughout this course. There are two axes in a grid layout — the column (or block) axis and the row (or inline) axis.

The column axis stretches from top to bottom across the web page. The row axis stretches from left to right across the web page.

In the following four exercises, we will learn and use properties that rely on an understanding of grid axes.

justify-items is a property that positions grid items along the inline, or row, axis. This means that it positions items from left to right across the web page.

justify-items accepts these values:

  • start — aligns grid items to the left side of the grid area
  • end — aligns grid items to the right side of the grid area
  • center — aligns grid items to the center of the grid area
  • stretch — stretches all items to fill the grid area

There are several other values that justify-itemsaccepts, which you can read about on the Mozilla Developer Network. The definitions for these values can also be found in the documentation. It is important to note that the page with the definitions includes some values that are not accepted in CSS Grid layout.

<main>
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
</main>
main {
  display: grid;
  grid-template-columns: repeat(3, 400px);
  justify-items: center;
}

In the example above, we use justify-items to adjust the positioning of some elements on this web page.

  1. There is a grid container with three columns that are each 400 pixels wide.
  2. The container has three grid items that do not have a specified width.
  3. Without setting the justify-items property, these elements will span the width of the column they are in (400 pixels).
  4. By setting the justify-items property to center, the .card <div>s will be centered inside of their columns. They will only be as wide as necessary to contain their content (the words Card 1, etc).
  5. If we specify a width for the .cardelements, they will not stretch the width of their column.

This property is declared on grid containers.

In the previous exercise, we learned how to position elements within their columns. In this exercise, we will learn how to position a grid within its parent element.

We can use justify-content to position the entire grid along the row axis.

It accepts these values:

  • start — aligns the grid to the left side of the grid container
  • end — aligns the grid to the right side of the grid container
  • center — centers the grid horizontally in the grid container
  • stretch — stretches the grid items to increase the size of the grid to expand horizontally across the container
  • space-around — includes an equal amount of space on each side of a grid element, resulting in double the amount of space between elements as there is before the first and after the last element
  • space-between — includes an equal amount of space between grid items and no space at either end
  • space-evenly — places an even amount of space between grid items and at either end

There are several other values that justify-content accepts, which you can read about on the Mozilla Developer Network. The definitions for these values can also be found in the documentation. It is important to note that the page with the definitions includes some values that are not accepted in CSS Grid layout.

<main>
  <div class="left">Left</div>
  <div class="right">Right</div>
</main>
main {
  display: grid;
  width: 1000px;
  grid-template-columns: 300px 300px;
  grid-template-areas: "left right"; 
  justify-content: center;
}
  1. the example above, the grid container is 1000 pixels wide, but we only specified two columns that are 300 pixels each. This will leave 400 pixels of unused space in the grid container.
  2. justify-content: center; positions the columns in the center of the grid, leaving 200 pixels on the right and 200 pixels on the left of the grid.

This property is declared on grid containers.

In the previous two exercises, we learned how to position grid items and grid columns from left to right across the page. Below, we'll learn how to position grid items from top to bottom!

align-items is a property that positions grid items along the block, or column axis. This means that it positions items from top to bottom.

align-items accepts these values:

  • start — aligns grid items to the top side of the grid area
  • end — aligns grid items to the bottom side of the grid area
  • center — aligns grid items to the center of the grid area
  • stretch — stretches all items to fill the grid area

There are several other values that align-items accepts, which you can read about on the Mozilla Developer Network. The definitions for these values can also be found in the documentation. It is important to note that the page with the definitions includes some values that are not accepted in CSS Grid layout.

<main>
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
</main>
main {
  display: grid;
  grid-template-rows: repeat(3, 400px);
  align-items: center;
}

In the example above, we use align-items to adjust the positioning of some elements on this web page.

  1. There is a grid container with three rows that are 400 pixels tall.
  2. The container has three grid items that do not have a specified width.
  3. Without setting the align-items property, these elements will span the height of the row they are in (400 pixels).
  4. By setting the align-items property to center, the .card <div>s will be centered vertically inside of their rows. They will only be as tall as necessary to contain their content (the words Card 1, etc).
  5. If we specify a height for the .cardelements, they will not stretch the height of their row even if align-items: stretch;is set.

This property is declared on grid containers.

In the previous exercise, we positioned grid items within their rows. align-content positions the rows along the column axis, or from top to bottom.

It accepts these positional values:

  • start — aligns the grid to the top of the grid container
  • end — aligns the grid to the bottom of the grid container
  • center — centers the grid vertically in the grid container
  • stretch — stretches the grid items to increase the size of the grid to expand vertically across the container
  • space-around — includes an equal amount of space on each side of a grid element, resulting in double the amount of space between elements as there is before the first and after the last element
  • space-between — includes an equal amount of space between grid items and no space at either end
  • space-evenly — places an even amount of space between grid items and at either end

There are several other values that align-contentaccepts, which you can read about on the Mozilla Developer Network. The definitions for these values can also be found in the documentation. It is important to note that the page with the definitions includes some values that are not accepted in CSS Grid layout.

<main>
  <div class="top">Top</div>
  <div class="bottom">Bottom</div>
</main>
main {
  display: grid;
  height: 600px;
  rows: 200px 200px;
  grid-template-areas: "top"
                       "bottom"; 
  align-content: center;
}
  1. In the example above, the grid container is 600 pixels tall, but we only specified two rows that are 200 pixels each. This will leave 200 pixels of unused space in the grid container.
  2. align-content: center; positions the rows in the center of the grid, leaving 100 pixels at the top and 100 pixels at the bottom of the grid.

This property is declared on grid containers.

The justify-items and align-items properties specify how all grid items contained within a single container will position themselves along the row and column axes, respectively.

justify-self specifies how an individual element should position itself with respect to the row axis. This property will override justify-items for any item on which it is declared.

align-self specifies how an individual element should position itself with respect to the column axis. This property will override align-items for any item on which it is declared.

They both accept these four properties:

  • start — positions grid items on the left side/top of the grid area
  • end — positions grid items on the right side/bottom of the grid area
  • center — positions grid items on the center of the grid area
  • stretch — positions grid items to fill the grid area (default)

align-self and justify-self accept the same values as align-items and justify-items. You can read about these values on the Mozilla Developer Network. The definitions for these values can also be found in the documentation. It is important to note that the page with the definitions includes some values that are not accepted in CSS Grid layout.

These properties are declared on grid items.

So far, we have been explicitly defining the dimensions and quantities of our grid elements using various properties. This works well in many cases, such as a landing page for a business that will display a specific amount of information at all times.

However, there are instances in which we don't know how much information we're going to display. For example, consider online shopping. Often, these web pages include the option at the bottom of the search results to display a certain quantity of results or to display ALL results on a single page. When displaying all results, the web developer can't know in advance how many elements will be in the search results each time.

What happens if the developer has specified a 3-column, 5-row grid (for a total of 15 items), but the search results return 30?

Something called the implicit grid takes over. The implicit grid is an algorithm built into the specification for CSS Grid that determines default behavior for the placement of elements when there are more than fit into the grid specified by the CSS.

The default behavior of the implicit grid is as follows: items fill up rows first, adding new rows as necessary. New grid rows will only be tall enough to contain the content within them.

CSS Grid provides two properties to specify the size of grid tracks added implicitly: grid-auto-rows and grid-auto-columns.

grid-auto-rows specifies the height of implicitly added grid rows. grid-auto-columns specifies the width of implicitly added grid columns.

grid-auto-rows and grid-auto-columns accept the same values as their explicit counterparts, grid-template-rows and grid-template-columns:

  • pixels (px)
  • percentages (%)
  • fractions (fr)
  • the repeat() function
<body>
  <div>Part 1</div>   
  <div>Part 2</div>
  <div>Part 3</div>
  <div>Part 4</div>
  <div>Part 5</div>
</body>
body {
  display: grid;
  grid: repeat(2, 100px) / repeat(2, 150px); 
  grid-auto-rows: 50px;
}

In the example above, there are 5 <div>s. However, in the section rule set, we only specify a 2-row, 2-column grid — four grid cells.

The fifth <div> will be added to an implicit row that will be 50 pixels tall.

If we did not specify grid-auto-rows, the rows would be auto-adjusted to the height of the content of the grid items.

These properties are declared on grid containers.

In addition to setting the dimensions of implicitly-added rows and columns, we can specify the order in which they are rendered.

grid-auto-flow specifies whether new elements should be added to rows or columns.

grid-auto-flow accepts these values:

  • row — specifies the new elements should fill rows from left to right and create new rows when there are too many elements (default)
  • column — specifies the new elements should fill columns from top to bottom and create new columns when there are too many elements
  • dense — this keyword invokes an algorithm that attempts to fill holes earlier in the grid layout if smaller elements are added

You can pair row and column with dense, like this: grid-auto-flow: row dense;.

This property is declared on grid containers.

  • grid-template-areas specifies grid named grid areas
  • grid layouts are two-dimensional: they have a row, or inline, axis and a column, or block, axis.
  • justify-items specifies how individual elements should spread across the row axis
  • justify-content specifies how groups of elements should spread across the row axis
  • justify-self specifies how a single element should position itself with respect to the row axis
  • align-items specifies how individual elements should spread across the column axis
  • align-content specifies how groups of elements should spread across the column axis
  • align-self specifies how a single element should position itself with respect to the column axis
  • grid-auto-rows specifies the height of rows added implicitly to the grid
  • grid-auto-columns specifies the width of columns added implicitly to the grid
  • grid-auto-flow specifies in which direction implicit elements should be created
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment