1

The Essentials of Responsive Web Design

By the end of this first chapter, we will have covered everything needed to author a fully responsive web page.

You might be wondering, why the other 10 chapters? By the end of this chapter, that should be apparent too.

When the first edition of this book came out in 2012, responsive web design was a new and exciting possibility to address the needs of the ever-growing list of devices that could access the internet. In 2020 it's simply the de facto standard. Unless you have a good reason, if you're building a website or web application and it isn't responsive, you're probably doing it wrong!

Perhaps you're reading this because you need to understand what makes a responsive web design, and get a better handle on the capabilities of HTML and CSS? Or perhaps you're already building websites responsively and need a steer on features and techniques you may have missed along the way—not to mention all the new techniques that will be at our disposal in 2020 and beyond?

Either way, we have you covered. If you're in that latter camp, this first chapter should serve as a quick and basic refresher. If you're in the former, think of it as a "boot camp" of sorts, so we're all on the same page.

Here's what we will cover in this first chapter:

  • The browser and device landscape
  • Defining responsive web design
  • Setting browser support levels
  • A brief discussion on development tools and text editors
  • Our first responsive example: a simple HTML5 page
  • The viewport meta tag
  • Fluid images
  • Writing CSS3 media queries to make pages adapt
  • The shortfalls in our basic example
  • Why our journey has only just begun

Are you sitting comfortably? Then we will begin!

The browser and device landscape

Less than 10 years ago, it was reasonable to build a website at a fixed width. The expectation was that all end users would get a fairly consistent experience. This fixed width (typically 960px wide or thereabouts) wasn't too wide for laptop screens, and users with large resolution monitors merely had an abundance of space on either side.

But in 2007, Apple's iPhone ushered in the first truly usable phone browsing experience, and the way people access and interact with the web changed forever.

In the first edition of this book, published in early 2012, the following was noted about the percentage of total browser usage by device type:

In the 12 months from July 2010 to July 2011, global mobile browser use had risen from 2.86 to 7.02 percent.

In the second edition of this book, I noted:

