Unofficial Responsive Web Design Quick Reference

Introduction

This quick reference is an organised and tidied up version of my notes from freeCodeCamp's Responsive Web Design course. Credit to the original authors on freeCodeCamp. And further credit to developers.mozilla and w3schools where I found additional information. Please feel free to contact me on alex@alexroan.com if you spot any errors or have any suggested changes.

- Alexander

HTML

Basic layout

The basic layout of an html document includes several key tags which provide information about the document and provide the structure for the page. The basic order is:

        
          <!DOCTYPE html>
          <html lang="en">
            <head>
              <title>Example page title</title>
              <meta name="description" content="example description text" />
              <meta charset="UTF-8" />
              <meta name="viewport" content="width=device-width, initial-scale=1.0" />
              <link href="styles.css" rel="stylesheet" />
            </head>
            <body>
              <header></header>
              <main></main>
              <footer></footer>
            </body>
          </html>
        
      

Google fonts and fontawesome icons

During the exercises additional links were added to the html head to access additional fonts from google fonts and icons from fontawesome. Detailed instructions are available at:

<head>
    <!-- example to get Open Sans font family from google -->
    <link href="https//fonts.googleapis.com/css?family=Open+Sans:400,700,800" rel="stylesheet"/>

    <!-- register at fontawesome to get a personalised url -->
    <link href="url from fontawesome" rel="stylesheet"/>
</head>

General

Identifying elements (id class)

Id

In general id is used to identify specific html elements. In CSS a hashtag is used to refer to an id e.g. #exampleID

<input type="radio" id="exampleID">

Class

In general class is used to identify html elements. One class can be applied to many elements. In CSS a full stop is used to refer to a class e.g. .exampleClass

<div class="exampleClass1"></div>
<!-- More than one class can be used separated by a space -->
<div class="exampleClass1 exampleClass2"></div>

Layout elements

Heading h1

Paragraph p

List ul

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag. While an ordered list starts with <ol>

<ul>  
  <li>list item 1</li>  
  <li>list item 2</li>  
  <li>list item 3</li>  
</ul>

Div

Div is an element that is primarily used to provide structure and formatting to a page where other more specific elements are not available

<div class="classOne classTwo"> </div> <!-- attaching multiple classes -->
<div id="id"> </div> <!-- using id to connect items to CSS -->

Span

Span is typically used to mark text or part of a document for formatting

Section

Section is used to mark generic standalone section of a document, it should always have a heading. As it can be tricky to know whether to use a section or more specific CSS element here are some guidelines found on Mozilla:

Developers Mozilla - section

Article

Article is commonly used to group multiple elements with related information. For example in the exercises an article with a class attribute is used to style all nested elements of a particular type:

Divider hr

W3 schools defines the purpose of hr to make a thematic break or shift of topic.

Line break br

The br element inserts a single line break.

Table

Tables can be created in CSS with a set structure of elements.

<!-- to illustrate, here is a table from the exercises -->
<table>
    <caption>Assets</caption>
    <thead>
        <tr>
            <td></td>
            <th><span class="sr-only year">2019</span></th>
            <th><span class="sr-only year">2020</span></th>
            <th class="current"><span class="sr-only year">2021</span></th>
        </tr>
    </thead>
    <tbody>
    <!-- repeat following for each row, only 1 row shown -->
        <tr class="data">
            <th>Cash <span class="description">Current cash on hand.</span></th>
            <td>$25</td>
            <td>$30</td>
            <td class="current">$28</td>
        </tr>
    </tbody>
</table>

Inputs

Form

The form element is used to create an HTML form for user input. It can contain various input elements. Form attributes:

When a form element contains a button element and the button attribute type is set to submit the button will trigger sending the nearest parent form. Form data for a button is based on it’s name and value attributes.

<form action="https://freecodecamp.org/practice-project/accessibility-quiz" method="POST">
<button type="submit">Submit</Submit>
</form>

Fieldset

Fieldset is used to group various form elements. It draws a box around them. It is block level by default.

