10. Responsive CSS

(Approximate Time: ~ 2 hours)

Key Terms

  • Responsive Design
  • media query
  • viewport
  • breakpoint
  • multiple-column
  • flexbox
  • grid layout
  • Responsive Images
  • Responsive Typography
  • orientation
  • Pointer Devices
  • More complex media queries
What is Responsive Design?

Responsive Design Origins

The term responsive design was coined by web designer Ethan Marcotte in 2010 and described the use of three techniques in combination.

The first was the idea of fluid grids, something which was already being explored by Zoe Mickley Gillenwater, and can be read up on in Marcotte’s article, Fluid Grids, published in 2009 on A List Apart.

The second technique was the idea of fluid images. Using a very simple technique of setting the max-width property to 100%, images would scale down smaller if their containing column became narrower than the image’s intrinsic size, but never grow larger. This enables an image to scale down to fit in a flexibly-sized column, rather than overflow it, but not grow larger and become pixelated if the column becomes wider than the image.

The third key component was the media query. Media Queries enable the type of layout switch that web technologist Cameron Adams had previously explored using JavaScript, but instead uses only CSS. Rather than having one layout for all screen sizes, the layout could be changed. For example, Sidebars could be repositioned for the smaller screen, or alternate navigation could be displayed.

It is important to understand that responsive web design isn’t a separate technology — it is a term used to describe an approach to web design, or a set of best practices, used to create a layout that can respond to the device being used to view the content. In Marcotte’s original exploration, this meant flexible grids (using floats) and media queries. In the decade since that article was written, however, working responsively has become the default. Modern CSS layout methods are inherently responsive. We now have new things built into the web platform to make designing responsive sites easier.

The rest of this lesson will point you to the various web platform features you might want to use when creating a responsive website.

Media Queries

Responsive design emerged as a result of media queries. The Media Queries Level 3 specification became a Candidate Recommendation in 2009, meaning that it was deemed ready for implementation in browsers. Media Queries allow us to run a series of tests (e.g. whether the user’s screen is greater than a certain width, or a certain resolution) and apply CSS selectively to style the page appropriately for the user’s needs.

For example, the following media query determines if the current webpage is being displayed as screen media (therefore not a printed document) and the viewport is at least 800 pixels wide. The CSS for the .container selector will only be applied if these two things are true.

You can add multiple media queries within a stylesheet, tweaking your whole layout or parts of it to best suit the various screen sizes. The points at which a media query is introduced, and the layout changed, are known as breakpoints.

A common approach when using media queries is to create a simple single-column layout for narrow-screen devices (e.g., mobile phones), then check for larger screens and implement a multiple column layout when you know that you have enough screen width to handle it. This is often described as mobile-first design.

Find out more in the MDN documentation for Media Queries.

 

Flexible grids

Responsive sites don’t just change their layout between breakpoints, they are built on flexible grids. A flexible grid means that you don’t need to target every possible device size that there is and build a pixel perfect layout for it. That approach would be impossible given the vast number of differently-sized devices that exist in the world today. Also, the fact that on desktop, people do not always have their browser window maximized.

By using a flexible grid, you only need to add in a breakpoint and change the design at the point where the content starts to look bad. For example, if the line lengths become too long as the screen size increases, or a box becomes squashed with two words on each line as it narrows, then it makes sense to set a max-width property to a particular size to make the information easier to read. As you grow as a web developer, you will learn the optimal breakpoints for particular screen dimensions.

In the early days of responsive design, our only option for performing layout was to use floats that we introduced in one of last week’s lessons. Flexible floated layouts were achieved by giving each element a percentage width and ensuring that across the layout the totals were not more than 100%. In his original piece on fluid grids, Marcotte detailed a formula for taking a layout designed using pixels and converting it into percentages.

target / context = result

For example, if our target column size is 60 pixels, and the context (or container) it is in is 960 pixels, we divide 60 by 960, after moving the decimal point two places to the right, we arrive at 6.25% and that is the value we can use in our CSS.

While this approach is considered outdated at this point, due to the slow transition of legacy design patterns, you will still see this method used in many domains across the web today. Since it is likely that you will come across websites using this approach in your work, read this article to learn more about it. Although it is worth understanding, the focus of our lesson is on more modern approaches to responsive CSS. Therefore, we will spend most of our time dedicated to those topics.

 

Modern layout technologies

Modern layout methods such as multiple-column layout, flexbox, and grid are responsive by default. They all assume that you are trying to create a flexible grid and give you easier ways to do so.

Multiple-column

The oldest of these layout methods is Multiple-column, or multicol. When you specify a column-count, this indicates how many columns you want your content to be split into. The browser then works out the size of each column. Its size will change according to the screen size. Here is an example:

If you instead specify a column-width, you are specifying a minimum width. The browser will create as many columns of that width as will comfortably fit into the container, then share the remaining space between all the other columns. As a result, the number of columns will change according to how much space there is. Here is an illustration:

