50,39 €
Responsive Web Design with HTML5 and CSS, Fourth Edition, is a fully revamped and extended version of one of the most comprehensive and bestselling books on the latest HTML5 and CSS techniques for responsive web design. It emphasizes pragmatic application, teaching you the approaches needed to build most real-life websites, with downloadable examples in every chapter.
Written in the author's friendly and easy-to-follow style, this edition covers all the newest developments and improvements in responsive web design, including approaches for better accessibility, variable fonts and font loading, and the latest color manipulation tools making their way to browsers. You can enjoy coverage of bleeding-edge features such as CSS layers, container queries, nesting, and subgrid.
The book concludes by exploring some exclusive tips and approaches for front-end development from the author.
By the end of the book, you will not only have a comprehensive understanding of responsive web design and what is possible with the latest HTML5 and CSS, but also the knowledge of how to best implement each technique. Read through as a complete guide or dip in as a reference for each topic-focused chapter.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 580
Veröffentlichungsjahr: 2022
Responsive Web Design with HTML5 and CSS
Fourth Edition
Build future-proof responsive websites using the latest HTML5 and CSS techniques
Ben Frain
BIRMINGHAM—MUMBAI
Responsive Web Design with HTML5 and CSS
Fourth Edition
Copyright © 2022 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Senior Publishing Product Manager: Suman Sen
Acquisition Editor – Peer Reviews: Gaurav Gavas
Project Editor: Parvathy Nair
Content Development Editor: Lucy Wan
Copy Editor: Safis Editing
Technical Editor: Tejas Mhasvekar
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Presentation Designer: Rajesh Shirsath
First published: April 2012
Second edition: August 2015
Third edition: April 2020
Fourth edition: September 2022
Production reference: 3300525
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80324-271-2
www.packt.com
Ben Frain has been a web designer/developer since 1996. He is currently employed as a UI/UX Technical Lead at bet365. Before the web, he worked as an underrated (and modest) TV actor and technology journalist, having graduated from Salford University with a degree in Media and Performance. He has written four equally underrated (his opinion) screenplays and still harbors the (fading) belief he might sell one.
He likes to pretend he isn’t a nerd but spends an inordinate amount of time building keyboards and talking about them, text editors, and the web on his blog and YouTube channel. Outside of geekery, he enjoys simple pleasures. Playing indoor football while his body and wife still allow it, and trying to keep up with his two sons.
I told the team at Packt it would take me a short age to write this book. I was true to my word! Their patience and understanding throughout was appreciated.
The team of reviewers did a sterling job; I’d like to take the chance to thank them here for giving up their time to improve this title. I’ll also extend thanks here to my editor, Lucy Wan. She shepherded everything along with efficiency, and made smart and effective amendments throughout.
Finally, thanks to my family. I was told as a child that the most important thing you can give someone is your time. I’m looking forward to having more of that to give you, whether you like it or not!
J. Pedro Ribeiro is a Brazilian software engineer based in London. He has been working on the web since the mid-90s, back when dial-up connections, GeoCities, and Netscape Navigator were a thing.
His work is focused on building performant, accessible websites and apps that deliver great user experience. Alongside web development, Pedro has worked as a technical reviewer for other publications like Mastering Responsive Web Design and Responsive Web Design Patterns, both at Packt Publishing.
He is also the author of Baseliner, a Chrome extension with over 6,000 weekly users.
Blog – jpedroribeiro.comTwitter – https://twitter.com/jpedroribeiroGitHub – https://github.com/jpedroribeiroMichelle Manemann was raised by—and with—the internet (long before it became the norm). She spent her formative years exploring the web as it evolved from simple text-only sites, to sites with pages formatted as tables within tables like so many nesting dolls, through the rise and fall of Flash, to the (relatively) standardized modern web of today. Influenced by the scrolling marquees and animated GIFs of the mid-90s, it’s perhaps fortunate that her earliest efforts in web design are lost to the sands of time (R.I.P. GeoCities).
While finalizing her degree in Anthropology from Grinnell College, Michelle rediscovered the allure of web design. Anthro B.A. in-hand, she accepted an internship that allowed her to hone her HTML and CSS in real time; her formative love of web design and its possibilities reignited immediately. Originally the sole designer in her organization, Michelle built a full-fledged Web Design Department from the ground up; a decade later, she manages a small but mighty team of fellow designers and together they create beautiful websites for educators across North America.
While this is Michelle’s first turn as a technical reviewer, she is a veteran of the publishing industry, having created hundreds of print cover designs and online web experiences for her company and its partners over the course of a decade. When business hours are over, Michelle is on the move. If she’s not exploring the natural beauty along her native Mississippi River, she’s traveling the world to uncover new founts of inspiration and creativity.
I would like to thank Packt Senior Project Editor, Parvathy, for her patient handling of my questions and comments over the better half of a year.
Any success I enjoy is due to the unconditional love and support of my parents and my youngest brother, Chase, whose humor and strength far surpass my own. I strive to be his equal in kindness every day.
Join the book’s Discord workspace to discuss all your responsive web design concerns directly with the author and interact with other readers:
https://packt.link/RWD4e
Contributors
Join our book’s Discord space
Preface
Who this book is for
What this book covers
Section I: The Fundamentals of Responsive Web Design
Section II: Core Skills for Effective Front-End Web Development
Section III: Latest Platform Features and Parting Advice
To get the most out of this book
Get in touch
Section 1: The Fundamentals of Responsive Web Design
The Essentials of Responsive Web Design
Getting the most out of this book – get to know your free benefits
The browser and device landscape
Defining responsive web design
Responsive web design in a nutshell
Browser support
Text editors
Tools for software development
Our first responsive example
Our basic HTML file
Taming images
A brief tangent on width/max-width for images
Enter media queries
Breakpoints
Amending the example for a larger screen
The shortcomings of our example
Summary
Join our book’s Discord space
Writing HTML Markup
Getting the start of HTML pages right
The doctype
The HTML tag and lang attribute
Character encoding
The forgiving nature of HTML5 markup
A sensible approach to HTML markup
All hail the mighty <a> element
New semantic elements in HTML5
The <main> element
The <section> element
The <nav> element
The <article> element
The <aside> element
The <header> element
The <footer> element
The HTML5 outline algorithm
A note on h1-h6 and the <hgroup> element
The <div> element
The <p> element
The <blockquote> element
The <figure> and <figcaption> elements
<details> and <summary> elements
The <address> element
HTML text-level semantics
The <span> element
The <b> element
The <strong> element
The <em> element
The <i> element
Obsolete HTML features
Putting HTML elements to use
WCAG accessibility conformance and WAI-ARIA for more accessible web applications
Web Content Accessibility Guidelines (WCAG)
WAI-ARIA
Taking ARIA further
Embedding media in HTML5
Adding video and audio in HTML
Providing alternate media sources
Audio and video tags work almost identically
Responsive HTML5 video and iframes
The modern way to embed iframes and keep aspect ratio
The loading attribute
The <dialog> element
Summary
An exercise
Media Queries and Container Queries
The meta viewport tag
Why media queries are needed for a responsive web design
Basic conditional logic in CSS
Media query syntax
Media queries in link tags
Media query on an @import at-rule
Media queries in a CSS file
Inverting media query logic
Combining media queries
A number of different media queries
Everyday media queries
What can media queries test for?
Using media queries to alter a design
Advanced media query considerations
Do media queries affect which files get downloaded or how the page renders?
Should you split media queries into their own files?
Consolidate media queries or scatter them where it suits?
What about file size?
Media Queries Level 5
Interaction media features
The pointer media feature
The hover media feature
User preference media features
The prefers-color-scheme media feature
The prefers-reduced-motion feature
Future possibilities
Container queries
This may change!
Using a container query
Why name the container?
Container relative lengths
Possibilities
Summary
Join our book’s Discord space
Fluid Layout and Flexbox
Converting a fixed pixel design into a fluid proportional layout
Why do we need Flexbox?
Introducing Flexbox
The bumpy path to Flexbox
Choosing your autoprefixing solution
Getting Flexy
Perfect vertically centered text
Offset items
Reverse the order of items
How about if we want them laid out vertically instead?
Column reverse
Inline-flex
Flexbox alignment properties
align-items
align-self
Possible alignment values
justify-content
The flex property
Simple sticky footer
Changing the source order
Wrapping with flex
Wrapping up Flexbox
Summary
Layout with CSS Grid
What CSS Grid is and the problems it solves
Basic Grid syntax
Grid-specific concepts and terminology
Setting up a Grid Layout
Explicit and implicit
grid-auto-rows and grid-auto-columns
grid-auto-flow
Placing and sizing Grid Layout items
gap
repeat
fr units
Placing items in the grid
span
dense
Named grid lines
grid-template-areas
auto-fit and auto-fill
The minmax() function
Shorthand syntax
grid-template shorthand
grid shorthand
grid shorthand value – option one
grid shorthand value – option two
grid shorthand value – option three
Allowing nested elements to take part in the Grid
The subgrid value
Applying what you have learned so far
Summary
Section 2: Core Skills for Effective Front-End Web Development
CSS Selectors, Typography, and More
Selectors, units, and capabilities
Anatomy of a CSS rule
Pseudo-elements and pseudo-classes
CSS selectors – beyond the normal!
CSS attribute selectors
CSS substring matching attribute selectors
The “beginning with” substring matching attribute selector
The “contains an instance of” substring matching attribute selector
The “ends with” substring matching attribute selector
Chaining attribute selectors
CSS structural pseudo-classes
The :last-child selector
The nth-child selectors
Understanding what nth rules do
nth-based selection in responsive web designs
Combinator selectors – child, next sibling, and subsequent sibling
The child combinator
The next sibling
The subsequent sibling
The negation (:not) selector
The empty (:empty) selector
Grouping selectors
The :is() functional pseudo-class
The :where() functional pseudo-class
The :has() relational pseudo-class
Responsive viewport relative lengths
Using @supports to fork CSS
Feature queries
Combining conditionals
Web typography
System fonts
The @font-face CSS rule
Implementing web fonts with @font-face
Optimizing font loading with font-display
font-display
Variable fonts
font-face changes
How to make use of a variable font
Registered axis
Custom axis
Font features
Exercise
Summary
Join our book’s Discord space
CSS Color
RGB color
HSL color
Alpha channels
Alpha with hex
Alpha with functional notation
Space-separated functional color notation
Color concepts and terminology
Color space
Gamut
The current state of CSS color
Introductory note
Display-P3
@media (color-gamut) media query
LCH with the lch() function
OKLab and OKLCH
Fallbacks for older browsers
The color-mix() function
The color-contrast() function
Relative colors with the relative color syntax
Summary
Resources
Stunning Aesthetics with CSS
Text shadows
Multiple text shadows
Box shadows
Inset shadow
Multiple shadows
Understanding spread
Background gradients
The linear-gradient notation
Specifying gradient direction
Color stops
Radial background gradients
Handy “extent” keywords for responsive sizing
Conic gradients
Repeating gradients
Background gradient patterns
Multiple background images
Background size
Background position
Background shorthand
High-resolution background images
CSS filters
Available CSS filters
Combining CSS filters
A warning on CSS performance
CSS clip-path
CSS basic shapes
clip-path with a circle
clip-path with ellipse
clip-path with inset
clip-path with polygon
clip-path with URL (clipping source)
Animating clip-path
mask-image
mix-blend-mode
Summary
Responsive Images
Modern image formats
AVIF image format
WebP image format
Image format comparisons
Using the picture element to progressively enhance images
The inherent problem of responsive images
Simple resolution switching with srcset
Advanced switching with srcset and sizes
Did you say the browser “might” pick one image over another?
Art direction with the picture element
A practical note on providing alternate image formats and sizes
Summary
Join our book’s Discord space
SVG
A brief history of SVG
An image that is also a readable web document
The root SVG element
Namespace
The title and desc tags
The defs tag
The g element
SVG shapes
SVG paths
Creating SVGs with popular image editing packages and services
Saving time with SVG icon services
Inserting SVGs into your web pages
Using an img tag
Using an object tag
Inserting an SVG as a background image
A brief aside on data URIs
Generating image sprites
Inserting an SVG inline
Reusing graphical objects from symbols
Inline SVGs allow different colors in different contexts
Making dual-tone icons that inherit the color of their parent
Re-coloring SVGs with CSS custom properties
Reusing graphical objects from external sources
What you can do with each SVG insertion method (inline, object, background-image, and img)
Extra SVG capabilities and oddities
SMIL animation
Styling an SVG with an external style sheet
Styling an SVG with internal styles
SVG properties and values within CSS
Animating an SVG with CSS
Animating SVG with JavaScript
A simple example of animating an SVG with GreenSock
Using SVGs as filters
A note on media queries inside SVGs
Optimizing SVGs
SVG implementation tips
Summary
Further resources
Transitions, Transformations, and Animations
What CSS transitions are and how we can use them
The properties of a transition
The transition shorthand property
Transitioning different properties over different periods of time
Understanding timing functions
CSS 2D transforms
Scale
Translate
Using translate to center absolutely positioned elements
Rotate
Skew
Matrix
The transform-origin property
CSS 3D transformations
The translate3d property
A progressive enhancement example using translate3d
Animating with CSS
The animation-fill-mode property
Exercises and training
Summary
Custom Properties and CSS Functions
Working with custom properties
Simple theming
Setting and getting custom property values with JavaScript
Custom properties and specificity
Setting a fallback value
env() environment variables
Custom properties and web components
CSS functions
calc()
min()
max()
clamp()
Putting it all together
Summary
Join our book’s Discord space
Forms
HTML5 forms
Understanding the component parts of HTML5 forms
The placeholder attribute
Styling the placeholder text
Styling the input caret with the caret-color CSS property
The required attribute
The autofocus attribute
The autocomplete attribute
The list attribute and the associated datalist element
HTML5 input types
The email input type
The number input type
Using min and max to create number ranges
Changing the step increments
The url input type
The tel input type
The search input type
The pattern input attribute
The color type input
Date and time
The date input type
The month input type
The week input type
The time input type
The range input type
Styling HTML5 forms with CSS
Indicating required fields
Creating a background fill effect
Summary
Section 3: Latest Platform Features and Parting Advice
Cutting-Edge CSS Features
Cascade layers
Naming cascade layers
Where to declare layers
Adding rules to layers
The priority of rules in and outside of layers
Nesting layers inside other layers
The importance of !important
!important in cascade layers
Old browsers
CSS nesting
Nesting conditionals such as media queries
Trying CSS nesting syntax today
Giving your feedback on the proposal
Asking browser vendors to implement CSS nesting
Summary
Bonus Techniques and Parting Advice
Truncating text
Single-line truncation
Multi-line truncation
Creating horizontal scrolling panels
Styling scrollbars
CSS Scroll Snap
The scroll-snap-type property
The scroll-snap-align property
The scroll-snap-stop property
Smooth scrolling with CSS scroll-behavior
Parting advice
Getting designs in the browser as soon as possible
Testing on real devices
Embracing progressive enhancement
Defining a browser support matrix
Functional parity, not visual parity
Choosing the browsers to support
Tiering the user experience
Avoiding CSS frameworks in production
Hiding, showing, and loading content across viewports
Validators and linting tools
Performance
Performance tools
The next big things
Summary
Join our book’s Discord space
Unlock Your Book’s Exclusive Benefits
How to unlock these benefits in three easy steps
Step 3
Need help?
Other Books You May Enjoy
Index
Cover
Index
When I wrote the first edition of this book in 2011 and 2012, it was by no means certain that responsive web design would become the de facto approach for web design for the foreseeable future. Here we are, 10 years and three further editions later, and its popularity and utility show no sign of abating.
There’s a saying that is apt for the authors of technical books, “When one person teaches, two people learn.” That’s certainly been the case each time I write a new edition. I’ve learned so much more covering these topics than I imagined I would. In my day-to-day work, I already find myself coming back to certain chapters and sections when trying to refresh my memory on how to do one thing or another that I have subsequently forgotten. I hope these pages prove as resourceful for you!
Thinking back on the contents of the first edition, it’s also struck me just how capable the technologies we have at our disposal have become. If you are an old hand at the web development game, feel free to jump right in to some of the newest topics such as CSS color or cascade layers – I’d be shocked if you didn’t come away the least bit excited. Many of the things now trivial would have blown my mind a decade ago.
I won’t waste any more of your precious time here. Thank you for taking the time to read this book. I hope you enjoy this latest edition and take plenty from it. Please reach out to me via my website at benfrain.com with your thoughts, both good and bad, and any questions that arise. They will naturally inform the content of any future editions.
Finally, while the publishers mention it again in a moment, if you do enjoy it, please consider adding a review on Amazon or your book store of choice. From a commercial point of view, it really does help with sales. From a personal perspective, it’s really lovely to read them and know people around the world are making use of something you spent so long working on.
It should go without saying here that if you don’t enjoy it, please keep your opinions to yourself!
Are you a full stack or backend developer who needs to improve their frontend skills? Perhaps you work on the frontend and you need a definitive overview of all modern HTML and CSS has to offer? Maybe you have done a little website building but you need a deep understanding of responsive web designs and how to achieve them? This is the book for you!
All you need to take advantage of this book is a working understanding of HTML and CSS. No JavaScript knowledge is needed.
Chapter 1, The Essentials of Responsive Web Design, is a whistle-stop tour of the key ingredients in coding a responsive web design.
Chapter 2, Writing HTML Markup, covers all the semantic elements of HTML5, text-level semantics, and considerations of accessibility. We also cover how to insert media such as video into our pages and how to use the new dialog element.
Chapter 3, Media Queries and Container Queries, covers everything you need to know about CSS media queries: their capabilities, the syntax, and the various ways you can wield them. There is also an overview of container queries.
Chapter 4, Fluid Layout and Flexbox, covers how to convert designs into proportional layouts and provides a thorough exploration of Flexbox layouts.
Chapter 5, Layout with CSS Grid, is a deep dive into the two-dimensional layout system of CSS grid, with an explainer of how to make use of the new subgrid property.
Chapter 6, CSS Selectors, Typography, and More, gets us to grips with the endless possibilities of CSS selectors, feature queries, and web typography, including variable fonts, viewport relative units, and a whole lot more.
Chapter 7, CSS Color, covers the latest developments in expressing colors and color manipulation, including Lab/LCH, P3 color, and new color functions like color-contrast and color-mix.
Chapter 8, Stunning Aesthetics with CSS, covers CSS filters, box shadows, linear and radial gradients, multiple backgrounds, and how to target background images to high-resolution devices.
Chapter 9, Responsive Images, covers how to make use of new image formats like AVIF and WebP, and how to make the most relevant version of an image available to the browser.
Chapter 10, SVG, teaches us everything we need to use SVG graphics inside documents and as background images, as well as how to interact with them using JavaScript.
Chapter 11, Transitions, Transformations, and Animations, gets our CSS moving as we explore how to make interactions and animations using CSS.
Chapter 12, Custom Properties and CSS Functions, covers the many benefits of custom properties, then moves on to the utility of new CSS functions like min(), max(), and clamp().
Chapter 13, Forms, shows us how the latest HTML5 and CSS features make interacting with forms easier than ever before. Many HTML input types give you easy access to the relevant software keyboard on mobile devices.
Chapter 14, Cutting-Edge CSS Features, covers how to use CSS layers to better organize your code and how to write nested CSS, hopefully coming to your browser in the near future.
Chapter 15, Bonus Techniques and Parting Advice, explores the essential considerations before embarking on a responsive web design and also provides a few last-minute nuggets of wisdom to aid you in your responsive quest.
The code bundle for the book is hosted at the book’s dedicated website at https://rwd.education/, as well as on GitHub at https://github.com/benfrain/rwd4. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: “We can fix that prior problem easily by adding this snippet in the <head>.”
A block of code is set as follows:
img { max-width: 100%; }When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
img { max-width: 100%; display: inline-flex; }Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes. For example: “When writing HTML, you will typically be marking up or writing content inside a series of tags or elements.”
Warnings or important notes appear like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome.
General feedback: Email [email protected], and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit http://www.packtpub.com/submit-errata, selecting your book, clicking on the Submit New Errata link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.
Once you’ve read Responsive Web Design with HTML5 and CSS, Fourth Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
This first section is described as fundamental, as it is the section on which the other two build. In Chapter 1, The Essentials of Responsive Web Design, we will create our first fully responsive website. In Chapter 2, Writing HTML Markup, we are going to understand how to express meaning through markup. Avoid understanding HTML elements at your peril! Many problems in web development, even among seasoned developers, can be avoided simply by using structured and semantic markup. Finally, in Chapter 3, Media Queries and Container Queries, we will learn how to encapsulate styles that only apply in certain eventualities, functionality that’s a cornerstone of responsive web design. The final two chapters, Fluid Layout and Flexbox, and Layout with CSS Grid, conclude this first section, covering the two most powerful layout methods available to us in modern web design, Flexbox and Grid.
If you feel these are topics you already have a strong grasp of, go right ahead and skip to the next section. Otherwise, take the time to deeply understand these fundamentals before moving on. With the fundamentals understood, everything that comes later – in this book, and in your web adventures – will be so much easier to achieve.
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. A decade later, as I write this in 2022, it’s simply the de facto standard. If you’re building a website or web application and it isn’t responsive, you’re probably doing it wrong!
This first chapter serves as a quick and basic refresher on building out an extremely simple web design, responsively. By the end, we will have covered everything needed to author a fully responsive web page.
You might be wondering, why do we need the other chapters then? By the end of this chapter, that should be apparent too.
Here’s what we will cover in this first chapter:
The ever-evolving browser and device landscapeDefining responsive web designSetting browser support levelsA brief discussion on development tools and text editorsOur first responsive example: a simple HTML5 pageThe viewport meta tagFluid imagesWriting CSS3 media queries to make pages adaptThe shortfalls in our basic exampleWhy our journey has only just begunAre you sitting comfortably? Then we will begin!
Unlock exclusive free benefits that come with your purchase, thoughtfully crafted to supercharge your learning journey and help you learn without limits.
Here’s a quick overview of what you get with this book:
Figure 1.1: Illustration of the next-gen Packt Reader’s features
Our web-based reader, designed to help you learn effectively, comes with the following features:
Multi-device progress sync: Learn from any device with seamless progress sync.
Highlighting and notetaking: Turn your reading into lasting knowledge.
Bookmarking: Revisit your most important learnings anytime.
Dark mode: Focus with minimal eye strain by switching to dark or sepia mode.
Figure 1.2: Illustration of Packt’s AI assistant
Our interactive AI assistant has been trained on the content of this book, so it can help you out if you encounter any issues. It comes with the following features:
Summarize it: Summarize key sections or an entire chapter.
AI code explainers: In the next-gen Packt Reader, click the Explain button above each code block for AI-powered code explanations.
Note: The AI assistant is part of next-gen Packt Reader and is still in beta.
Figure 1.3: Free PDF and ePub
Learn without limits with the following perks included with your purchase:
: Learn from anywhere with a DRM-free PDF copy of this book.
: Use your favorite e-reader to learn using a DRM-free ePub version of this book.
Take a moment to get the most out of your purchase and enjoy the complete learning experience.
https://www.packtpub.com/unlock/9781803242712
Note: Have your purchase invoice ready before you begin.
A little over a decade ago, it was reasonable to build websites with fixed widths. The device landscape was a whole lot more limited, so the expectation was that all end users would get a fairly consistent experience. This fixed width (typically 960 px 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 accessed and interacted 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 recorded at gs.statcounter.com:
…in the 12 months from July 2010 to July 2011, global mobile browser use had risen from 2.86 to 7.02 percent…
By September 2019, writing the third edition, using StatCounter, mobile was a whopping 51.11%, desktop was 45.18%, and tablet was 3.71%.
As I write this latest edition, the latest data at gs.statcounter.com for July 2022 shows an even more pronounced change with mobile at 60.73%, desktop at 37% and tablet at 2.27%..
The indisputable fact is that the number of people using smaller-screen devices to view the internet is growing at an ever-increasing rate, while at the other end of the scale, 40-inch ultrawide displays are now also commonplace (along with various tablet and console devices). There is now more 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, device/browser capabilities).
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.
To attempt to put the philosophy of responsive web design in 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.
The sheer volume of disparate devices that access the web means most people understand the need for technical solutions that cater to most devices.
The popularity and ubiquity of responsive web design usually make 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 and works on phones as well as computers.”
However, one question that almost always comes up when starting a responsive design project is that of 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 work and code required to achieve feature or aesthetic parity with modern, evergreen browsers such as Firefox or Chrome. Be as pragmatic as possible.
By the same token, we are going to practice progressive enhancement, in essence, starting with a functional and accessible website for the most basic browsers, which will get 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 or device.
Ultimately, the only browser statistics that really matter are yours.
If you are 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 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 to.
For example, if you’re unlucky enough to have 25% of your website visitors stuck using old versions of iOS (for example), you’ll need to consider what features that browser supports and tailor your solution accordingly.
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 on browser X, don’t develop specific solutions for browser X.
Figure 1.4: Can I Use provides browser support data for every web platform feature
It makes no difference what tool you use to write your code. All you actually need is something that enables you to type HTML, CSS, and JavaScript. Whether your preference is Sublime Text, Vim, Emacs, Nova, Visual Studio Code, or Notepad – it matters little. Just use what works best for you.
Similarly, there are no requisite tools that are essential to get responsive web design out of the door. That said, you should be aware that there are many freely available tools to negate many of the manual and time-intensive tasks of building websites.
CSS post-processors such as PostCSS can automate horrible and thankless jobs like CSS vendor prefixing, an old requirement that necessitated writing multiple versions of a property for each browser engine, and poly-filling new CSS features, where newer syntaxes can be made to work on older browsers. Linting and validation tools can check your HTML, JavaScript, and CSS code as you work, eliminating many time-wasting typos or syntax-induced errors. More recently, code formatters have become popular. 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, while 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 front-end code as quickly and reliably as possible.
With that out of the way, without further ado, let’s get our first responsive web design made!
In the introduction, 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://github.com/benfrain/rwd4 or the book’s dedicated website, rwd.education. It’s worth knowing that where individual examples are built up throughout a chapter, there will typically be a “start” and “end” version for each. The start contains just the essentials to start following along. The end contains the completed exercise/example.
We will start with a simple HTML5 structure. Don’t worry at this point about what each of the lines does, especially the content of the <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 divs, a graphic for a logo, some text, and a list of items. Although you can see more of that content in the screengrabs, below is a shorter version of the code. 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 https://github.com/benfrain/rwd4 or the rwd.education website.
<!DOCTYPE html><htmlclass"no-js"lang"en"><head><metacharset"utf-8" /><title>Our first responsive web page with HTML5 and CSS3</title><metaname"description"content"A basic responsive web page – an example from Chapter1" /><linkrel"stylesheet"href"css/styles.css" /></head><body><divclass"Header"><ahref"/"class"LogoWrapper" ><imgsrc"img/SOC-Logo.png"alt"Scone O'Clock logo" /></a><h1class"Strap">Scones: the most resplendent of snacks</h1></div><divclass"IntroWrapper"><h2class"IntroText"> Occasionally maligned and misunderstood; the scone is a quintessentially British classic. </h2><divclass"MoneyShot"><pclass"ImageCaption"> Incredible scones, picture from Wikipedia </p></div></div><p>Recipe and serving suggestions follow.</p><divclass"Ingredients"><h3class"SubHeader">Ingredients</h3><ul></ul></div><divclass"HowToMake"><h3class"SubHeader">Method</h3><olclass"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 re-flows as needed.
What about on different devices? Again, with no CSS whatsoever added to the page, this is how that renders on an iPhone 13:
Figure 1.5: 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 980 px 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 a web page is allowed to be viewed in is known technically as the viewport. To be clear, the viewport area excludes the browser toolbars and URL bar etc. 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>:
<metaname"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 standard 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 and Container Queries.
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.6: 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 to images.
They say a picture speaks a thousand words. All this writing about scones in 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.7: 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 414 px wide by 896 px high. If we set a width of 414 px to that image, what happens if a user rotates the screen? On this device, the 414 px-wide viewport is now 896 px 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. 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.8: 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.
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.
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 around 1400 px:
Figure 1.9: We clearly need to fix the size of this image for larger viewports
Oh dear! In fact, at even around 800 px 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.
As we have established, somewhere beyond the 800 px-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, but for now, all you need to appreciate is that media queries are directives in CSS that allow us to isolate CSS rules to certain environment conditions; size of screen, in this instance.
Before we proceed, it’s worth familiarizing you with the term “breakpoint.”
The term breakpoint is web developer vernacular to define a 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 (320 px x 480 px) and iPad (768 px x 1024 px) devices.
That practice was a bad decision then, and it would be an even worse one now. The problem is that doing that means a design caters 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 its best at specific sizes.
Use a breakpoint if your design, visually, needs to change at a certain point, but not to cater to a specific device!
For the purpose of whipping our basic example into shape, 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) tells the browser these rules should be applied to all screen types, and we then have the and keyword, which chains together another set of conditionals, which in this case is the (min-width: 800px). That tells the browser that the rules should also be limited to all viewports at least 800 px 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.
We’ve already established that our design is starting to suffer at around 800 px width. 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 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.
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) { body { border-left: 4px solid #f9f9f9; border-right: 4px solid #f9f9f9; padding: 1rem2rem; } .IntroWrapper { display: flex; gap: 020px; flex: 11 auto; align-items: center; } .MoneyShot, .IntroText { margin: 0; flex: 1150%; } .MoneyShotImg { filter: drop-shadow(0020px#0008); border: 0; } .IntroText { padding: 0.5rem; font-size: 2.5rem; text-align: left; position: relative; } .Ingredients { font-size: 0.9rem; float: right; padding: 1rem; margin: 000.5rem1rem; border-radius: 3px; background-color: #ffffdf; border: 9px solid #debb71; } .Ingredientsh3 { 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:
Figure 1.10: A few more styles added and our basic page is palatable
And like this when the viewport is 800 px or wider:
Figure 1.11: The same HTML and CSS provides a different layout for larger viewports
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.
This has been a very basic example but it has encapsulated the essential methodology of building out responsive web design.
Let’s just go over the important points we have covered in this chapter and our basic example:
Use whatever text editor you likeTools exist to make writing code easier, but don’t get hung up on what to useResponsive designs are made possible with a flexible layout, fluid images, and media queriesA meta tag is needed in the head of your HTML so a browser knows how to render the pageYou’ll want all images to be set with a max width of 100% in the CSS by defaultA breakpoint is just a point, typically a screen width, at which we use a media query to alter the designWhen you write CSS for responsive design, start with base styles that can work on any device, typically the smallest screen, and then use media queries to adapt for larger screensScones with clotted cream and jam are really tastyYou can find the full specifications for CSS Media Queries (Level 3) here: https://www.w3.org/TR/mediaqueries-3/.
There is also a working draft for CSS Media Queries (Level 4) here: https://drafts.csswg.org/mediaqueries-4/.
In this chapter, we’ve covered all the essential parts of building a basic responsive web page with HTML and CSS. Granted, it’s not what I’d call a real looker. I’ll 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 the limit of 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, 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.
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 for 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.
Got any burning questions? Join the book’s Discord workspace to discuss all your responsive web design concerns directly with the author and interact with other readers:
https://packt.link/RWD4e
HTML stands for HyperText Markup Language. It is a language that allows content to be marked up in a manner that makes it more understandable to technology, and then, in turn, humans. You can have content on the web without CSS or without JavaScript. But you can’t have human-friendly content without HTML.
It’s a common misconception that HTML is the “easy” part of authoring web pages and applications. Writing the HTML is often dismissed out of hand as something anyone can do easily. My experience tells me otherwise. Also consider that for users who require the use of assistive technology to browse the web, the way you author HTML can mean the difference between a confusing unusable mess and a meaningful, useful, and delightful experience. Writing good quality HTML is not a specific need of responsive web design. It’s far more important than that. It’s a prerequisite of anything that you want to be accessible to all users of the web.
This chapter is therefore going to be about writing HTML markup. We will be considering the “vocabulary” of HTML; its semantics. More succinctly, the way we can use the elements of HTML to describe the content we place in markup. HTML is what’s known as a living standard. A few years back, the latest version was typically referred to as HTML5, a buzzword that helped identify modern web techniques and approaches. It’s the reason this book was originally named Responsive Web Design with HTML5 and CSS3 instead of simply Responsive Web Design with HTML and CSS. Back in 2012, you could more easily highlight that your techniques were modern by using “HTML5” and “CSS3”. As I write this in 2022, this distinction is less important. To read the living standard of HTML, head over here: https://html.spec.whatwg.org/multipage/.
The topics we will cover in this chapter are:
Starting HTML pages correctly