<fieldset></fieldset>

Legend

<legend></legend>

Label

Label associates text with an input element. These are inline by default. Add display: block to CSS to change

<label for="id"></label>

Input

The input element is used to get user-input. It has a wide range of types with specific formats and behaviours.

<label for="id"></label>
<input id="id" name="name" />
<label><input id="id" name="name"></label>

Select

Select is a container for a group of option elements. Think of a dropdown list. The option element acts as a label for each possible dropdown selection

<select required>
<option value="1">option text</option>
<option value="2" selected>option text 2</option>
</select>

Textarea

Textarea provides a sinple text entry box

<textarea></textarea>

Button

<button type="button">text</button>

Image

Image is used to insert an image based on a url

<img src="https://address.jpg" alt="accessibility text">
<img src="https://cdn.freecodecamp.org/platform/universal/fcc_meta_1920X1080-indigo.png"
alt="freecodecamp logo"
class="hero-img"
loading="lazy"
width="400">

<a href="https://link.com"><img src="https://address.jpg"></a> // img with link

Anchor

Anchor is used for links

<a href="https://link.com">link text</a>
<a href=#student-info>INFO</a> <!-- link within a page by id -->
<p class="author-name"><a href="https://freecodecamp.org" target="_blank">By freeCodeCamp</a></p>

Icon

In the exercises icons are used, these can be sourced from fontawesome

<!-- a few examples from the course exercises -->
<i class="fab fa-facebook-f"></i>
<i class="fab fa-twitter"></i>
<i class="fab fa-instagram"></i>
<i class="fab fa-linkedin-in"></i>
<i class="fab fa-youtube"></i>
<i class="fa fa-github" aria-hidden="true"></i>

Other topics

HTML formatting

While the focus is on formatting with CSS the exercises include a number of examples of formatting directly in HTML

<em>text</em> // emphasis
<strong>text</strong> // bold
<ul><li>text</li></ul> // unordered list
<ol><li>text</li></ol> // ordered list
<blockquote>text</blockquote> // blockquote

CSS

General

Selectors

These are used to target html and apply CSS. The :root (root), and * (global) selectors are higher level and apply across the html document. Below that individual html elements can be selected by directly using html tags; h1, header, main, nav, p etc.

More control can be achieved by using id and class

* {
    border: 1px solid black;    
}

:root { } /* root selector is the highest level in CSS */
* { } /* global selector */
element1, element2, element3 { } /* select multiple elements */
header h1 { } /* select elements based on hierarchy */
.name { } /* class selector */
#name { } /* id selector */
.className1, .className2 { } /* multiple class selector */
.gallery img { } /* select element within a class */
.className1 * {} /* all descendent selectors in a class */
nav > ul { } /* child combinator selector: target elements that match the second selector and are a direct child of the first */
.info > input, .info > label { } /* selecting two with child combinator */
element[class="className"] {} /* select specific elements with a specific class name */
element.className {} /* the above will select element where the only class is className, this will select those that include */
span[class~="sr-only"] {} /* select any <span> whose class includes sr-only */
#id span[class] { } /* target any <span> within #id that has a class */

Psuedo selectors

Pseudo selectors provide additional control. These can be used to affect an item relative to an element (e.g. before), they can also be used to apply CSS to links, and also to set rules based on language. Tips:

p::before {} /* insert content before every <p> element */
p::after {} /* insert content after every <p> element */
p::first-letter {} /* select the first letter of every <p> element */
p:first-of-type {} /* Selects every <p> element that is the first <p> element of its parent */
p:first-child {} /* selects every <p> element that is the first child of its parent */
p:nth-of-type(2) {} /* select every <p> element that is the 2nd <p> element of it's parent */*
p:last-of-type {} /* Selects every <p> element that is the last <p> element of its parent */

.class1 p:not(.class2) {} /* select all elements (class1) that do no match a given CSS rule (class2) */

:lang {} /* different rules for different languages */

a:link {}
a:visited {}
a:hover {} /* must come after a:link */
a:active {} /* must come after a:hover */