Flexbox

In flexbox, as their initial behavior, flex items will shrink and distribute space between the items according to the space in their container. By changing the values for flex-grow and flex-shrink, you can indicate how you want the items to behave when they encounter more or less space around them.

In the example below, the flex items will each take an equal amount of space in the flex container. Using the shorthand of flex: 1, the items inside the flex container will grow and shrink proportionally to how much space there is around them.

This repl.it presents a responsive CSS layout using flexbox. When you try to maximize and minimize the rendered code, the two boxes will stack on top of one another on smaller screens and next to each other on larger screens. The change happens when the screen size is bigger or smaller than 768 pixels which is the breakpoint in this case.

This article goes into further detail on flexbox.

In this video, we will review everything you need to know about CSS flexbox in only 15 minutes. We will cover what flexbox is, how flexbox works, and the different properties you can use to layout and style your flexbox containers.


Source: Web Dev Simplified

CSS Grid

In CSS grid layout, the fr unit allows the distribution of available space across grid tracks. The example code block below creates a grid container with three tracks sized at 1fr each. This creates three column tracks, each taking one part of the available space in the container.

As you can see in this repl.it, each colored column takes up one-third of the entire container. If you try to maximize and minimize the screen, each column’s width automatically adjusts according to the width of the screen.

This article goes into further detail on CSS grid.

 

Responsive Images

The simplest approach to responsive images is to take an image that is at the largest size and scale it down according to the screen size. For example, in most stylesheets you will find the following CSS code snippet:

Although the downsides to this approach include the image might be displayed a lot smaller than its intrinsic size, you may not want the same image aspect ratio on mobile as on desktop, or wish to show a different image altogether on smaller screens, this method is simple and effective for most applications.

This repl.it presents what it looks like in practice:

You can find out more about Responsive Images here.

 

Responsive typography

One element of responsive design not covered earlier is the idea of responsive typography. This deals with the change of font sizes to reflect lesser or greater amounts of screen real estate.

In this example, we want to set our level 1 heading (h1) to be “4rem”, meaning it will be four times our base font size. That’s a really large heading! We only want this jumbo heading on larger screen sizes. Therefore we first create a smaller heading then use media queries to overwrite that rule when the user is viewing it on a screen size of at least 1,000 pixels. Here is the code:

This is the code in action in this repl.it.

As this approach to typography shows, you do not need to restrict media queries to only changing the layout of the page. They can be used to tweak any element to make it more readable or visually-appealing on different screen sizes.

 

Using viewport units for Responsive Typography

Another modern approach to responsive typography is to use the viewport unit, vw. 1vw is equal to one percent of the viewport width, meaning that if you set your font size using vw, it will always relate to the size of the viewport. Here is an example code snippet:

The issue with the approach above is that the user loses the ability to zoom in and out on any text using the vw unit, as that text is always related to the size of the viewport. Therefore, it is not a good idea to set text using viewport units alone.

A solution, in this case, is to include the method calc(). If you add the vw unit to a value set using a fixed size such as em or rem, then the text will still be zoomable. Essentially, this happens because the vw unit is added on top of the calculated value. Here is an example:

h1 {
font-size: calc(1.5rem + 3vw);
}

This means that we only need to specify the font size for the heading once, rather than set it up for mobile and redefine it in the media queries. The font then gradually increases as you increase the size of the viewport.

 

The viewport meta tag

If you take a close look at the HTML source of a responsive webpage, you will usually see the following <meta> tag in the <head> element of the document.

In this repl.it, it is located on line 5.

<meta name="viewport" content="width=device-width,initial-scale=1">

This meta tag tells mobile browsers that they should set the width of the viewport to the width of the device the user is using. It also asks the browser to scale the document to 100% of its intended size, which shows the document at the mobile-optimized size that you intended.

Why is this needed? It is because mobile browsers tend to lie about their viewport width.

This meta tag exists because when the original iPhone launched and people started to view websites on a small phone screen, most sites were not mobile optimized at the time. The mobile browser would therefore set the viewport width to 960 pixels, render the page at that width, and show the result as a zoomed-out version of the desktop layout. Other mobile browsers (e.g. on Google Android) did the same thing. Users could zoom in and pan around the website to view the bits they were interested in, but it looked bad. You will still see this today if you have the misfortune of visiting a website that does not have a responsive design.

In this situation of setting the viewport at 960px, your responsive design with breakpoints and media queries won’t work as intended on mobile browsers for screen sizes less than 960px. For example, if you’ve got a narrow screen layout that kicks in at 480px viewport width or less, you’ll never see your narrow screen layout on mobile. By setting width=device-width, you are overriding Apple’s default width=960px with the actual width of the device. As a result, your media queries will work as intended.

So the takeaway is that you should always include the above line of HTML in the head element of your documents.

Though there are other settings you can use with the viewport meta tag, in general the above line is what you will want to use.