As these words are written, in mid 2014, the same statistics system gs.statcounter.com reports that figure has risen to 29.48% (by way of comparison, North America's mobile figure is at 24%). It's a rising trend that shows no sign of abating.

As I write these latest words in September 2019, again using StatCounter, mobile accounts for a whopping 51.11% of total browser usage, desktop 45.18%, and tablet 3.71%.

The indisputable fact is that the number of people using smaller-screen devices to view the internet is growing at an ever-increasing rate, whilst at the other end of the scale, 27- and 30-inch displays are now also commonplace (along with various tablet and console devices). There is now more of a difference between the smallest screens browsing the web and the largest than ever before.

Thankfully, there is a solution to this ever-expanding browser and device landscape. A responsive web design, built with HTML and CSS allows a website to "just work" across multiple devices and screens. It enables the layout and capabilities of a website to respond to their environment (screen size, input type, and device/browser capabilities).

Originally, before responsive web design was a thing, it was not uncommon for businesses to have a separate mobile site with its own unique URL. That was something that required detecting the user-agent on the host server before sending the browser to the relevant desktop or mobile URL. Another bonus with a responsive website is that it can be implemented without the need for server-based/backend solutions.

Defining responsive web design

The term "responsive web design" was coined by Ethan Marcotte in 2010. In his seminal A List Apart article http://www.alistapart.com/articles/responsive-web-design, he consolidated three existing techniques (flexible grid layout, flexible images/media, and media queries) into one unified approach and named it responsive web design.

Responsive web design in a nutshell

To attempt to put the philosophy of responsive web design into a "nutshell," I would say it's the presentation of web content in the most relevant format for the viewport and device accessing it.

In its infancy, it was typical for responsive design to be implemented by starting with a fixed-width desktop design before trying to scale the design down as needed for smaller screens. However, processes evolved and it became apparent there was a better way. Namely, that everything from design to content management and development worked better when starting with the smallest screens first, and then "progressively enhancing" the design and content for larger screens and/or more capable devices. If the term "progressive enhancement" makes no sense right now, fear not. We'll be talking about that again in a moment.

Before we get into things fully, there are a few subjects I'd like to address and get squared away before we continue: browser support, text editors, and tooling.

Browser support

The sheer volume of disparate devices that access the web means most people understand the need for technical solutions that cater for most devices.

The popularity and ubiquity of responsive web design usually makes the approach an easy sell to clients and stakeholders. Nowadays, most people have some idea what responsive web design is about, even if that understanding amounts to little more than "a website that looks good on phones as well as computers."

However, one question that almost always comes up when starting a responsive design project is browser support. With so many browser and device variants it's not always pragmatic to support every single browser permutation fully. Perhaps time is a limiting factor; perhaps money—perhaps both.

Typically, the older the browser, the greater the amount of work and code required to get feature or aesthetic parity with modern browsers.

We are going to practice progressive enhancement. In essence, starting with a functional and accessible website for the most basic browsers, which will be progressively enhanced with features for more capable browsers. It should be a very rare occasion indeed that you are forced to create a website that isn't at least functional on an old browser/device.

If working on a greenfield project, where there is no existing browser usage data, you can at least think about the demographics of your target audience and make some broad assumptions about likely devices/browsers being used based on those demographics.

Before considering any web project it makes sense to decide, in advance, what platforms you need to fully support and which you are happy to concede visual/functional anomalies for.

For example, if you're unlucky enough to have 25% of your website visitors using Internet Explorer 11, you'll need to consider what features that browser supports and tailor your solution accordingly. The same caution is required if a large number of your users are visiting with older mobile phone platforms such as Android 4.

To this end, if you aren't already, become familiar with websites such as http://caniuse.com. Can I use provides a simple interface for establishing the browser support for each web platform feature.

Generally speaking, when starting a project, as a simple and broad way to determine what browsers to support, I apply the following crude piece of logic: if the cost of developing and supporting browser X is more than the revenue/benefit created by the users of browser X, don't develop specific solutions for browser X.

Figure 1.1: Can I Use provides browser support data for every web platform feature

Text editors

It makes no difference what tool you use to write your code. If the simplest of text editors allows you to write your HTML, CSS, and JavaScript efficiently, that's absolutely fine. Whether your preference is Sublime Text, Vim, Emacs, Nova, Visual Studio Code, or Notepad, it matters little. Just use what works best for you.

Tools for software development

Similarly, there are no requisite tools that are essential to get a responsive web design out of the door. That said, you should be aware that there are many, often free, tools available to eliminate many of the manual and time-intensive tasks of building websites. For example, CSS preprocessors such as Sass can help with code organization, variables, color manipulations, and arithmetic. CSS postprocessors such as PostCSS can automate horrible and thankless jobs like CSS vendor prefixing. Linting and validation tools can check your HTML, JavaScript, and CSS code against standards as you work, eliminating many time-wasting errors that are the result of nothing more than a typo. More recently, code formatters have changed the way we work day to day. Tools like Prettier, for example, automatically format your code with indentation and spacing when you save. None of these tools are essential but they may afford you some benefits.

New tools come out constantly and they are continually evolving. Therefore, whilst some relevant and beneficial tools will be mentioned by name as we go, be aware that something better may be just around the corner. Hence we won't be relying on anything other than standards-based HTML and CSS in our examples. You should, however, use whatever tools you can bring to bear to produce your frontend code as quickly and reliably as possible.

Our first responsive example

In the first paragraph, I promised that by the end of this chapter you would know all you needed to build a fully responsive web page. So far, I've just been talking around the issue at hand. It's time to walk the walk.

Code samples

You can download all the code samples from this book by visiting https://rwd.education/. It's worth knowing that where individual examples are built up throughout a chapter, only the final version of the example is provided in the code download. For example, if you download the code samples for Chapter 2, the examples will be in the state they are at by the end of that chapter. No intermediate states are provided other than in the text.

Our basic HTML file

We will start with a simple HTML5 structure. Don't worry at this point what each of the lines do, especially the content of <head>, as we will cover that in detail in Chapter 2, Writing HTML Markup.

For now, concentrate on the elements inside the <body> tag. There we have a few div elements, a graphic for a logo, a paragraph or two of text, and a list of items. Although you can see more content in the screengrabs, a shorter version of the code follows. For brevity, I have removed the paragraphs of text as we only need to concern ourselves with the core structure.

However, what you should know is that the text is a recipe and description of how to make scones—a quintessentially British dessert.

Remember, if you want to get your hands on the full HTML file, you can download the example code from the https://rwd.education/ website.

<!DOCTYPE html>
<html class="no-js" lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Our first responsive web page with HTML5 and CSS3</title>
    <meta name="description" content="A basic responsive web page – an example from Chapter 1" />
    <link rel="stylesheet" href="css/styles.css" />
  </head>
  <body>
    <div class="Header">
      <a href="/" class="LogoWrapper"><img src="img/SOC-Logo.png" alt="Scone O'Clock logo"/></a>
      <p class="Strap">Scones: the most resplendent of snacks</p>
    </div>
    <div class="IntroWrapper">
      <p class="IntroText">Occasionally maligned and misunderstood; the scone is a quintessentially British classic.</p>
      <div class="MoneyShot">
        <p class="ImageCaption">Incredible scones, picture from Wikipedia</p>
      </div>
    </div>
    <p>Recipe and serving suggestions follow.</p>
    <div class="Ingredients">
      <h3 class="SubHeader">Ingredients</h3>
      <ul></ul>
    </div>
    <div class="HowToMake">
      <h3 class="SubHeader">Method</h3>
      <ol class="MethodWrapper"></ol>
    </div>
  </body>
</html>

By default, web pages are inherently flexible. If I open the example page, even as it is at this point, with no special work done to make it responsive, and resize the browser window, the text reflows as needed.

What about on different devices? Again, with no CSS whatsoever added to the page, this is how that renders on an iPhone XR:

Figure 1.2: Not pretty but by default all web pages are inherently flexible

As you can see, it's rendering, but like a desktop page shrunken down to fit the space available. The reason for that is that iOS renders web pages at 980px wide by default and shrinks them down into the "viewport."

Before responsive design was a thing, it was commonplace to see websites render like that on an iPhone. Nowadays, thanks to the ubiquity of responsive web design, they are as rare as rocking horse droppings!

The area of a browser window that allows a web page to be viewed is known technically as the viewport. To be clear, the viewport area excludes the browser toolbars, URL bar, and so on. From now on, we will generally use this more accurate term.

We can make the page more mobile-friendly by adding this snippet in the <head>:

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

This viewport meta tag is the non-standard, but de facto, way of telling the browser how to render the page. Although introduced to the web by Apple, rather than a standards process, it remains essential for responsive web design. We will cover the meta tag and its various settings and permutations in Chapter 3, Media Queries – Supporting Differing Viewports.

For now, you just need to know that in this case, our viewport meta tag is effectively saying "make the content render at the width of the device."

In fact, it's probably easier to just show you the effect this line has on applicable devices:

Figure 1.3: With just one line added, already things are improving dramatically

Great! Another snag fixed; the text is now rendering and flowing at a more "native size." Let's move on.

Taming images

They say a picture speaks a thousand words. All this writing about scones on our sample page and there's no image of the beauties! I'm going to add in an image of a scone near the top of the page; a sort of "hero" image to entice users to read the page.

Figure 1.4: There is a line or two of CSS that's always needed to make images appear a sensible size

Oh! That nice big image (2000px wide) is forcing our page to render more than a little wonky. We clearly need to fix that.

Ideas? Well, we could add a fixed width to the image via CSS but the problem there is that we want the image to scale to different screen sizes. For example, in CSS, our iPhone XR is 414px wide by 896px high. If we set a width of 414px to that image, what happens if a user rotates the screen? On this device, the 414px wide viewport is now 896px wide. Thankfully, it's pretty easy to achieve fluid images with a single line of CSS.

I'm going to create the css/styles.css CSS file now that's already linked in the head of the HTML page.

In our blank styles.css file, here is the first thing I'm adding. Although this could be written as a single line, I'm actually going to write it as three for the sake of legibility. Ordinarily, I'd be setting a few other defaults, and we'll discuss those defaults in later chapters, but for our purposes, I'm happy to open with just this:

img {
  max-width: 100%;
}

With that file saved and the page refreshed, we see something more akin to what we might expect.

Figure 1.5: With a little CSS, our images will never exceed their bounds

All this max-width based rule does is stipulate that all images should grow to be a maximum of 100% of their size. Where a containing element (such as the body or a div it sits within) is less than the full intrinsic width of the image, the image will simply scale up to display as large as it can within that constraint.

A brief tangent on width/max-width for images

To make images fluid, you could also use the more widely used width property. For example, width: 100%, but this has a different effect. When a property of width is used, then the image will be displayed at that width, relative to its container if using percentages, regardless of its own inherent size. The result in our example would be that the logo (also an image) would stretch beyond its intrinsic size to fill 100% of its container. With a container far wider than the image, as is the case with our logo, this leads to a massively oversized image.

Excellent. Everything is now laid out as expected. No matter the viewport size, nothing is overflowing the page horizontally.

The code samples provided throughout this book do not include "vendor prefix" styles. Vendor prefixes have been employed historically to prefix experimental CSS properties in different browsers; for example, -webkit-backface-visibility. Including vendor prefixes in CSS is often essential to achieve support for certain properties in older browsers. There are now tools to automate this prefixing and, as you might imagine, the tools perform the task faster and more accurately than we can.

Therefore, I'm refraining from including any vendor-prefixed code in the samples, in the hope you will adopt a similar painless approach. The topic of vendor prefixing, and the tools to automate it, is detailed more fully in Chapter 7, Stunning Aesthetics with CSS.

However, if we look at the page in larger viewports, the basic styles start to get both literally and figuratively stretched. Take a look at the example page at a size of around 1400px:

A close up of food

Description automatically generated

Figure 1.6: We clearly need to fix the size of this image at larger viewports!

Oh, dear! In fact, even at around 800px wide it's starting to suffer. Around this point, it would be handy if we could rearrange a few things. Maybe resize the image and position it off to one side. Perhaps alter some font sizes and background colors of elements.

Thankfully, we can achieve all this functionality quite easily by employing CSS media queries to bend things to our will.

Enter media queries

As we have established, somewhere beyond the 800px wide point, our current layout starts to look stretched. We'll use CSS media queries at this point to adjust the layout depending upon the screen width. We will cover media queries in great depth in Chapter 3, which is inventively titled Media Queries. For now, all you need to appreciate is that media queries are directives in CSS that allow us to isolate CSS rules to certain environmental conditions; the size of the screen in this instance.

Breakpoints

Before we proceed, it's worth familiarizing yourself with the term "breakpoint."

The term "breakpoint" is web developer vernacular for defining a particular viewport width or height at which a responsive design should change significantly.

When people first started making use of media queries, it was common to see designs built with specific breakpoints to cater to the popular devices of the day. At the time, it was typically iPhone (320px × 480px) and iPad (768px × 1024px) devices.

That practice was a bad decision then, and it would be an even worse one now. The problem is that doing that caters a design to specific screen sizes. We want a responsive design—something that is agnostic of the screen size viewing it, responding to any size viewport it finds itself in, not something that only looks at its best at specific sizes.

Imagine me as your well-intentioned Dad at this point. I'm furrowing my brow and insisting that "There are no specific breakpoints—use a breakpoint if your design needs it, not for a specific device!". OK, I'm taking my "Dad" hat off again now; I promise to not crack any jokes while your friends are around.

To conclude this little aside, it's important to remember that you will enjoy better results if you are guided by your design when deciding where to introduce "breakpoints."

For the purpose of whipping our basic example into shape, however, we will concentrate on just one type of media query: a minimum width media query. CSS rules within this type of media query only get applied if the viewport is or exceeds a certain width. The exact minimum width can be specified using a raft of different length units, including percent, em, rem, and px. In CSS, a minimum width media query is written like this:

@media screen and (min-width: 800px) {
  /* styles */
}

The @media directive tells the browser we are starting a media query, the screen part (declaring screen is technically not needed in this situation but we will deal with that in detail in Chapter 3, Media Queries – Supporting Differing Viewports) tells the browser these rules should be applied to all screen types. We then have the and keyword, which chains together another set of conditionals, which in this case is (min-width: 800px). That tells the browser that the rules should also be limited to all viewports at least 800px wide.

I believe it was Bryan Rieger, http://www.slideshare.net/bryanrieger/rethinking-the-mobile-web-by-yiibu, who first wrote that "The absence of support for media queries is in fact the first media query." What he meant by that is that the first rules we write outside of a media query should be our starter or "base" rules for the most basic devices, which we then enhance for more capable devices and larger screens.

That is what we are doing in this example. The basic styles are written first. It is only when we need to do something different that we introduce a media query.

This approach also facilitates a "smallest screen first" mentality and allows us to progressively layer on detail as and when the design needs to change for bigger screens.

Amending the example for a larger screen

We've already established that our design is starting to suffer at around 800px wide.

Therefore, let's mix things up a little by way of a simple example of how we can lay things out differently at different viewport sizes.

First off, we will stop that main "hero" image from getting too big and keep it over on the right. Then the intro text can sit to the left.

We will then have the main portion of the text (the "method" that describes how to make the scones) on the left below, with a small boxed-out section detailing the ingredients over on the right.

All these changes can be achieved relatively simply by encapsulating these specific styles within a media query. Here's what things look like with the relevant styles added:

A screenshot of a social media post

Description automatically generated

Figure 1.7: With a few rules added within a media query we get a different layout for larger screens

It still looks essentially the same as it did before on smaller screens but adjusts to the new layout if the viewport is 800px or wider.

There are some further visual embellishments that don't add to the understanding of what's happening responsively, hence I have omitted them here, but if you'd like to view the relevant code, download the chapter code at http://rwd.education.

Here are the layout styles that were added:

@media screen and (min-width: 800px) {
  .IntroWrapper {
    display: table;
    table-layout: fixed;
    width: 100%;
  }
  .MoneyShot,
  .IntroText {
    display: table-cell;
    width: 50%;
    vertical-align: middle;
    text-align: center;
  }
  .IntroText {
    padding: 0.5rem;
    font-size: 2.5rem;
    text-align: left;
  }
  .Ingredients {
    font-size: 0.9rem;
    float: right;
    padding: 1rem;
    margin: 0 0 0.5rem 1rem;
    border-radius: 3px;
    background-color: #ffffdf;
    border: 2px solid #e8cfa9;
  }
  .Ingredients h3 {
    margin: 0;
  }
}

That wasn't too bad, was it? With only minimal code we have built a page that responds to the viewport size and offers a preferable layout as needed. By adding just a few more styles things look even easier on the eye.

With those in place, our basic responsive page now looks like this on an iPhone:

A screenshot of a cell phone

Description automatically generated

Figure 1.8: A few more styles added and our basic page is palatable

And like this when the viewport is 800px or wider:

A screenshot of a social media post

Description automatically generated

Figure 1.9: Same HTML and CSS but different layout for larger viewports

This has been a very basic example but it has encapsulated the essential methodology of building out a responsive web design.

Let's just go over the important parts of what we have covered in this chapter and in this basic example again:

  • Use whatever text editor you like
  • Tools exist to make writing code easier but don't get hung up on what to use
  • Responsive designs are made possible with a flexible layout, fluid images, and media queries
  • A meta tag is needed in the head of your HTML so a browser knows how to render the page
  • You'll want all images to be set with a max-width of 100% in the CSS by default
  • A breakpoint is just a point, typically a screen-width, at which we use a media query to alter the design
  • When you write CSS for a responsive design, start with base styles that can work on any device—typically the smallest screen and then use media queries to adapt it for larger screens
  • Scones with clotted cream and jam are really tasty

You can find the full specifications for CSS Media Queries (Level 3) here: http://www.w3.org/TR/css3-mediaqueries/.

There is also a working draft for CSS Media Queries (Level 4) here: http://dev.w3.org/csswg/mediaqueries-4/.

The shortcomings of our example

In this chapter, we've covered all the essential component parts of building a basic responsive web page with HTML and CSS. Granted, it's not what I'd call a real looker. I'd forgive you for using words like "infantile," "lazy," and "ugly" but just do it quietly amongst yourselves; I have feelings, you know!

The point here is you and I both know that this basic responsive example is far from what we will likely be tasked with building day to day. Nor should it reflect the limit of what we are capable of building.

We need to cover typography, color, shadows, and hover styles; semantic markup; accessibility concerns; animation; scalable graphics; forms; and so much more!

You get the picture; the truth is we have barely scratched the surface. But don't worry. That's what the rest of the book is for.

Summary

Well done—you now know and understand the essential elements needed to create a fully responsive web page. However, as we have just discovered, there are plenty of places where things could be improved.

But that's fine. We don't just want the ability to make competent responsive web designs, we want to be able to create "best of breed" experiences. And as you're here, investing your time in the betterment of websites everywhere, I know you're up to the challenge. So let's press on.

In the next chapter, Chapter 2, Writing HTML Markup, we are going to take a deep dive into HTML5 markup. HTML is the very skeleton of any web page or application, the bedrock on which to build anything meaningful, the oxygen a website breathes, the... OK, I'm out of analogies—suffice it to say, HTML is pretty important, so let's press on and get stuck in.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.229.253