Layout

Initial page setup

Browsers apply some default settings to a page. The following settings remove default margin, padding, scrollbars and help to normalise the window.

body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100vh;
    overflow: hidden;
}

Layout tip: Add border: 1px solid black to everything to aid with design process as you can see all your element shapes * {border: 1px solid black;}

CSS box model

Box sizing

Box sizing controls whether padding and borders are added on top of content width or if content is shrunk to include them.

html {
box-sizing: border-box; /* Elements include padding & borders in dimensions. */
box-sizing: content-box; 
}

*, ::before, ::after {
box-sizing: inherit
}

Grid

Grid provides the ability to define a grid-container using display: grid;. The number of columns and rows of the grid can be specified with grid-template-columns & grid-template-rows. Child elements can then be placed inside the grid with grid-colum and grid-row.

/* set up grid */
display: grid;

/* examples of defining grid dimensions */
grid-template-columns: 200px 600px; /* 2 columns */

/* example of gap */
row-gap: 3rem;
gap: 2rem; /* sets row and column gap. With 2 values sets row, then column */

/* item placement */
align-items: center; /* align on vertical */
justify-content: center; /* align on horizontal */
place-items: center; /* align-items & justify-content at same time. If two values 1st is used for align-items */

/* properties for child-items */
grid-column: 2 / 3; /* Determines which column an element starts and ends in */
grid-auto-flow: column; /* autoplacement based on content */
grid-auto-columns: 1fr; /* overide grid-auto-flow */

/* sizing examples */
grid-template-columns: 1fr 94rem 1fr; /* 3 columns using fractions */
grid-template-columns: repeat(3, 1fr); /* 3 columns using a fracation */
grid-template-columns: minmax(2rem, 1fr) minmax(min-content, 94rem) minmax(2rem, 1fr); /* 3 columns using minmax */
grid-template-rows: repeat(3, min-content); /* rows that size based on content */

Terminology:

Parent properties:

Child properties:

Special units & sizing

Flexbox

Flexbox provides the ability to define an element as a flex container. Direct children of the container are then known as flex items. The children can then be arranged in a row or column direction. Alignment and wrapping can also be controlled. Alignment options are similar to those described in grid

display: flex;
flex-direction: row; /* stack items in a row */
flex-direction: column; /* stack items in a column */
flex-wrap: wrap; /* specify if items should wrap */
flex-flow: row wrap; /* shorthand for direction + wrap */
justify-content: center; /* options: flex-start, flex-end, space-around, space-evenly, space-between */
align-items: center; /* options: flex-start, flex-end, stretch, baseline */
align-content: space-between; /* options: space-around, stretch, center, flex-start, flex-end */

Columns with column-width

As an alternative to using grid columns can be created by specifying width.

column-width: 25rem;

Position, top right left bottom, z-index

Position

There are a choice of position properties for elements within CSS. Depending on the proprty selected the top, right, left and bottom values can be set to move elements around.

Top, right, left, bottom

Z-Index

position: fixed;
top: 0; // fix to the top of a container
z-index: 999;

/* center an item with CSS */
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
margin: auto;

Float

Places an element on the left or right side of its container, allowing text and inline elements to wrap around it.

float: left; /* 

Display

Display options:

Divider

An easy way to create dividers is to use <div> elements, and assign them to a specific class with border values

<div class="divider"></div>
.divider {
bottom-border: 1px solid #888989;
margin: 2px 0;
}

Margin

The space surrounding an element. - Top, bottom, left and right values can be set in a variety of ways. - Add a <p> selector and set margins to 0 to remove default whitespace - Setting margin to 0 will remove scrollbars (added by default by some browsers)

margin: 0; /* remove all margins */
margin: auto; /* set all to auto */
margin: 10px 20px 10px 15px; /* top, right, bottom, left */
margin: 0 auto 20; /* top, left and right, bottom 20 */
margin: 0 auto; /* top and bottom, left and right */
margin-top: 20px; /* specify top, right, bottom or left */

Padding

The space between an elements content and border. Top, bottom, left and right values can be set in a variety of ways.

padding: auto; /* set all to autio */
padding: 10px 0; /* top and bottom, left and right */
padding-left: 20px; /* specify top, right, bottom or left */
padding: 0.5rem calc(1.25rem +2px) 0.5rem 0; /* top, right, bottom, left */

Accessibility (@media)

The @media query can be used to conditionally apply CSS. Commonly used with viewport width by setting max-width and min-width values. This provides the ability to adjust layout/format for small screens, mobile etc.

/* examples from exercises */
@media (max-width: 960px) {
    .card {
        padding: 2rem;
    }
}

@media (min-width: 500px) and (max-width: 1000px){
}

@media only screen and (max-width: 720px) {
    .image-wrapper {
        grid-template-columns: 1fr;
    }
}

Overflow

Can be used with hidden to stop scrollbars from appearing

overflow: hidden; 

Element properties

Variables

CSS supports variables. These should be defined in the :root selector. These are then available to all following selectors.

/* set variable */
root: {
--building-color1: #999; /* '--' variable name ':' value */
}

/* use variable */
building-color: var(--building-color1); /* var(variableName) */
background-color: var(--building-color2, green); /* fall-back value */

Font, text, list

Font

Font properties that can be set include family, size, weight etc.

Each browser has some common font families available to it. Fall back fonts can be added after the first separated by commas. Fonts with open space in the name must be surrounded with quotes (“Open Sans”).

Additional fonts are available by linking to external sources such as google. Google fonts guide.

Font tips:

font-family: "Open Sans", sans-serif; /* fall back font follows the first after a ',' */
font-size: 16px;
font-size: **min(5vw, 1.2em);**
font-weight: 800; /* increases 'boldness' of font */
font-weight: bold;
/* link to google to get Open Sans font */
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700,800" rel="stylesheet">
Text

Text properties that can be set include alignment, indentation, decoration (e.g. underline). CSS also has properties for letters and list styling.

text-align: center;
text-indent: -4px;
text-decoration: none; /* remove underline from anchor */
vertical-align: top;
Letters
letter-spacing: 0.15px;
List styles
list-style-type: none;
list-style: none;

Dimensions & shapes

Width/height

Width and height of elements can be set using in a fixed way using px. They can also be set relative to parent elements using %. Another options is to use vw (viewport width) and vh (viewport height)

Tip:

width: 80% /* sets to % of parent element */
**max-width: 500px; /* use e.g. 40rem for responsive */
min-width: 300px;
min-height: 2em;
width: 60vw; /* vh/vw: set height relative to viewport 1vw = 1% */
width: max(250px, 25vw); /* return largest of comma separated values */
width: unset; /* remove earlier specified rules */**
Aspect ratio
aspect-ratio: 35 / 4;
Gap

Sets gaps (gutters) between rows and columns. For flex, grid and multi-column layouts. Apply the property to the container element. Row-gap and column-gap sub properties

gap: 16px;
row-gap: 10px;
column-gap: 10px;
Object-fit

Maintains aspect ratio and crops images to fit in containers

object-fit: cover; // 
Shapes

Shapes can be created in CSS usually by using a combination of width, height, top, right, left, border, bottom and transform properties along with pseudo :before and :after selectors.

Examples:

Borders & backgrounds

Borders

Elements border properties include width, color, style. Black is used by default, however if setting borders it is best practice to set black explicitly. Tips:

border: 0; /* remove all borders */

border-left-width: 10px; /* specify border on one side */
border-left-style: solid; /* or dashed or dotted or double */

border-left-color: black;
border-color: #000000 #0000ff #00ff00 #ff0000 /* set colours individually */

border-bottom: 4px solid #fdb347; /* quick format width, style and colour */
Border radius

Border radius can be used to round corners of elements such as div

border-radius: 9px; /* set all corners based on px */
border-radius: 46%; /* set all corners based on % */
border-top-left-radius: 90px; /* set one corner only */
border-radius: 40% 50%; /* set top & bottom vs. left & right */
border-radius: 190% 150px 0 0; /* set 4 corners individually */
Box shadow

Add a shadow to an element. The height and width of the shadow is based on the height and width of the element it’s applied to, but optional spreadRadius can be used to adjust this.

Syntax: box-shadow: offsetX offsetY blurRadius spreadRadius color; where:

box-shadow: 0 0 3px 3px #efb762;
Background-image

Specify an image by url to use as the background of an element

/* from url */*
background-image: url(https//weburl.jpg);

Color

Basics

Color can be defined in several ways. This includes keywords: red, rgb values: rgb(0,255, 0), hsl values: hsl(240, 100%, 50% and hex values: f7f7f7

color: f7f7f7; /* change font color */
background-color: burlywood; /* change background color by keyword */
background-color: rgb(0,255,0); /* change background color by RGB */
background-color: #00FF00; /* change background color by hex */
background-color: hsl(240,100%,50%) /* change background color by hsl */
Linear gradient

These are used to create a transition of specified colors along a line. This method creates an image element and usually paired with a background element which can take an image as a value. It requires a minumum of two colours, but can accept many. Syntax: linear-gradient(gradientDirection, color1 colourstop%, color2 colourstop%, color3, colourstop%) where:

background: linear-gradient(90deg, 
rgb(255,0,0) 10%, 
rbg(0,255,0) 30%, 
rgb(0,0,255 90%)
);

/* example from cityskylines */
background: linear-gradient(
orange,
var(--building-color1) 80%,
var(--window-color1)
);

/* to make gradient change a solid line repeat % for 2 colors */
background: linear-gradient(
var(--building-color2) 0%,
var(--building-color2) 6%,
var(--window-color2) 6%,
var(--window-color2) 9%,
)
Repeating linear gradient

A repeating linear gradient causes the specified gradient to repeat until reaching the end of the element. This can be used to create a stripe effect.

/* examples from cityskylines */
background: repeating-linear-gradient(
var(--building-color2),
var(--building-color2) 6%,
var(--window-color2) 6%,
var(--window-color2) 9%
);

background:
repeating-linear-gradient(
90deg,
var(--building-color4),
var(--building-color4) 10%,
transparent 10%,
transparent 15%
);
Radial gradient

These are defined at their centre and require at least two color stops. Syntax: background-image: radial-gradient(shape size at position, start-color, …, last-color);

/* sun example from cityskylines */
background: radial-gradient(
circle closest-corner at 15% 15%,
#ffcf33 0%,
#ffcf33 20%,
#ffff66 21%,
#bbeeff 100%
);
Opacity:

A value for opacity can be added to color properties. The value of 100% or 1.0 represents opaque as in a solid wall. At 0% it represents completely transparant. With the rgb() color property opacity can be added by using rgba() and specifying a value between 0 and 1.

background-color: rgba(255,255,255,0.5); /* white with 50% opacity

Other topics (filter, transform, content)

Filter

Filter was used to create a blur effect during one of the exercises.

filter: blur(2px);
Transform

Transform can be used to modify a shape, it’s position and size etc. by changing layout or affecting surrounding elements. The transform-origin can be specified which sets the point around which a CSS transformation is applied. This takes two values representing the top and left offset.

/* selection of transform examples */
transform-origin: 0% 0%; /* point to transform around. top & left offsets.*/
transform: rotate(-0.6deg);
transform: rotate(130deg)scaleX(-1); /* rotate and retain scale */
transform: translate();
transform: scale();
transform: matrix;
transform: uppercase;
transform: skew(0deg, 44deg); /* two values - where to shear on x & y axis */
Content

Content can be used to set or override the content of an element. Tip: in one of the exercises content: ""; was used to make empty ::before and ::after pseudo-selectors render to the page.

content: "";

Tables

One property used in one of the exercises was border-collapse to allow cell borders in a table to collapse into a single border.

border-collapse: collapse;

Functions (minmax, calc, repeat)

Throughout the exercises a few functions were utilised to set CSS values. These included minmax(), calc() and repeat().

/* minmax can be used with px, %, fr or keyword such as max-content */
grid-template-columns: minmax(2rem, 1fr) minmax(94rem, min-content), minmax(2rem,1fr); 

/* calculate can be used to perform simple calculations when setting values */
padding: 0.5rem calc(1.25rem + 2px) 0.5rem0; /* calculate values */

/* repeat can be used to easily create multiple columns */
grid-template-columns: repeat(2, 1fr); 

User interface

Cursor

Cursor can be used to control how the mouse pointer displays. During the exercises this is commonly set to a pointer when hovering over buttons

.btn:hover {
cursor: pointer;
}

scroll behaviour

This sets the behavior for a scrolling box when scrolling is triggered by the navigation. This can be set to auto (for instant scrolling) or smooth

scroll-behavior: smooth;

Animation

Basic settings with @keyframes

The @keyframes at-rule is used to define the flow of a CSS animation. Within the @keyframes rule, you can create selectors for specific points in the animation sequence, such as 0% or 25%, or you can use from and to to define the start and end of the sequence.

/* keyframes example showing a change of position */*
@keyframes wheel {
    0% {
        top: 0;
        left: 0;
    }
    30% {
        top: 50px;
    }
}

The animation settings are then set using full stop followed by the keyframe name:

/* example from wheel exercise */

.wheel {
animation-name: wheel;    /* link keyframe animation to CSS object */
animation-duration: 10s;    /* Time in seconds (s) or milliseconds (ms) */
animation-iteration-count: infinite;
animation-timing-function: linear; /* `ease-in-out` start/end at a slower pace */  
}

.wheel {
animation: cabins 10s linear infinite; /* quick-format */
}

Motion based animations @media rule

Certain types of motion-based animations can cause discomfort for some users. In particular, people with vestibular disorders have sensitivity to certain motion triggers. The @media at-rule has a media feature called prefers-reduced-motion to set CSS based on the user’s preferences. It can take one of the following values:

@media (feature: value) {
    selector {
        styles
    }
}

Accessibility

General notes

Screen readers

.sr-only {
position: absolute; /* take out of document flow */
width: 1px;
height: 1px;
padding: 0; /* take out of document flow */
margin: -1px; /* take out of document flow */
overflow: hidden; /* prevent overflow */
clip: rect(0, 0, 0, 0); /* define visible portions of an element */
clip-path: inset(50%); /* determine shape clip property should take */
white-space: nowrap; /* prevent overflow */
border: 0;
}

Navigation accessibility can be improved by providing keyboard shortcuts. The accesskey attribute accepts a space-separated list of access keys

<button type="submit" accesskey="s">Submit</button>

HTML and CSS to reverse heading order

For visual display vs. screen reader (from the exercises)

<h1>
<span class="flex">
<span>AcmeWidgetCorp</span>
<span>Balance Sheet</span>
</span>
</h1>
h1 .flex {
display: flex;
flex-direction: column-reverse;
gap: 1rem;
}

Useful formats

Draw a cat eye (drawing shapes)

<div class="cat-left-eye">
<div class="cat-left-inner-eye"></div>
</div>
.cat-left-eye {
position: absolute;
top: 54px;
left: 39px;
border-radius: 60%;
transform: rotate(25deg);
width: 30px;
height: 40px;
background-color: #000;
}
.cat-left-inner-eye {
position: absolute;
top: 8px;
left: 2px;
width: 10px;
height: 20px;
transform: rotate(10deg);
background-color: #fff;
border-radius: 60%;
}

Quotation format

.quote {
color: #00beef;
font-size: 2.4rem;
text-align: center;
font-family: "Raleway", sans-serif;
}
.quote:before {
content: '" ';
}
.quote:after {
content: ' "';
}

Design theory

Colours

Key notes taken from the crayon exercise that went into details on colour theory for html and css:

A useful article on color contrast