0% found this document useful (0 votes)
537 views

1808 HTML and CSS Visual QuickStart Guide 9th Edition

Uploaded by

rouf8029
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
537 views

1808 HTML and CSS Visual QuickStart Guide 9th Edition

Uploaded by

rouf8029
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 571

Contents

1. Cov er Pa ge
2. T it l e Pa ge
3. Copy r igh t Pa ge
4. Dedica t ion
5. A ckn owl edgm en t s
6. Con t en t s a t a Gl a n ce
7. T a bl e of Con t en t s
8. In t r odu ct ion
1. Wh a t You Wil l Lea r n
2. Wh o Is T h is Book For ?
3. How T h is Book Is St r u ct u r ed
4. On l in e Con t en t
5. Er r a t a
9. 1. Wh a t A r e HT ML a n d CSS?
1. Wh a t Is HT ML?
2. Wh a t Is CSS?
3. How HT ML a n d CSS Wor k T oget h er
4. Wr a ppin g Up
10. 2. Cr ea t in g a Websit e on You r Com pu t er
1. Usin g a T ext Edit or
2. Usin g A dv a n ced T ool s
3. Websit e Dir ect or y St r u ct u r es a n d Fil e
Ext en sion s
4. Usin g CodePen for Qu ick T est s
5. Wr a ppin g Up
11. 3. HT ML Sy n t a x
1. How HT ML T a gs Wor k
2. A ddin g Com m en t s
3. St r u ct u r in g a n HT ML Pa ge
4. T h e <m et a > T a g
5. Wh a t Is Sem a n t ic Ma r ku p?
6. Wr a ppin g Up
12. 4. Ba sic HT ML El em en t s
1. HT ML T ext For m a t t in g
2. Pa r a gr a ph s a n d Hea din gs
3. List s
4. Qu ot in g a Bl ock of T ext
5. For m a t t in g T ext In l in e
6. Ma r kin g Up Code
7. Wr a ppin g Up
13. 5. Lin ks
1. Lin k Ma r ku p
2. URL St r u ct u r e
3. In t er n a l v s. Ext er n a l Lin kin g
4. Rel a t iv e v s. A bsol u t e Lin kin g
5. Ot h er T y pes of Lin ks
6. Lin k T a r get s
7. Wr a ppin g Up
14. 6. St r u ct u r e a n d La y ou t wit h HT ML
1. Webpa ge La y ou t
2. Bl ock v s. In l in e El em en t s
3. Pa ge Sect ion s
4. Bu il din g a Bl og A r t icl e La y ou t
5. Wr a ppin g Up
15. 7. Media
1. How Does Media Wor k on t h e Web?
2. Im a ges
3. A ddin g Im a ges t o a Pa ge
4. Respon siv e Im a ges: Con sider in g Differ en t
Dev ices a n d Con n ect ion s
5. T h e <pict u r e> El em en t
6. Usin g SV G
7. Ot h er Media
8. Em beddin g V ideo
9. Em beddin g A u dio
10. St or in g Mu l t im edia Fil es
11. Wr a ppin g Up
16. 8. T a bl es a n d Ot h er St r u ct u r ed Da t a El em en t s
1. T a bl es
2. Descr ipt ion List s
3. Wh y Is St r u ct u r ed Da t a Im por t a n t ?
4. Wr a ppin g Up
17. 9. Web For m s
1. In t er a ct in g wit h Webpa ges
2. How a Web For m Wor ks
3. Com pon en t s of a n HT ML For m
4. T h e <for m > El em en t
5. For m Fiel ds
6. La bel in g Fiel ds
7. Set t in g Up a Ba sic For m
8. Cr ea t in g Sel ect Boxes
9. Cr ea t in g Ra dio Bu t t on s
10. Cr ea t in g Ch eckboxes
11. Cr ea t in g Em a il For m s
12. Specia l Fiel d T y pes
13. T h e <m et er > El em en t
14. V a l ida t in g For m s
15. Wr a ppin g Up
18. 10. A dv a n ced a n d Exper im en t a l Fea t u r es
1. It ’s A l l A bou t Br owser Su ppor t
2. A dv a n ced El em en t s
3. Exper im en t a l Fea t u r es
4. Wr a ppin g Up
19. 11. In t r odu ct ion t o CSS
1. Wh a t A r e St y l es?
2. Wh a t Does Ca sca din g Mea n ?
3. CSS Sy n t a x
4. Usin g CSS on You r Webpa ge
5. Ext er n a l St y l e Sh eet s
6. Com m en t in g You r CSS Code
7. Wr a ppin g Up
20. 12. T a r get in g El em en t s
1. T a r get in g El em en t s by T a g
2. T a r get in g El em en t s by Cl a ss
3. T h e Ca sca de, In h er it a n ce, a n d Pa r en t -Ch il d
Rel a t ion sh ips
4. Sel ect in g El em en t s by t h eir Rel a t ion sh ips
5. Specificit y a n d Pr eceden ce in t h e Ca sca de
6. T a r get in g El em en t s wit h Specific A t t r ibu t es
7. A dv a n ced T a r get in g
8. Wr a ppin g Up
21. 13. St y l in g T ext
1. Ch oosin g Fon t s
2. Googl e Fon t s
3. In cl u din g Ext er n a l Fon t s wit h @fon t -fa ce
4. Sizin g T ext
5. For m a t t in g T ext
6. For m a t t in g for Rea da bil it y
7. Wr a ppin g Up
22. 14. Col or in CSS
1. How Com pu t er Mon it or s Wor k
2. Repr esen t in g Col or in CSS
3. Gr a dien t s
4. T h e bor der Pr oper t y
5. Wr a ppin g Up
23. 15. Usin g CSS for Pa ge La y ou t
1. T h e Box Model
2. Pa ddin g a n d Ma r gin s
3. El em en t Fl ow
4. Cr ea t in g La y er s a n d Ov er l a ppin g El em en t s
5. Cr ea t in g a n Ov er l a y Usin g z-in dex
6. A Not e A bou t Cr ea t in g La y ou t s
7. Wr a ppin g Up
24. 16. La y ou t s wit h CSS Gr id a n d Fl exbox
1. Moder n Sol u t ion s for a n Im por t a n t Pr obl em
2. Usin g Fl exbox
3. Usin g CSS Gr id La y ou t
4. Br owser Su ppor t
5. Wr a ppin g Up
25. 17. Respon siv e Design a n d Media Qu er ies
1. Defin in g Media Qu er ies
2. Respon siv e La y ou t s
3. Ma kin g a Fu l l -widt h La y ou t Respon siv e
4. Not Ju st for Scr een Widt h s
5. Wr a ppin g Up
26. 18. CSS T r a n sfor m a t ion s a n d A n im a t ion s
1. CSS T r a n sit ion s
2. CSS T r a n sfor m a t ion s
3. CSS A n im a t ion s
4. Wr a ppin g Up
27. 19. CSS V a r ia bl es
1. Wh a t A r e V a r ia bl es?
2. Sim pl ify in g St y l es wit h V a r ia bl es
3. Ca l cu l a t ion s wit h V a r ia bl es
4. Wr a ppin g Up
28. 20. CSS Pr epr ocessor s
1. How CSS Pr epr ocessor s Wor k
2. Get t in g St a r t ed wit h Sa ss
3. Wr it in g Sa ss
4. Wr a ppin g Up
29. 21. Get t in g You r Websit e On l in e
1. Ch oosin g Host in g a n d a Dom a in
2. Pr e-La u n ch Ch eck
3. Ma kin g You r Sit e Liv e
4. T est in g You r Sit e
5. Wr a ppin g Up
30. 22. T est in g You r Websit e
1. Wh y T est You r Websit e?
2. V a l ida t in g Ma r ku p
3. Br owser T est in g
4. Dev ice T est in g
5. T r ou bl esh oot in g wit h Ch r om e Dev el oper T ool s
6. Wr a ppin g Up
31. 23. Im pr ov in g Websit e Per for m a n ce
1. Wh a t Do We Mea n by Per for m a n ce?
2. Kn ow How You r Websit e Per for m s
3. Per for m a n ce T est in g T ool s
4. Min ify HT ML a n d CSS Fil es
5. Opt im ize You r Im a ges
6. Loa d You r Cr it ica l CSS Fir st
7. Wr a ppin g Up
32. 24. Web A ccessibil it y
1. In cl u din g a s Ma n y Peopl e a s Possibl e
2. Wh a t You ’v e Don e so Fa r
3. A ddit ion a l T a gs a n d A t t r ibu t es
4. A ccessibil it y T est s a n d V a l ida t ion
5. Fin din g You r WCA G Ra t in g
6. Wr a ppin g Up
33. 25. Goin g Bey on d HT ML & CSS
1. Ja v a Scr ipt
2. Com m on Ja v a Scr ipt Libr a r ies
3. V er sion Con t r ol
4. Bu il d T ool s
5. Wr a ppin g Up
34. Fin a l Wr a p-u p
1. Wh a t ’s Next ?
35. In dex
1. i
2. ii
3. iii
4. iv
5. v
6. v i
7. v ii
8. v iii
9. ix
10. x
11. xi
12. xii
13. xiii
14. xiv
15. xv
16. xv i
17. xv ii
18. xv iii
19. 1
20. 2
21. 3
22. 4
23. 5
24. 6
25. 7
26. 8
27. 9
28. 10
29. 11
30. 12
31. 13
32. 14
33. 15
34. 16
35. 17
36. 18
37. 19
38. 20
39. 21
40. 22
41. 23
42. 24
43. 25
44. 26
45. 27
46. 28
47. 29
48. 30
49. 31
50. 32
51. 33
52. 34
53. 35
54. 36
55. 37
56. 38
57. 39
58. 40
59. 41
60. 42
61. 43
62. 44
63. 45
64. 46
65. 47
66. 48
67. 49
68. 50
69. 51
70. 52
71. 53
72. 54
73. 55
74. 56
75. 57
76. 58
77. 59
78. 60
79. 61
80. 62
81. 63
82. 64
83. 65
84. 66
85. 67
86. 68
87. 69
88. 70
89. 71
90. 72
91. 73
92. 74
93. 75
94. 76
95. 77
96. 78
97. 79
98. 80
99. 81
100. 82
101. 83
102. 84
103. 85
104. 86
105. 87
106. 88
107. 89
108. 90
109. 91
110. 92
111. 93
112. 94
113. 95
114. 96
115. 97
116. 98
117. 99
118. 100
119. 101
120. 102
121. 103
122. 104
123. 105
124. 106
125. 107
126. 108
127. 109
128. 110
129. 111
130. 112
131. 113
132. 114
133. 115
134. 116
135. 117
136. 118
137. 119
138. 120
139. 121
140. 122
141. 123
142. 124
143. 125
144. 126
145. 127
146. 128
147. 129
148. 130
149. 131
150. 132
151. 133
152. 134
153. 135
154. 136
155. 137
156. 138
157. 139
158. 140
159. 141
160. 142
161. 143
162. 144
163. 145
164. 146
165. 147
166. 148
167. 149
168. 150
169. 151
170. 152
171. 153
172. 154
173. 155
174. 156
175. 157
176. 158
177. 159
178. 160
179. 161
180. 162
181. 163
182. 164
183. 165
184. 166
185. 167
186. 168
187. 169
188. 170
189. 171
190. 172
191. 173
192. 174
193. 175
194. 176
195. 177
196. 178
197. 179
198. 180
199. 181
200. 182
201. 183
202. 184
203. 185
204. 186
205. 187
206. 188
207. 189
208. 190
209. 191
210. 192
211. 193
212. 194
213. 195
214. 196
215. 197
216. 198
217. 199
218. 200
219. 201
220. 202
221. 203
222. 204
223. 205
224. 206
225. 207
226. 208
227. 209
228. 210
229. 211
230. 212
231. 213
232. 214
233. 215
234. 216
235. 217
236. 218
237. 219
238. 220
239. 221
240. 222
241. 223
242. 224
243. 225
244. 226
245. 227
246. 228
247. 229
248. 230
249. 231
250. 232
251. 233
252. 234
253. 235
254. 236
255. 237
256. 238
257. 239
258. 240
259. 241
260. 242
261. 243
262. 244
263. 245
264. 246
265. 247
266. 248
267. 249
268. 250
269. 251
270. 252
271. 253
272. 254
273. 255
274. 256
275. 257
276. 258
277. 259
278. 260
279. 261
280. 262
281. 263
282. 264
283. 265
284. 266
285. 267
286. 268
287. 269
288. 270
289. 271
290. 272
291. 273
292. 274
293. 275
294. 276
295. 277
296. 278
297. 279
298. 280
299. 281
300. 282
301. 283
302. 284
303. 285
304. 286
305. 287
306. 288
307. 289
308. 290
309. 291
310. 292
311. 293
312. 294
313. 295
314. 296
315. 297
316. 298
317. 299
318. 300
319. 301
320. 302
321. 303
322. 304
323. 305
324. 306
325. 307
326. 308
327. 309
328. 310
329. 311
330. 312
331. 313
332. 314
333. 315
334. 316
335. 317
336. 318
337. 319
338. 320
339. 321
340. 322
341. 323
342. 324
343. 325
344. 326
345. 327
346. 328
347. 329
348. 330
349. 331
350. 332
351. 333
352. 334
HTML and CSS

Visual Quickstart
Guide

9th Edition

Joe Casabona
Visual QuickStart Guide
HTML and CSS, 9th Edition
Joe Casabona

Peachpit Press
www.peachpit.com

Copyright © 2021 by Pearson Education, Inc. or its


affiliates. All Rights Reserved.

San Francisco, CA

Peachpit Press is an imprint of Pearson Education, Inc.

To report errors, please send a note to


[email protected]

Notice of Rights

This publication is protected by copyright, and


permission should be obtained from the publisher prior
to any prohibited reproduction, storage in a retrieval
system, or transmission in any form or by any means,
electronic, mechanical, photocopying, recording, or
otherwise. For information regarding permissions,
request forms and the appropriate contacts within the
Pearson Education Global Rights & Permissions
department, please visit www.pearson.com/permissions.

Notice of Liability

The information in this book is distributed on an “As Is”


basis, without warranty. While every precaution has
been taken in the preparation of the book, neither the
author nor Peachpit shall have any liability to any
person or entity with respect to any loss or damage
caused or alleged to be caused directly or indirectly by
the instructions contained in this book or by the
computer software and hardware products described in
it.

Trademarks
Visual QuickStart Guide is a registered trademark of
Peachpit Press, a division of Pearson Education.

Unless otherwise indicated herein, any third party


trademarks that may appear in this work are the
property of their respective owners and any references to
third party trademarks, logos or other trade dress are for
demonstrative or descriptive purposes only. Such
references are not intended to imply any sponsorship,
endorsement, authorization, or promotion of Pearson
Education, Inc. products by the owners of such marks,
or any relationship between the owner and Pearson
Education, Inc., or its affiliates, authors, licensees or
distributors.

Executive Editor: Laura Norman


Development Editor: Victor Gavenda
Senior Production Editor: Tracey Croom
Copy Editor: Scout Festa
Proofreader: Becky Winter
Compositor: Danielle Foster
Indexer: Valerie Haynes-Perry
Cover Design: RHDG / Riezebos Holzbaur Design
Group, Peachpit Press
Interior Design: Peachpit Press with Danielle Foster
Logo Design: MINE™ www.minesf.com

ISBN-13: 978-0-13-670256-6
ISBN-10: 0-13-670256-2

ScoutAutomatedPrintCode
Dedication
To my wife, Erin. Y our love and support has allowed me
not only to write this book, but to have the life I’ve
always wanted.

To my daughter, Teresa. Y ou make me smile and laugh


every day. And to my son, Louis. Welcome to the world,
buddy.

I love you all.


Acknowledgments
Writing a book, especially a good one, takes time and a
group of solid people. And this one wouldn’t have
happened without the great team I got to be a part of. I
want to extend a special thank you to:

La u r a Nor m a n , w h o h elped m e g et ba ck in th e book


w r itin g g a m e w ith th is title, for h er su ppor t a n d
g u ida n ce a lon g th e w a y .

V ictor Ga v en da , for h is dev elopm en t editin g a n d deep


kn ow ledg e of th e V QS for m a t, a n d for m a kin g it seem
like I h a v e g ood con tr ol ov er th e En g lish la n g u a g e.

Fa r a z Kelh in i, th e tech editor . His feedba ck a n d


su g g estion s m a de for a m u ch better r ea d.

Scou t Festa , for ex cellen t copy editin g .

Tr a cey Cr oom a n d th e en tir e Pea r son desig n tea m , for


m a kin g th is book look fa n ta stic.

Sh a w n Hesketh , a fr ien d a n d m en tor w h o ta u g h t m e a ll


th e g ood th in g s I kn ow a bou t scr een ca sts.

Br ia n Rich a r ds, for h elpin g m e w or k th ou g h som e of th e


m or e a dv a n ced topics in th is book.

My fr ien ds a n d fa m ily , for th e su ppor t a n d


en cou r a g em en t th r ou g h ou t th e w r itin g pr ocess.

Ev er y on e w h o h a s con tr ibu ted by lettin g m e u se a


scr een sh ot, im a g e, or r esou r ce th a t th ey cr ea ted.

To TT a t m y loca l Sta r bu cks. He a lw a y s sa w m e com in g


a n d h a d m y or der r ea dy .

To y ou , th e r ea der s. Th a n k y ou for a llow in g m e to


con tr ibu te to y ou r lea r n in g jou r n ey .

Fin a lly , to Eliza beth Ca str o for cr ea tin g th is title, a n d to


Br u ce Hy slop for pa ssin g m e th e tor ch .
Contents at a Glance
Introduction

Chapter 1 What Are HTML and CSS?

Chapter 2 Creating a Website on Y our Computer

Chapter 3 HTML Syntax

Chapter 4 Basic HTML Elements

Chapter 5 Links

Chapter 6 Structure and Layout with HTML

Chapter 7 Media

Chapter 8 Tables and Other Structured Data Elements

Chapter 9 Web Forms

Chapter 10 Advanced and Experimental Features

Chapter 11 Introduction to CSS

Chapter 12 Targeting Elements

Chapter 13 Styling Text

Chapter 14 Color in CSS

Chapter 15 Using CSS for Page Layout

Chapter 16 Layouts with CSS Grid and Flexbox

Chapter 17 Responsive Design and Media Queries

Chapter 18 CSS Transformations and Animations

Chapter 19 CSS Variables

Chapter 20 CSS Preprocessors

Chapter 21 Getting Y our Website Online

Chapter 22 Testing Y our Website


Chapter 23 Improving Website Performance

Chapter 24 Web Accessibility

Chapter 25 Going Beyond HTML & CSS

Final Wrap-up

Index
Table of Contents
Introduction

Chapter 1 What Are HTML and CSS?


What Is HTML?
What Is CSS?
How HTML and CSS Work Together
Wrapping Up

Chapter 2 Creating a Website on Your Computer


Using a Text Editor
Using Advanced Tools
Website Directory Structures and File
Extensions
Using CodePen for Quick Tests
Wrapping Up

Chapter 3 HTML Syntax


How HTML Tags Work
Adding Comments
Structuring an HTML Page
The <meta> Tag
What Is Semantic Markup?
Wrapping Up

Chapter 4 Basic HTML Elements


HTML Text Formatting
Paragraphs and Headings
Lists
Quoting a Block of Text
Formatting Text Inline
Marking Up Code
Wrapping Up
Chapter 5 Links
Link Markup
URL Structure
Internal vs. External Linking
Relative vs. Absolute Linking
Other Types of Links
Link Targets
Wrapping Up

Chapter 6 Structure and Layout with HTML


Webpage Layout
Block vs. Inline Elements
Page Sections
Building a Blog Article Layout
Wrapping Up

Chapter 7 Media
How Does Media Work on the Web?
Images
Adding Images to a Page
Responsive Images: Considering Different
Devices and Connections
The <picture> Element
Using SVG
Other Media
Embedding Video
Embedding Audio
Storing Multimedia Files
Wrapping Up

Chapter 8 Tables and Other Structured Data


Elements
Tables
Description Lists
Why Is Structured Data Important?
Wrapping Up
Chapter 9 Web Forms
Interacting with Webpages
How a Web Form Works
Components of an HTML Form
The <form> Element
Form Fields
Labeling Fields
Setting Up a Basic Form
Creating Select Boxes
Creating Radio Buttons
Creating Checkboxes
Creating Email Forms
Special Field Types
The <meter> Element
Validating Forms
Wrapping Up

Chapter 10 Advanced and Experimental Features


It’s All About Browser Support
Advanced Elements
Experimental Features
Wrapping Up

Chapter 11 Introduction to CSS


What Are Styles?
What Does Cascading Mean?
CSS Syntax
Using CSS on Y our Webpage
External Style Sheets
Commenting Y our CSS Code
Wrapping Up

Chapter 12 Targeting Elements


Targeting Elements by Tag
Targeting Elements by Class
The Cascade, Inheritance, and Parent-Child
Relationships
Selecting Elements by their Relationships
Specificity and Precedence in the Cascade
Targeting Elements with Specific Attributes
Advanced Targeting
Wrapping Up

Chapter 13 Styling Text


Choosing Fonts
Google Fonts
Including External Fonts with @font-face
Sizing Text
Formatting Text
Formatting for Readability
Wrapping Up

Chapter 14 Color in CSS


How Computer Monitors Work
Representing Color in CSS
Gradients
The border Property
Wrapping Up

Chapter 15 Using CSS for Page Layout


The Box Model
Padding and Margins
Element Flow
Creating Layers and Overlapping Elements
Creating an Overlay Using z-index
A Note About Creating Layouts
Wrapping Up

Chapter 16 Layouts with CSS Grid and Flexbox


Modern Solutions for an Important Problem
Using Flexbox
Using CSS Grid Layout
Browser Support
Wrapping Up

Chapter 17 Responsive Design and Media Queries


Defining Media Queries
Responsive Layouts
Making a Full-width Layout Responsive
Not Just for Screen Widths
Wrapping Up

Chapter 18 CSS Transformations and Animations


CSS Transitions
CSS Transformations
CSS Animations
Wrapping Up

Chapter 19 CSS Variables


What Are Variables?
Simplifying Styles with Variables
Calculations with Variables
Wrapping Up

Chapter 20 CSS Preprocessors


How CSS Preprocessors Work
Getting Started with Sass
Writing Sass
Wrapping Up

Chapter 21 Getting Your Website Online


Choosing Hosting and a Domain
Pre-Launch Check
Making Y our Site Live
Testing Y our Site
Wrapping Up

Chapter 22 Testing Your Website


Why Test Y our Website?
Validating Markup
Browser Testing
Device Testing
Troubleshooting with Chrome Developer Tools
Wrapping Up

Chapter 23 Improving Website Performance


What Do We Mean by Performance?
Know How Y our Website Performs
Performance Testing Tools
Minify HTML and CSS Files
Optimize Y our Images
Load Y our Critical CSS First
Wrapping Up

Chapter 24 Web Accessibility


Including as Many People as Possible
What Y ou’ve Done so Far
Additional Tags and Attributes
Accessibility Tests and Validation
Finding Y our WCAG Rating
Wrapping Up

Chapter 25 Going Beyond HTML & CSS


JavaScript
Common JavaScript Libraries
Version Control
Build Tools
Wrapping Up

Final Wrap-up
What’s Next?

Index
Introduction
In This Introduction

What Y ou Will Learn


Who Is This Book For?

How This Book Is Structured


Online Content

Errata

When I started making websites, back in 2000, it was a


much simpler time. I was able to build a full website
with just HTML and CSS and a few images. There were
also fewer browsers and devices. But as the web evolved
and computers got smarter and more powerful, the
needs of both web users and web developers changed.
This made some things easier. It also made learning
more complicated.
Today, a website that doesn’t use any JavaScript is a rare
sight (and site!). There are so many build tools, libraries,
and development philosophies that learning how to
make a website can seem overwhelming.

But there’s good news: at the heart of it all are still just
plain and simple HTML and CSS.

WHAT YOU WILL LEARN


The building blocks of the web are plain HTML and CSS
—and you can make a website knowing just those two
technologies. That’s what you learn in this book.
Specifically, you’ll get the ins and outs of what it takes to
write good, meaningful, and well-structured HTML.
Y ou’ll learn how to write proper, maintainable CSS to
make your HTML look nice. And you’ll learn how to get
it all online.
Websites are meant to be universal files that can be
accessed and displayed everywhere by everyone.
Accessibility— in multiple senses of the word—is the
name of the game, and learning to design and build
websites that can be reached by all users, regardless of
their personal abilities, using any device they choose.
To make a webpage, you need only what you already
have on your computer: a text editor, a place to save
files, and a browser. This book teaches you how to put all
those pieces together.

Current technologies
On top of learning how to write HTML and CSS (and get
it online), you’ll get a crash course in what it’s like to
build a professional website today. Y ou’ll learn about
important aspects of web design, such as performance
(making sure your website loads quickly and doesn’t
burden the user). Y ou’ll learn about how to make your
website accessible so that anyone can use it, including
those who are color blind or rely on a screen reader.
This book also explores modern tools like CSS
preprocessors, JavaScript libraries, and version control.
It’s good to know these things as you move forward
because they will probably be the next step on your
learning journey. This brings us to the next question:
who is this book for?

WHO IS THIS BOOK FOR?


In short, this book is written for anyone who wants to
learn HTML and CSS. It assumes no prior knowledge.

That means that if you want to make a website for your


hobby, this book is for you. If you’re taking a beginner
course (or teaching a beginner course), it’s for you too.
Or if you want to become a professional web developer,
hey, it’s for you too. After all, books like this are how I
got my start. Y ou’ll get all the tools you need to get a
website online. And then I’ll give you some options for
what you can learn next.
However, if you’re looking for advanced techniques, like
using HTML Canvas, writing JavaScript from scratch, or
using advanced build tools like node.js, this book is not
for you. Though I will say that after reading through the
official HTML and CSS documentation thoroughly,
you’ll probably pick up some new things. I know I did.

HOW THIS BOOK IS STRUCTURED


This book is structured so that each chapter builds on the
last. That means you’ll first learn exactly what HTML
and CSS are and what the purpose of each is. Then you’ll
learn about how to organize your website’s files and
directories. Then, on to the crux of the matter!

Both the HTML and CSS sections of the book start with
the most basic markup or code and move to more
complex techniques. If you’re starting with no
knowledge, it’s best to take the chapters in order.
This book, like others in the Visual QuickStart Guide
series, uses a combination of explanatory text and step-
by-step tasks to teach you HTML and CSS. Each chapter
begins with text that introduces a topic, and a series of
short sections present specific features within that topic.

These sections typically begin with an explanation of the


feature, which is followed by one or more tasks that
walk you through implementing the feature. Code
samples and images accompany each task to show you
what to do.
If you’re brushing up or using this book as a reference,
each chapter also stands alone—so if you need a
refresher on forms or on the box model, you can just
check out those chapters. While the book is not
comprehensive, it covers all the important parts and it
points you in the right direction for the rest.
The book ends with some bigger concepts to consider
once you’re comfortable putting an entire website
together.
Although you’ll get all the building blocks to make a full
site, we won’t build a single site from scratch. There will,
however, be full-page examples for you to follow, as well
as starter files to work from.

Code
There are three ways code is presented in the book.
Code within regular narrative text (which you’ll usually
see in numbered steps) is set in a distinctive font. Here
are a couple of examples: </head> and .nav-main {.

Blocks of code appear as standalone paragraphs within


the flow of text, or as separate numbered Code samples
(CODE 00.1).
Both of the previous types can include small portions
that are highlighted in red to draw your attention to
them:
Click h er e to v iew code im a g e

<a href="#contact">Jump to Contact


→Form</a>

Y ou’ll encounter most of the code in the step-by-step


tasks. They’ll show you exactly what to type and then
show you the results. So please follow along—there’s
nothing like learning by doing!
In the actual code files, I include inline comments to
help you understand what’s going on. These comments
use special markup to prevent them from appearing on
the page when it’s rendered in a web browser.
CODE 00.1 A sample code block
Click h er e to v iew code im a g e

p.introduction {
color: red;
font-family: Monaco, monospace;
font-size: 16px;
}
HTML comments look like this:
Click h er e to v iew code im a g e

<!-- This is an HTML comment -->

CSS comments look like this:

/* This is a CSS comment */

Much of the code is available for download at


peachpit.com (see “Online Content,” below). Y ou can
also find it, along with links and other useful resources,
at casabona.org/vqs/.

Supplemental information
Throughout the book there are two other elements to
look out for: tips and sidebars.

Tip
Tips are formatted like this and include helpful notes, links, and other
information that’s good to know.

This Is a Sidebar
Sidebars, as the name implies, include more inf ormation than a tip but don’t really f it
in the main body of the text, which is designed to giv e y ou hands-on experience.
Sidebars support the step-by -step tasks and are designed to enhance and strengthen
the skills y ou’re learning.

VIDEOS

Sample Video Title


This book is heav ily supplemented with v ideos, which y ou can access v ia the online
Web Edition (see “Online Content”). The v ideos reinf orce bigger points, expand on
skills taught in step-by -step tasks, and highlight topics that are more easily
demonstrated in v ideo than in static images.

ONLINE CONTENT
Y our purchase of this Visual QuickStart Guide includes
online materials provided by way of your Account page
on peachpit.com.

Code samples
Some of the code examples shown in the book are
provided for your personal use and study. They’re
organized in folders by chapter.

Web Edition
The Web Edition is an online interactive version of the
book, providing an enhanced learning experience. Y our
Web Edition can be accessed from any device with a
connection to the internet, and it contains the following:

Th e com plete tex t of th e book

Hou r s of in str u ction a l v ideo key ed to th e tex t

Accessing the code samples and Web Edition


Note: If you encounter problems registering your
product or accessing the code samples or Web Edition,
go to www.peachpit.com/support for assistance.
You must register your purchase on peachpit.com in
order to access the online content:
1. Go to w w w .pea ch pit.com /h tm lv qs.
2. Sig n in or cr ea te a n ew a ccou n t.
3. Click Su bm it.
4. A n sw er th e qu estion a s pr oof of pu r ch a se.
5. Th e code sa m pl es ca n be a ccessed fr om th e Reg ister ed
Pr odu cts ta b on y ou r A ccou n t pa g e. Click th e A ccess Bon u s
Con ten t lin k below th e title of y ou r pr odu ct to pr oceed to th e
dow n loa d pa g e. Click th e lesson file lin ks to dow n loa d th em to
y ou r com pu ter . A s a cou r tesy , th e code sa m ples a r e a lso
a v a ila ble—a lon g w ith oth er u sefu l lea r n in g r esou r ces—fr om
ca sa bon a .or g /v qs/.
Th e Web Edit ion ca n be a ccessed fr om th e Dig ita l Pu r ch a ses
ta b on y ou r A ccou n t pa g e. Click th e La u n ch lin k to a ccess
th e pr odu ct.

Note that if you purchased a digital product directly


from peachpit.com, your product will already be
registered. However, you still need to follow the
registration steps and answer the proof of purchase
question before the Access Bonus Content link will
appear under the product on your Registered Products
tab.

ERRATA
Finally, try as I might to get rid of them all, there still
may be some errors in the final, printed text. Y ou can
find a list of those on the book’s page at
www.peachpit.com/title/9780136702566. Click the
Updates tab to report an error or to see any corrections
that are available.
I hope you enjoy the book and get a lot out of it, whether
you’re learning or using it as a reference.
1

What Are HTML and CSS?


In This Chapter

What Is HTML?
What Is CSS?

How HTML and CSS Work Together


Wrapping Up

The web has come a long way since it launched, in 1991.


We’ve seen some big evolutions: from plain, static pages
to slightly nicer-looking websites, to fully interactive
web-based applications that we can access from
anywhere in the world—including the device in our
pocket.

And while the web has evolved considerably over that


time, at its very core are still two important technologies:
HTML and CSS. But what are they, and why should you
know them?

WHAT IS HTML?
HTML stands for HyperText Markup Language and it
does two important things: it describes how webpages
should look, and it defines the semantics of those pages.
But what is a markup language? Well, websites are
made up of a bunch of different components. A variety
of kinds of data—text, images, audio, video, and
downloadable media—are part of a website. Those files—
every component of the website—are stored on a server
for you and other people to access.
Think of it this way: imagine that accessing a website
from a server is like ordering takeout. Y ou order from
your favorite restaurant (sending a request across the
internet), the kitchen staff (the server) selects the items
you need, and then the delivery person (the internet
again) brings the food (the files for the website) to your
door (your computer).
All of this data is presented to you in your browser
(Chrome, Firefox, Safari, Microsoft Edge, etc.) in a
human-readable way.

Because humans and computers don’t read data the


same way, there needs to be something that tells
computers how to display all of this data in a structured
way—to render it—so humans can read it.
The raw data files that the server sends you come with
one or more files written in HTML. To continue our
takeout analogy, you can think of an HTML file like a
bento box (or, if you’re not into Japanese cuisine, like a
cafeteria tray). It acts as a container that keeps the
different types of data organized and presents them in a
useful arrangement.

That’s where markup comes in. An HTML file is simply


a text file marked up with special codes that tell the web
browser how to display the data it’s receiving from the
server on the computer’s screen. HTML markup draws
from a large collection of text tags that are embedded in
the text and tell the computer—specifically the browser—
how a website should look.
Semantics in this context is important because it gives
meaning to those tags (also known as elements). For
example, there’s an <h1> HTML element (for Heading
1) (FIGURE 1.1), which tells the browser and search
engines that the enclosed text is a heading—and not just
any heading, but the most important heading. The
browser then knows to display it in big bold letters … that
is, unless you use CSS, or Cascading Style Sheets (which
you’ll learn about later), to tell the browser to display it
differently.

Figure 1.1 A heading tag in HTML

While you could just put a bunch of plain text into a file
and open it in a browser, that text will have no structure
or meaning. It will all run together, and there will be no
visual hierarchy. It will just be a blob of text.
Let’s start by looking at the simple Word document in
FIGURE 1.2. Y ou can see there are multiple headings
at different sizes, paragraphs with spacing, and text
that’s formatted as bold or italic type.
Figure 1.2 A Microsoft Word document

This visual hierarchy gives the reader an idea of how


they should approach the text: when a new section
starts, where emphasis in the text lies, and more. In
Word you do this using the Styles pane. On a webpage,
you do that by adding HTML tags to the HTML file.

To create a simple hierarchy with HTML:


1. Open Notepa d on Win dow s, or Tex tEdit on Ma c.
2. Ty pe <h1>Bigger headings are more important</h1>.
3. Ty pe <h2>This is smaller</h2>.
4. Ty pe <h3>This is smaller still</h3>.
5. <p>This is body copy, and is most common.</p>.
6. Sa v e th e file a s h ier a r ch y .h t m l .
7. Dou ble-click th e file to open it in y ou r br ow ser .
You r br ow ser sh ou ld displa y fou r pa r a g r a ph s of tex t,
decr ea sin g in size fr om top to bottom (FIGURE 1.3).
Figure 1.3 A simple hierarchy in HTML

VIDEO 1.1

Creating a Visual Hierarchy with HTML


See how y ou can create an outline, or v isual hierarchy, using only HTML markup.

Current version: HTML5


At the time of this writing, the current version of HTML
is HTML5. This version introduced lots of new elements
and simplified a lot of the markup.
Because it’s likely that you’re just entering the wonderful
world of HTML, using HTML5 mostly means you have a
ton of great features at your disposal, and that those
features are well supported. But it is good to know that
HTML5 is backwards compatible, and much of it works
with old and new browsers.

Luckily, browsers are pretty forgiving of HTML versions


and even of errors in your markup, so you won’t have to
worry about completely breaking anything with your
code!

WHAT IS CSS?
If HTML provides the structure for a webpage, then CSS
supplies the style—and it’s right in the name! CSS stands
for Cascading Style Sheets, and it describes how a
webpage should look: it prescribes colors, fonts, spacing,
and much more. In short, you can make your website
look however you want.
While HTML uses tags, CSS uses rulesets. They look like
this:

h1 {
color: black;
font-size: 30px;
}

A great example of how CSS works is the website CSS


Zen Garden. Y ou can visit the site at csszengarden.com
and, by changing the CSS, completely change the look
and feel of the pages without changing the underlying
HTML markup. Much like when you apply different
themes or layouts to documents in Microsoft Word,
changing the CSS styles on a webpage makes the page
look different, but the hierarchy of the content stays the
same (FIGURE 1.4).

Figure 1.4 CSS Zen Garden

VIDEO 1.2

Changing Styles on CSS Zen Garden


Let’s take a look at CSS Zen Garden in action! You’ll see how to change a bunch of
sty les to see how the appearance of the site changes. And then y ou’ll take a quick
peek at the markup to see that it’s not changing.

VIDEO 1.3

Applying Simple Styles to Markup


Start with y our HTML markup f rom earlier and add some sty les to it.
While browsers come with their own default styles, you
can easily override them with your own styles, in the
form of CSS files called style sheets.

Current version: CSS3


CSS is currently on version 3 (CSS3) and is constantly
evolving as browsers and computers get more powerful.

With CSS3 you get animations, more visual effects, and


much, much better support for layout features like
columns and grids, among other features.
For feature support, CSS3 is more dependent on the
user’s browser than is HTML. With HTML, browsers
treat unknown tags as plain text, so they still render
properly. But older browsers likely will not support
newer features in CSS3—and that will affect how your
pages look and function. Y ou’ll learn more about that
later in the book.

HOW HTML AND CSS WORK


TOGETHER
Even though HTML and CSS perform different functions
for a website, they are almost always coupled in learning
materials such as this book.
That’s because they are the two core languages
necessary for making modern websites. Although
technically only HTML is required to make a webpage,
without CSS you’ll get a bland website that doesn’t look
like much more than a Word document (FIGURE 1.5).
Figure 1.5 HTML, no CSS

VIDEO 1.4

Styles vs. No Styles


First, I’ll show y ou a plain website with no CSS, and then I’ll apply a sty le sheet to
show y ou how dramatically it can change.

These days, with the power of HTML5 and CSS3, we can


create with our websites unique experiences that would
have required a true programming language like
JavaScript just a few years ago (FIGURE 1.6).

Figure 1.6 The HTML page from Figure 1.5, this time
with CSS

Exciting times
Because of the synergy between HTML5 and CSS3, we
live in a pretty exciting time for website creation. Things
we once had to hack together are now natively
supported (like columns of text), and HTML is getting
more semantic and accessible.
That means more people with different abilities can use
websites, search engines are getting more useful
information, and websites should load faster, because
you don’t need to add workarounds or extra processing
to make certain aspects of your website work.

Much of that has to do with advancements in web


browser development.

WRAPPING UP
Another reason HTML and CSS are so often discussed
together is that they’re both processed by the user’s
browser. Other web technologies, programs, and apps
work differently. Some might be processed by a server,
or some on a developer’s computer and exported. HTML
and CSS are uniquely positioned because the source code
is accessible to the user in the browser.
When something new gets added to HTML or CSS, it’s
up to each individual browser to implement the changes.
That means that Google Chrome, Firefox, Safari, and
Microsoft Edge may implement the new features at
different times.

As a result, the websites you create might look different


in each browser.
We’ll talk more about testing your websites in a later
chapter, but knowing this will help you understand the
true power of HTML and CSS: any device that has a
browser can view your website.

It also means that you don’t need any additional tools,


equipment, or expenses to start making websites. Y ou
can do it right from your computer.
Let’s do that now.
VIDEO 1.5

Browser Comparison
See how one website can look dif f erent when v iewed in Chrome, Saf ari, and Microsof t
Edge.
2

Creating a Website on Your


Computer
In This Chapter

Using a Text Editor


Using Advanced Tools

Website Directory Structures and File Extensions


Using CodePen for Quick Tests

Wrapping Up

The beauty of HTML and CSS being interpreted by the


browser is that you can basically create HTML and CSS
on anything that has a browser. Although this book
focuses on working on a Mac or a Windows computer,
you can definitely get it done on a Chromebook, an iPad,
or, in a pinch, even your phone.
It also means that (assuming you have a device with a
browser on it) you can do it at no initial cost. In Chapter
21 you’ll learn about the two components you need to
get your website online: a server (also known as a
hosting service) and an address for that server (known
as a domain). Y ou don’t need either of them to start
working with HTML and CSS, nor do you need to pay
for any other software. Everything used in this chapter is
free!

There are three components to creating a website on


your computer:

A tex t editor

A folder str u ctu r e


A w eb br ow ser

USING A TEXT EDITOR


A text editor is a program that lets you write plain text
(that is, text without any formatting) on your computer.
In Windows, Notepad serves that purpose, and macOS
ships with TextEdit (FIGURE 2.1). Be careful: TextEdit
lets you add simple formatting to plain text, so you’ll
need to make sure to save the file in plain text format
and add the .html extension to the file name. Don’t save
the file in the default rich text format (.rtf).

Figure 2.1 TextEdit for macOS

To create a new webpage:


1. Open Notepa d on Win dow s, or Tex tEdit on m a cOS.
In th e follow in g steps, en ter ea ch ta g on a sepa r a te lin e of
code.
2. Ty pe <html>.
3. Ty pe <head>.
4. Ty pe </head>.
5. Ty pe <body>.
6. Ty pe </body>.
7. Ty pe </html>.
8. Sa v e th e file a s in dex.h t m l .
VIDEO 2.1

Creating a New Webpage


Use a simple text editor to create a basic HTML webpage and sav e the f ile.

VIDEO 2.2

Installing VS Code
Download, install, and customize Visual Studio Code.

USING ADVANCED TOOLS


There are also a multitude of advanced tools specifically
for writing code and markup. They include features like:

Sy n t a x h igh l igh t in g to m a ke y ou r code ea sier to r ea d

A u t ocom pl et ion to a llow y ou to w r ite code fa ster

Rea l -t im e com pil in g

Er r or ch eckin g

V er sion con t r ol

Some are souped-up text editors, like Notepad++ (for


Windows) and Atom and Visual Studio Code (VS Code),
which are both cross-platform.
Some are integrated development environments (IDEs)
that have whole suites of tools built in. Coda for Mac is a
popular one, but there’s also the cross-platform
PHPStorm. These are generally used for programming in
languages like PHP or Python.

I recommend VS Code (FIGURE 2.2). It’s free, well


made, and stable, and the user interface is completely
customizable. The ability to customize the interface of
VS Code will make reading HTML and CSS easier, and it
allows you to highlight the markup for an HTML tag or
CSS statement, which we’ll cover in later chapters.
Figure 2.2 HTML markup in VS Code showing
syntax highlighting in action

WEBSITE DIRECTORY STRUCTURES


AND FILE EXTENSIONS
With a code editor in place, it’s time to talk about the
actual files you’ll need for your website, and the folder,
or directory, structure you’ll use to store them.

Since you’re developing right on your computer, you


could technically just throw all the files onto the desktop
and work from there. But I strongly recommend against
that. Instead, you should create a proper directory
structure.
Y our initial examples and projects will use only one or
two files. But as your websites get more complex, you’ll
need more files (and more types of files). Having a good
file structure will keep your site organized. It will help
you, and anyone else who might maintain your code,
find things easily.

Naming conventions
Before you set up the directory on your computer, let’s
talk about naming conventions. When it comes to
naming files, you’ll use one file extension for HTML files
(.html) and one for CSS files (.css).

All file names should be lowercase and should use


hyphens (-) in place of spaces. So “My Cool File” would
have the file name my-cool-file.html.

The same convention goes for directories: their names


should be all lowercase, and if you’re going to use
multiple words, use hyphens to separate them.

Tip

A file extension tells the computer how to handle the file. Usually this means
telling the computer which program should open the file, or what kind of
information the file contains.

VIDEO 2.3

Setting Up a Directory Structure


Your website will end up using a lot of f iles on y our computer, and the way y ou
organize those f iles into directories is important.

To set up a directory structure:


1. If y ou ’r e on Win dow s, g o to a n d open th e My Docu m en ts
folder . On m a cOS, open th e Docu m en ts folder in y ou r h om e,
or u ser , folder .
2. Rig h t-click in th e folder w in dow a n d ch oose New Folder . Th is
is th e topm ost folder in y ou r dir ector y str u ctu r e, w h ich is
a lso ca lled th e root folder of th e w ebsite.
3. Na m e th a t folder websit e.
You ca n n a m e th e folder a n y th in g y ou ’d like.
4. Dou ble-click th e n ew folder to open it.
5. Cr ea te a n ew folder ca lled im a ges.
6. Fin d th e in dex .h tm l file y ou cr ea ted in th e pr ev iou s ta sk.
Mov e it in to th e w ebsite folder .

Tip
This book uses Google Chrome throughout to test web pages that we create,
but you can use Safari, Edge, Firefox, or the latest version of any modern
browser you’d like!

Accessing your files


When you want to open an HTML file, you can double-
click its icon on your computer to open it in the browser.
Taking files online so that other people can open them is
a bit of a different story, and I’ll talk more about that in
Chapter 21. But there is one important piece of
information you should know.

To access a file online, you need to know its path—that


is, its location in the file system hierarchy. File paths use
the format /directory/file-name. Many times,
when we use a browser to visit a website, we don’t
specify the name of the file we wish to access. The
browser could be visiting a domain (peachpit.com) or a
specific subfolder in that domain (peachpit.com/store/).
A domain serves as the “address” for a website. Y ou can
think of it the same way you’d think of a mailing address
for house.
Continuing the home address analogy, to get to a specific
file on the web you have to know the route to follow to
reach it. This is provided by the file’s Uniform Resource
Locator (URL). The URL of a file incorporates the name
of its domain and the file’s path (FIGURE 2.3).
Figure 2.3 The URL of a webpage reflects its location
in the website’s directory structure.

What if you don’t know the exact URL of the page you
want to visit, but you know the domain name of its
website? In these cases, most web servers will choose a
default file to show you. This default file is most often
named index.html and sits at the root of the directory
we’re accessing. So the main page for your website (its
home page) will have the file name index.html.

Mimicking a web server


Another reason to forge good organizational habits early
in this process is that web servers—where your files will
eventually live—are organized in a specific way, with
your site’s files living in some publicly available folder,
usually named public_html, public, html, or even
root.

If you’d like to get a good idea of how web servers work


(although it isn’t necessary to understand this now), you
could download a program that creates a small server on
your computer. For Windows, that will be the software
bundle WAMP (Windows, Apache, MySQL, PHP). For
macOS, that will be MAMP (Mac, Apache, MySQL,
PHP). Don’t worry. In both cases, all four components
come in a single installer.
This is definitely overkill for what we need right now, but
let’s file it under “good to know.”

VIDEO 2.4

How Default Files Work


To see how def ault f iles work, y ou’ll f irst v isit a website where y ou specif y the f ile
name, and then y ou’ll v isit two dif f erent URLs where the f ile name is not specif ied.

VIDEO 2.5

Setting Up MAMP
Install MAMP on a Mac, and then look at how the f ile structure lines up with the URL
structure.

VIDEO 2.6

CodePen Demo
Use CodePen to create a quick HTML and CSS example.

USING CODEPEN FOR QUICK TESTS


There’s one more option for quickly testing code without
the need for a web server, but you will need an internet
connection.

The popular website CodePen provides an interface that


lets you write and test code in a single window. Y ou can
see how this works in FIGURE 2.4.
Figure 2.4 The CodePen code editing interface

Y ou enter your HTML and CSS into one of the panels at


the top of the page, while the bottom of the page displays
the results in real time. So if you want to rapidly see the
effects of what you’re writing without opening and
refreshing your browser, CodePen is a great option. It’s
especially good for rapid prototyping.

WRAPPING UP
Now that you have your text editor, your local website
directory, and a fast way to test code, you’re ready to
start writing HTML.

In the next chapter we’re going to dive into how HTML


works. Let’s do it!
3

HTML Syntax
In This Chapter

How HTML Tags Work


Adding Comments

Structuring an HTML Page


The <meta> Tag

What Is Semantic Markup?


Wrapping Up

As mentioned in Chapter 1, HTML is the language that


defines every webpage. But what exactly does that
mean, and what are the terms we should use when
talking about HTML?

HTML is a set of text tags. These tags are inserted into


the content of the HTML files that create your webpages,
and they define the type of content being displayed in the
browser.
In this chapter you will learn all about HTML, from the
terms you need to know, to how to write tags, to the
general makeup of an HTML document.

HOW HTML TAGS WORK


Take a look at one of the most common HTML tags
(FIGURE 3.1). The <p> is a standard HTML tag. It
starts with a less-than sign (<), followed by the letter p
(the name of the tag), and ends with a greater-than sign
(>). Taken together, these constitute an HTML tag.
Figure 3.1 An HTML element

Note that HTML tags usually work in pairs that frame


the content to which they apply. The only difference
between the first and second p tags is the addition of the
forward slash (/) after the left angle bracket that
encloses the second p tag. This denotes the closing tag,
and treated as a unit, the whole statement creates an
HTML element: opening tag, content, and closing tag.
The p in between the angle brackets is the character—
this tells the browser what the content is. In this case,
“p” stands for “paragraph” and causes the browser to
display the content between the tags as a block of text.
One might read this aloud as, “An opening paragraph
tag, followed by text, then a closing paragraph tag.”
Depending on the tag, the browser will display the text
differently.

Tip
You’ll often see the less-than and greater-than symbols that enclose a tag
referred to as left and right angle brackets, respectively, even though they’re
not technically equivalent. Another convenient way to refer to the symbols
collectively is to call them inequality symbols.
VIDEO 3.1

Changing a Tag
I’ll demonstrate how changing a tag changes the way the browser display s text.

VIDEO 3.2

Excluding Necessary Attributes


See what happens if y ou exclude a necessary attribute f rom an HTML tag, such as
<img> or <a>.

To change an HTML tag and see the result in the


browser:
1. In y ou r tex t editor , ty pe <p>This is text</p> (FIGURE
3.2).

Figu r e 3.2 Usin g HTML ta g s to defin e tex t a s a pa r a g r a ph

2. Sa v e th e file a s t a g.h t m l .
3. Dou ble-click th e file to open it in y ou r br ow ser (FIGURE 3.3).

Figu r e 3.3 How th e ta g g ed tex t looks in a br ow ser

4. Ba ck in th e editor , r epla ce <p> w ith <h1>.


5. Repla ce </p> w ith </h1> (FIGURE 3.4).
Figu r e 3.4 Th e sa m e bit of tex t bu t w ith <h1> ta g s
r epla cin g th e <p> ta g s

6. Sa v e th e file.
7. In th e br ow ser , r efr esh th e pa g e to see h ow th e tex t ch a n g es
size a n d sty le (FIGURE 3.5).

Figu r e 3.5 Ou r fa m ilia r tex t, n ow r en der ed a s a top-lev el


h ea din g

Attributes
There’s one more key piece of text you might find in
HTML tags: attributes. Attributes provide additional
information about the element they’re being applied to.
Let’s look at our paragraph tag again, this time with an
attribute:
Click h er e to v iew code im a g e

<p lang="en">This is a paragraph.</p>

The attribute should go after the character in the


opening tag. There are two parts to an attribute: the
name (lang) and the value (en). This attribute tells the
browser, “This paragraph is in English.”
Two other notes about attributes:

Elem en ts ca n h a v e a n y n u m ber of a ttr ibu tes.


Som e elem en ts, like im a g es (<img>) or h y per lin ks (<a>),
r equ ir e specific a ttr ibu tes to w or k pr oper ly .

ADDING COMMENTS
Finally, it’s considered a best practice to annotate your
HTML code with information about the code itself by
adding comments. Y ou can do this to label sections of
the code or to explain the purpose of individual pieces of
code. These comments are helpful when you revisit the
code later to update it, or especially when someone else
works on the code.

Comments don’t appear on the page when it’s rendered


in a browser. This is useful during development, because
you can “comment out” a piece of code to try out the
effect of turning it off temporarily without actually
deleting it from the file.

To add comments to HTML:


1. In y ou r HTML file, fin d th e spot w h er e y ou w a n t th e
com m en t to sta r t a n d ty pe <!--.
2. Do on e of th e follow in g :
If y ou ’r e a ddin g a com m en t, ty pe th e tex t of th e com m en t
follow ed by -->.
If y ou ’r e com m en tin g ou t ex istin g code, pla ce th e in ser tion
poin t a t th e en d of th e code a n d ty pe -->.

See CODE 3.1 for an example of commented code.


FIGURE 3.6 shows the rendered page.

Figure 3.6 When Code 3.1 is rendered in a user’s


browser, the commented code is invisible to the user.

Tip
Even though commented code doesn’t appear when a browser renders the
page, the comments are not completely hidden! Any user can view the page’s
source code (you’ll learn how to do that in Chapter 22) and see the full text of
any comments, so be careful not to store anything embarrassing or offensive
in comment text.
CODE 3.1 This code contains two comments that mark the beginning and end of a
section of the page, and one paragraph element that’s been commented out.
Click h er e to v iew code im a g e

<!doctype html>
<html class="no-js" lang="">
<head>
<link href="style.css"
rel="stylesheet" type="text/css" />
<title>Joe Casabona - Done for You
Podcasts and Courses</title>
</head>
<body>
<main>
<h1>Hi! I’m Joe Casabona.</h1>
<!-- Start of Site Description -->
<div>
<p>I create online courses at
<a
href="https://creatorcourses.com/">Creator
Courses</a>
and for
<a
href="https://www.linkedin.com/learning/instructors/joe-
casabona">LinkedIn
→Learning</a>
, host a podcast called
<em><a href="https://howibuilt.it/">How I
Built It</a>, </em>
and have been making websites for 20
years.</p>
</div>
<!--
<p>This content won't display because it's
been commented out.</p>
-->
<!-- End of Site Description -->
</main>
</body>

STRUCTURING AN HTML PAGE


Now that you have a basic understanding of how HTML
tags work, you need an understanding of the structure of
an entire page. The essential components of a standard
HTML page can be distilled into a boilerplate file. Y ou
can use this boilerplate file as a template for new HTML
documents (FIGURE 3.7).
Figure 3.7 HTML boilerplate file markup

These components should exist on every HTML page:

A DOCTYPE decla r a tion (to tell th e br ow ser w h a t v er sion


of HTML w e’r e u sin g ) a s th e v er y fir st lin e.

A n open in g <html> ta g . A ll oth er ta g s on th e pa g e w ill


be pla ced betw een th e open in g a n d closin g html ta g s.

Open in g a n d closin g <head> ta g s.

Open in g a n d closin g <body> ta g s.

A closin g </html> ta g en ds th e docu m en t. Noth in g


sh ou ld com e a fter th a t.

Tip
Older versions of HTML required that “DOCTYPE” be set in all uppercase
letters, but in HTML5 the term is case-insensitive.

<html>, <head>, and <body> tags

Aside from the DOCTY PE, three different tags define the
overall structure of a webpage:

Th e <html> ta g s m a r k th e open in g a n d closin g of th e


en tir e docu m en t. Ev er y oth er ta g (a side fr om DOCTYPE)
w ill g o betw een th ese ta g s.

Th e <head> elem en t is w h er e in for m a tion about th e


pa g e g oes. In m ost ca ses, n on e of th is in for m a tion w ill be
displa y ed in th e br ow ser w in dow .
Th e <body> elem en t is w h er e a ll th e pa g e con ten t g oes. If
th er e’s tex t betw een th e <body> a n d </body> ta g s, it
w ill likely be displa y ed to th e u ser .

There are some exceptions to these rules about the


<head> and <body> and what gets displayed. A good
example for the <head> is the <title> element. The
<title></title> tags go in the <head> and define
the text that gets displayed in the tab of your browser
(FIGURE 3.8).

Figure 3.8 The <title> element as displayed in the


browser

THE < M E T A > TAG


The <meta> tag, much like the <title> tag, belongs in
the <head> of the document. However, unlike
<title>, this displays no information to the user.

Instead, the <meta> tag is used to send information


about the web page to search engines. Its most common
attributes are name and content, which are used for
name-value pairs. One example of this is to provide the
description of a document:
Click h er e to v iew code im a g e

<meta name="description" content="A basic HTML


boilerplate file.">

A list of common values for the name attribute are:

author: Defin es th e n a m e of th e a u th or of th e docu m en t


description: Pr ov ides th e descr iption of th e docu m en t
th a t sh ou ld sh ow u p in sea r ch en g in e r esu lts

color-scheme: Deter m in es w h eth er a pa g e su ppor ts


da r k m ode on dev ices th a t a llow it.

viewport: Giv es in for m a tion a bou t th e in itia l size of th e


docu m en t. Th is is u sed on m obile dev ices on ly .

robots: Deter m in es w h eth er th e docu m en t sh ou ld be


in clu ded in sea r ch en g in e r esu lts.

Tip
The <meta> tag does not use a closing tag or slash.

Tip
The name/content combination for the <meta> tag is the most common. But
there are other attributes for more advanced definitions and functionality. You
can find them here: developer.mozilla.org/en-
US/docs/Web/HTML/Element/meta

To create an HTML boilerplate file:


1. Cr ea te a n ew file in y ou r tex t editor .
2. Ty pe <!DOCTYPE html>.
Th is is th e DOCTYPE decla r a tion . In HTML5 , ju st “ h tm l” is
u sed. In older v er sion s, th e defin ition is a bit m or e v er bose.
3. Ty pe <html> to sta r t th e docu m en t.
4. Ty pe <head>.
5. Ty pe <title>HTML Boilerplate</title>.
6. Ty pe <meta name="author" content="your name">.
Be su r e to r epla ce your name w ith y ou r ow n n a m e.
7. Ty pe </head>.
8. Ty pe <body>.
9. Ty pe </body>.
10. Ty pe </html> to close th e docu m en t.
11. Sa v e th e file a s boil er pl a t e.h t m l in y ou r w ebsite folder .

VIDEO 3.3

Creating an HTML Boilerplate File


I’ll walk y ou through creating an HTML boilerplate f ile.
WHAT IS SEMANTIC MARKUP?
As you’ve learned, the tags tell the browser the kind of
content being presented. But why is that important?
By using the appropriate tags, we’re describing our
content—to the user, to the browser, and to search
engines and other computer-based processors. This
allows each to interpret the information the way they see
fit. This could mean displaying it in a certain color, or
highlighting it in specific search results.

For example, Google displays site navigation directly in


search results, as long as the appropriate semantic tags
are used (FIGURE 3.9).
Figure 3.9 Site navigation links can be displayed in
search results.

In short, semantic markup means our webpage is more


accessible to everyone. It can be more easily translated
for international visitors, and assistive technology (like
screen readers) can understand its content better.

WRAPPING UP
HTML tags are the building blocks of the web. They
create structure and assign meaning to our text. This
helps everything and everyone who visits your webpage
understand it better.
Now that you have a basic understanding of how HTML
works and why we should use it, let’s use it for our most
common task: formatting content.

VIDEO 3.4

Screen Reader in Action


Let’s see how assistiv e technology takes adv antage of semantic markup.
4

Basic HTML Elements


In This Chapter

HTML Text Formatting


Paragraphs and Headings

Lists
Quoting a Block of Text

Formatting Text Inline


Marking Up Code

Wrapping Up

There’s a wide range of HTML elements, and technically


all formatting of those elements happens in CSS. But
certain HTML elements come with semantic meaning
for how text should be presented on the screen.
In this chapter, we look at the most basic elements, and
how they can come together to create a well-formatted,
readable, and meaningful page.

HTML TEXT FORMATTING


If you’ve created text in Word or Google Docs, you’ll
know that formatting can be done with the press of a
few buttons. Select the text and choose a style from the
menu, and formatting is applied. White space is added
between paragraphs and headings, bullets are added to
unordered lists, you can change the color of text, and
more.
It’s not quite like that in HTML. If you just write text in
an HTML document, there will be no formatting. All the
text will run together, new lines will be ignored, and
certain characters will not display properly.
While browsers do use a default style sheet to format all
HTML elements, we still need to use HTML to describe
every piece of content on the page. Without the HTML,
the browser won’t know what kind of text is on the page.

So let’s start with the most common elements: headings


and paragraphs.

PARAGRAPHS AND HEADINGS


Y ou were introduced to paragraphs in the last chapter.
They are blocks of text that generally contain one idea,
in one or more sentences.

To create paragraphs:
1. Open th e boiler pla te.h tm l file a n d sa v e it a s
ch a pt er 4.h t m l .
2. On a n ew lin e a fter th e open in g <body> ta g , ty pe <p>.
3. Ty pe This is a paragraph!.
4. Ty pe </p>.
5. On a n ew lin e, ty pe <p>This is another paragraph.</p>.
6. On a n ew lin e, ty pe <p>This is a third paragraph.</p>.
7. Sa v e th e file, th en open it in y ou r br ow ser .
You ’ll en d u p w ith w h a t y ou see in FIGURE 4.1.

Figure 4.1 Three blocks of text, formatted as


paragraphs in HTML

VIDEO 4.1

HTML with No Elements


To see how much of an impact elements hav e on a webpage, let’s look at an HTML
page that has no markup.
VIDEO 4.2

Creating Paragraphs
As an exercise, create a f ew paragraphs on a page and then see what they look like in
the browser.

VIDEO 4.3

How to Order Headings


Because of the strong semantic meaning associated with headings, they need to be
ordered properly.

Headings are slightly different. HTML allows for six


levels of headings, with Heading 1 (<h1>) being the
most important and Heading 6 (<h6>) the least
important (FIGURE 4.2).
Figure 4.2 All the headings available in HTML, from
<h1> to <h6>

The principal role of headings is to create a visual


hierarchy on a page. Paragraphs should be organized
into sections, with headings at the top of those sections.
Headings also add meaning to the text—meaning that’s
important to search engines.
Semantically, there should only be one Heading 1 on a
page. As we move down the page, we should make sure
to keep our headings in the right hierarchical order.
The smaller the heading number, the bigger the idea it
should represent. So <h2> tags should represent only the
big ideas on a page.

LISTS
After paragraphs and headings, the next most common
element you’ll find in text is a list. If you look back at a
Word or Google Doc you’ve done recently, you’ll likely
find bulleted lists show up at least a few times.
There are two different types of lists you can create in
HTML: ordered and unordered.

Ordered lists (by default) are prefixed by numbers.


Unordered lists have bullets ( ) prefixed.

Depending on the type of list you want to create, use an


<ol> tag (for an ordered list) or a <ul> tag (for an
unordered list). Between the opening and closing tags,
each item on the list will be enclosed in <li> tags (for
list item).

To create an unordered list:


1. In y ou r HTML file, ty pe <ul> to beg in th e list.
2. Ty pe <li>Apples</li> to cr ea te th e fir st of th r ee item s on
th e list.
3. Ty pe <li>Bananas</li>.
4. Ty pe <li>Cherries</li>.
5. Ty pe </ul> to en d th e list.
A n d in FIGURE 4.3, y ou see h ow it looks.

Figure 4.3 The unordered list you created, as


rendered in the browser
Tip
You’ll learn how to change the default symbol for bullets when we talk about
CSS, but you can use anything to represent the bullets, even your own
images. Visually, though, ordered lists should always be represented with
numbers.

Tip

Notice that list items are indented. When embedding HTML elements within
other elements, it’s common to indent them to make the markup more
readable.

VIDEO 4.4

Creating Ordered and Unordered Lists


Learn how to create both ty pes of lists, and nest one list within another.

QUOTING A BLOCK OF TEXT


Traditionally, in printed material, quotations of
substantial amounts of text are set apart from the
surrounding content by indentations or changing the
type style. HTML includes the block-level element
<blockquote> (which conveniently contains “block” in
its name) to accomplish the same thing in the browser.
By default, <blockquote> elements are indented
compared to other block elements, but you can use CSS
to change the indentation.
To provide a source for the quotation, include the cite
attribute with the URL of the source as its value. Y ou
can also use the <cite> element to give the title of the
source in text (CODE 4.1, FIGURE 4.4). It’s normally
styled in italics by the browser, but you can change that
with CSS. If you wish to provide a link to the source as
well, combine the <cite> element with an <a>
element.
CODE 4.1 An example of a <blockquote> with the cite attribute together
with an example of the <cite> element
Click h er e to v iew code im a g e
<p><cite>The Importance of Being Earnest
→</cite> is only one of many sources of
→witty sayings by Oscar Wilde. To take
→one example:</p>

<blockquote cite="https://en.wikiquote.org
→/wiki/Oscar_Wilde">
<p>I never travel without my diary. One
→should always have something sensational
→to read in the train.</p>
</blockquote>

Figure 4.4 Code 4.1 as rendered in a browser

To quote a paragraph with citation:


1. Ty pe <blockquote>.
2. Ty pe <p>.
3. Ty pe th e qu ote.
4. Ty pe </p>.
5. Ty pe <cite>.
6. Ty pe th e sou r ce of th e qu ote.
7. Ty pe </cite>.
8. Ty pe </blockquote>.

FORMATTING TEXT INLINE


The last of the basic elements we’ll cover are inline
elements—that is, elements that are used inside other
elements.

Paragraphs, headings, and lists are “block-level”


elements. They are self-contained sections that start on a
new line and take up the entire width of the container.
But inline elements do not start on a new line and are
only as wide as the content. An example is the
<strong> tag.
In the following task you'll create a short paragraph (a
block element) and change the formatting of some of the
text in the middle of it (an inline element).

To bold text with the <strong> tag:

1. Ty pe <p>We use the strong tag to.


2. Ty pe <strong>draw attention</strong>.
3. Ty pe to text by bolding it.</p>.
You ca n see th e r esu lt in FIGURE 4.5.

Figure 4.5 The paragraph produced by the code in


this example

Notice that the <strong> tag is inside the <p> tag but
still inline with the text. And by default, the browser
bolds <strong> text. However, there’s another benefit
to using the <strong> tag. It tells browsers and search
engines that this text is slightly more important than the
normally formatted text.

Tip
To draw attention to text without making it semantically more important, you
can use the <b> tag instead. In HTML5 this is the Bring Attention To element;
previously it was known as the Boldface element. It should be noted that you
shouldn’t rely on either one (<strong> or <b>) to bold text. That should be
done with CSS.

The catalog of tags for formatting inline text is extensive;


here are the most common ones (FIGURE 4.6):

<em> is u sed for em ph a sis. It sh ow s a s ita licized tex t. Use


th e <i> ta g if y ou w a n t to set th e tex t a pa r t w ith ou t
sem a n tica lly n otin g “ em ph a sis.”

<u> is u sed to u n der lin e tex t. It sh ow s a s tex t w ith a lin e


dr a w n u n der it.

<s> is u sed to cr oss som eth in g ou t beca u se it is n o lon g er


cor r ect. It sh ow s a s tex t w ith a lin e th r ou g h it. You m a y
a lso com e a cr oss <strike> in older code, bu t it’s n ow
been r epla ced by <s>.

<del> looks sim ila r to <s>, bu t len ds a slig h tly differ en t


m ea n in g to tex t. <del> m a r ks som eth in g th a t h a s been
deleted fr om th e or ig in a l docu m en t.

<ins>, w h ich is u su a lly u n der lin ed by defa u lt, n otes


som eth in g th a t h a s been in ser ted in to th e docu m en t.

<mark> is u sed to h ig h lig h t tex t. It a dds a y ellow


ba ckg r ou n d to tex t, a s if a h ig h lig h ter pen h a s been
dr a w n a cr oss it.

<small>, w h ich r en der s tex t sm a ller th a n th e defa u lt


size, is u sed for n otes, side com m en ts, a n d fin e pr in t.

<sup> is su per scr ipt, a n d m a kes tex t a ppea r sm a ller a n d


r a ised slig h tly a bov e th e ba selin e. Th is is often u sed for
ex pon en ts, or bibliog r a ph ic cita tion s.

<sub> is u sed to displa y su bscr ipt tex t. Like <sup>


r edu ces tex t size bu t is low er ed below th e ba selin e th a n
n or m a l tex t.

<time> r epr esen ts a specific tim e a n d is often com bin ed


w ith th e datetime a ttr ibu te to con v er t h u m a n r ea da ble
tim e in to a m a ch in e-r ea da ble for m a t.
You ’ll fin d a list of v a lid datetime v a lu es h er e:
dev eloper .m ozilla .or g /en -
US/docs/Web/HTML/Elem en t/tim e.

<abbr> r epr esen ts a n a bbr ev ia tion a n d is u su a lly


r en der ed w ith a dotted u n der lin e. You ca n in clu de th e
fu lly ex pa n ded v er sion of th e a bbr ev ia tion in th e title
a ttr ibu te, w h ich is u su a lly displa y ed in a tooltip on
m ou seov er .

<br> cr ea tes a lin e br ea k. It’s u sefu l for situ a tion s w h en


y ou w a n t to m a ke lin es a specific len g th , a s in poetr y or
in a m a ilin g a ddr ess.
Figure 4.6 All of the listed formatting markup and
their default styles in Chrome.

Tip
This is only a sampling of the tags available in HTML for formatting inline
text. You can find a more comprehensive list of tags at
developer.mozilla.org/en-US/docs/Web/HTML/Element#Inline_text_semantics
VIDEO 4.5

Converting a Fully Formatted Word Doc to HTML


You’v e learned enough f ormatting in HTML to start with a Word document and conv ert
it to HTML.

MARKING UP CODE
There are also two HTML tags specifically used for
marking up code:

<code> is displa y ed in a m on ospa ce fon t a n d is u sed to


r epr esen t a sh or t sn ippet of com pu ter code.

<pre> is a lso displa y ed in a m on ospa ce fon t a n d


r epr esen ts pr efor m a tted tex t. Th a t m ea n s a n y tex t,
in clu din g w h ite spa ces, a ppea r s ex a ctly a s it w a s ty ped.

Tip
When using < and > in the <code> element, you should use the HTML entities:
&lt; and &gt;, respectively. To learn about HTML entities visit
developer.mozilla.org/en-US/docs/Glossary/Entity.

If you need to display multiple lines of code, place the


<code> element inside a <pre> element. The only time
you should use <code> by itself is for an inline element
(CODE 4.2, FIGURE 4.7).
CODE 4.2 Examples of a <code> element inline in a paragraph, and another
where it contains several lines of code inside a <pre> element.
Click h er e to v iew code im a g e

<p>If you need to display multiple lines


of code, place the <code> &lt;code&gt;
</code>element
→inside a <code> &lt;pre&gt;</code>
element. </p>

<p>In completely unrelated news, here’s a


bit of the code for a table that you’ll
encounter
→again in Chapter 8:</p>

<pre><code>
&lt;table border="1"&gt;
&lt;thead&gt;
&lt;th colspan="4"&gt;Aaron
Judge&lt;/th&gt;
&lt;th&gt;RF&lt;/th&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr role="header"&gt;
&lt;td&gt;Year&lt;/td&gt;
</code></pre>

Figure 4.7 Code 4.2 as rendered in Chrome.

Working with Other Languages


If y ou’re working with languages that use a right-to-lef t (RTL) script like Arabic or
Hebrew, then there are two elements that will be helpf ul to y ou: <bdi> and <bdo>.
<bdi> is the Bidirectional Isolate element. Place text within it to isolate it f rom the
rest of the text around it to prev ent rendering issues. This is helpf ul if y our main text
uses a lef t-to-right (LTR) script but y ou want to include a quotation or a name written
in a right-to-lef t script.

If y ou want to ov erride the current directionality of the text (which is generally


def ined by the browser), y ou can use the Bidirectional Text Ov erride element (<bdo>)
element with the dir attribute. It accepts the v alues rtl or ltr.
Finally, if the entire direction of the page is RTL, y ou can apply the dir="rtl"
attribute to the <html> element.
There’s a thorough explanation at w3.org: www.w3.org/International/questions/qa-html-
dir.

WRAPPING UP
With that, you have the basics down. Y ou know how to
format text and create a nice visual hierarchy in the
browser. This will make your website much easier to
read. Now let’s talk about what makes the web … well,
the web: hyperlinks!
5

Links
In This Chapter

Link Markup
URL Structure

Internal vs. External Linking


Relative vs. Absolute Linking

Other Types of Links


Link Targets

Wrapping Up

The element that has made the web at least somewhat


interactive since the very beginning is the hyperlink.
Hyperlinks, or simply links, allow us to connect pages to
each other to form a website, and let us send visitors to
pages that are external to our website. They play an
important role in the organization and SEO (search
engine optimization) of websites. But how exactly do
they work? What can we link to?

LINK MARKUP
A link (or hyperlink) is a way to connect one webpage to
another. Links also allow users to jump to a different
section of a webpage, download documents, and more.
To distinguish them visually from other webpage
content, textual links are usually given a distinctive
appearance, using color (typically blue for a link that has
not yet been visited), special text formatting, or both.
Links are represented in HTML by the <a> (or anchor)
tag. The <a> tag is one of those HTML tags that can
include a number of attributes.
In this case, the link takes users to a page on a different
website, so we need to include the attribute href, for
hypertext reference. The value of the href attribute is
the URL (Uniform Resource Locator) of the destination
—the page you’re linking to. The enclosed content of the
<a> element is typically some label text—usually the
name of the page the link will take the user to. This label
is the only part of the link that the user sees.

Tip
The <a> tag does not absolutely require the href attribute, but it must be
present for the tag to work correctly as a hyperlink.

Let’s see how to set up the markup for a link to Google.

To create a hyperlink:
1. In y ou r HTML file, ty pe <a to sta r t th e a n ch or elem en t.
2. Ty pe href="https://google.com"> to defin e th e
destin a tion of th e lin k.
3. Ty pe V isit Googl e to pr ov ide a la bel for th e u ser to click.
4. Ty pe </a> to fin ish th e lin k (FIGURE 5.1).

Figu r e 5.1 Th e m a r ku p for th e lin k to g oog le.com

5. Sa v e th e file a n d v iew it in y ou r br ow ser (FIGURE 5.2).

Figu r e 5.2 Th is h y per lin k to g oog le.com sta n ds ou t by its


color a n d u n der lin e.
Tip
Link labels don’t have to be text. As you’ll learn in Chapter 7, you can use an
image as a clickable link too.

While the markup for a link may look straightforward,


there are several nuances to creating links. Key to
creating links is understanding how URLs are
structured.

VIDEO 5.1

The Components of Hyperlink Markup


Create a simple link to a dif f erent (external) website.

VIDEO 5.2

Walking Through a URL


Take a closer look at Figure 5.3, and learn more about each section in detail.

VIDEO 5.3

HTTP vs. HTTPS


Learn how the HTTP and HTTPS protocols are dif f erent.

URL STRUCTURE
At this point, it’s worth taking a closer look at URLs. In
FIGURE 5.3, you’ll see the components of a common
URL.
Figure 5.3 The components of the URL
https://www.wordpress.org

Tip
URLs are the most common type of a broader set of Uniform Resource
Identifiers (URIs). URIs tell the browser how to handle the resources that are
being linked to.

URLs are made up of these sections:

Th e protocol (eith er h ttp or h ttps).

Th e s ubdomain (option a l).

Th e name of th e w ebsite.

Th e top-level domain (or TLD). Th is is a lso kn ow n a s th e


extens ion.

To link to a specific file within a site, you need to provide


these items as well:

Th e pa th (folder h ier a r ch y ) con ta in in g th e file.


Th e file n a m e.

In order to reach a website at all, you need to provide at


least these three parts of the URL: the protocol, the
name, and the TLD. Paths, subdomains, and file names
need to be included only when you want to reach those
specific areas of the website.
Ultimately, where a link sends your users is based on
what kind of URL—or how much of the URL—you
include.
First, let’s look at how linking to pages within your
website compares with linking to pages outside your
website.

INTERNAL VS. EXTERNAL LINKING


This concept is pretty clear. Internal links are links to
pages within your own website (or on the same
domain). External links are links to someone else’s
webpage.

Tip

Even though subdomains appear to be part of your website, they are still
considered external. For example, sub.casabona.org is not the same site as
casabona.org.

As far as markup goes, internal and external links use


exactly the same structure, except (as you’ll learn later in
this chapter) external links are always absolute. That is,
they need to include the entire URL, including the
protocol. If one of those items is missing or incomplete,
the link will not work.
If you’re linking internally, there’s something else to
consider: you don’t always need to include the entire
URL, because it’s implied. This is the result of the
difference between absolute and relative links.
VIDEO 5.4

Errors in External Links


How important is it to include the protocol? This v ideo shows what happens when an
external link isn’t structured properly.

RELATIVE VS. ABSOLUTE LINKING


Back in Chapter 2, you learned about file structures and
how websites are organized (FIGURE 5.4). Y ou also
saw how URLs incorporate part of a file’s directory
structure. When we talk about relative versus absolute
linking, we’re talking about how much of the URL and
directory structure we want to include.

Figure 5.4 The directory structure we created in


Chapter 2

With an absolute link, you include the entire URL in the


anchor element markup. Always use an absolute link
when linking to an external site, but you'll usually use
relative links for files on your own site.
Tip
There are times when an absolute link is appropriate even for files within
your own site. This is generally the case with dynamically generated content
—that is, content generated automatically by a script.

Say you want to link to a specific file called cart.html on


the website mysite.com. Y ou’ll need to know the location
of the file in the site’s directory structure to link to it. If
cart.html is in a top-level folder (i.e., a folder in the root
directory) called /store/, then the absolute link for this
file is https://mysite.com/store/cart.html.

Relative links, on the other hand, don’t include the


complete URL of the location you’re linking to. The
structure of the link markup is based only on where the
linked file is relative to the current file. So relative links
are commonly used to link within pages on a single
website, whose files share one common directory.
There are several different types of relative links we can
create, as shown in TABLE 5.1.

Sa m e fol der : Th e lin ked file is in th e sa m e folder a s th e


lin kin g file. Th e r ela tiv e lin k w ou ld ju st be th e file n a m e
(e.g ., file.h tm l).

Ch il d fol der : Th e lin ked file is on e folder dow n fr om th e


lin kin g file (in oth er w or ds, in a folder con ta in ed in th e
lin kin g file’s folder ). Th e r ela tiv e lin k sta r ts w ith a
for w a r d sla sh (/), th en in clu des th e folder n a m e,
a n oth er for w a r d sla sh , a n d th e file n a m e (/folder -
n a m e/file.h tm l).

Pa r en t fol der : Th e lin ked file is on e folder u p fr om th e


lin kin g file. Th e r ela tiv e lin k w ou ld be tw o per iods a n d a
for w a r d sla sh (../) a n d th en th e file n a m e (../file.h tm l).
Th ese pa tter n s ca n be r epea ted for a n y n u m ber of
folder s. So if a file is th r ee folder s u p fr om th e cu r r en t
file, th e r ela tiv e lin k w ou ld be ../../../file.h tm l. A n d
th er e ca n be g r ea t-, g r ea t-g r ea t-, g r ea t-g r ea t-g r ea t-
g r a n dch ildr en , a n d so on .

Table 5.1 Types of relative links


Relative link Relative Example from our sample
type path directory

Sa m e Fol der : file.h tm l Fr om th e h om e


Both files a r e in pa g e: a bou t.h tm l
sa m e folder

Ch il d: Lin ked /folder - Fr om h om e:


file is in n ex t n a m e/file.h t /stor e/ca r t.h tm l
folder dow n ml

Gr a n dch il d: /ch ild- Fr om h om e:


Lin ked file is tw o folder /folder - /stor e/or der s/001
folder s dow n n a m e/file.h t .h tm l
ml

Pa r en t : Lin ked ../file.h tm l Fr om /stor e/ to


file is n ex t folder h om e:
up ../in dex .h tm l

Gr a n dpa r en t : ../../file.h tm l Fr om
Lin ked file is tw o /stor e/or der s/ to
folder s u p h om e:
../../in dex .h tm l

Looking at our example website again, to make a link


from the home page (mysite.com/index.html in the root
directory) to cart.html, you could use a relative link.
Since cart.html is in the child folder /store/, we could
link to it using a relative path: /store/cart.html.

To create a relative link:


1. In y ou r w ebsite folder on y ou r com pu ter , cr ea te a n ew folder
ca lled im a ges.
2. Go to u n spla sh .com a n d dow n loa d a n y im a g e y ou ’d like.
Sa v e it in to th e im a g es folder y ou ju st cr ea ted a n d n a m e th e
im a g e file u n spl a sh .jpg.
3. In th e w ebsite folder , m a ke a du plica te of th e file
boiler pla te.h tm l a n d r en a m e th e n ew file 5.h t m l .
4. Open th e file 5.h t m l .
5. Rig h t a fter th e open in g <body> ta g , ty pe <a href=".
6. Ty pe /images/unsplash.jpg">.
7. Ty pe Check out this image!.
8. Ty pe </a>.
9. Sa v e th e file a n d open it in y ou r br ow ser .
10. Click th e lin k to displa y th e im a g e in th e w ebpa g e.

VIDEO 5.5

Creating Relative Links


Let’s take a closer look at the markup f or creating relativ e links, and learn how those
links behav e in the browser.

OTHER TYPES OF LINKS


Aside from internal and external links, here are two
other types of links you can add to a webpage. Y ou can
link to a specific section of a page, and you can link to
other applications, like email.

Linking to a specific section of the page


This is a great way to highlight specific content or drive a
user to a pertinent area. There are two parts to this link:

A ssig n a u n iqu e n a m e to th e section y ou w a n t to lin k to


by in clu din g th e id a ttr ibu te. For ex a m ple, sa y y ou
w a n t to a dd a lin k to y ou r pa g e th a t ta kes people to a
con ta ct for m . If th e con ta ct for m is u n der th e h ea din g
“ Con ta ct Me!” y ou w ou ld a ssig n a n id a ttr ibu te
("contact", per h a ps) to th e h ea din g :

<h3 id="contact">Contact Me!</h3>

Lin k to th a t id in th e a n ch or ta g :

<a href="#contact">Jump to Contact Form</a>

The id attribute is often assigned to a heading tag (as in


the “Contact Me!” example) because heading tags denote
the beginnings of sections. But id is a standard attribute
that can be applied to any HTML element.
In our link, we identify the section using the hash tag, or
number sign (#), followed by the value of the id
attribute (e.g., #contact). The hash tag tells the browser
“this is a specific location on the page.”

VIDEO 5.6

Link to a Specific Location on a Page


You’ll see the markup f or linking to a page section, as well as how the browser
behav es when y ou link to a page section.

To create a link to a specific location on a page:


1. In y ou r HTML file, ty pe or copy a n d pa ste sev er a l tex t
pa r a g r a ph s (be su r e to en close th em in <p> ta g s) betw een th e
open in g a n d closin g <body> ta g s. If y ou w ish , m a ke th e la st
pa r a g r a ph a br ief biog r a ph ica l sketch of y ou r self.
2. Pla ce th e in ser tion poin t in fr on t of th e la st <p> ta g to cr ea te
a h ea din g befor e th e la st pa r a g r a ph . Ty pe <h3>About
Me</h3> to defin e th e h ea din g .
Now , a dd a n id a ttr ibu te to th is h ea din g so y ou ca n lin k
dir ectly to it.
3. Pla ce th e in ser tion poin t in th e open in g ta g of th e h ea din g
elem en t a n d ty pe id="aboutme".
Th e en tir e lin e of code sh ou ld look like th is:
<h3 id="aboutme"
4. Go ba ck to th e top of th e docu m en t, a n d r ig h t a fter th e
open in g <body> ta g , ty pe <a href=".
5. Ty pe #aboutme"> to tell th e lin k to ju m p to th e a n ch or y ou
ju st cr ea ted.
6. Ty pe Skip to "About Me" to cr ea te th e la bel for th e lin k
th a t w ill be displa y ed to th e u ser .
7. Ty pe </a> to close th e a n ch or elem en t.
8. Sa v e th e file a n d open it in a br ow ser to test th e lin k.

In many real-world implementations, you’ll see the


browser smoothly scroll to the linked section. In order to
achieve that effect, you’ll need to add some CSS to your
website.

Linking to more than just webpages


Finally, links can do more than just take you from one
webpage to another. There is a growing set of Uniform
Resource Identifiers (URIs) that tell the browser which
specific applications a link should open in. While email
links are the most common, you can also specify
telephone numbers (tel:), file servers (ftp:), and
more.
Email links are links that will open an email app on your
device, with the email address (and potentially other
information) filled in. To create one, you structure the
link like this:
Click h er e to v iew code im a g e

<a href="mailto:[email protected]">
→Email Joe</a>

Notice that there’s no URL here, just the prefix mailto:


and the email address.

Tip
Using mailto: is a great way to get a lot of spam email. A much more secure
and user-friendly way to add an email form to your webpage is to use a form.
You’ll learn about forms in Chapter 9.

VIDEO 5.7

Advanced Mailto Links


You can include more than just the main recipient’s email address in email links. You
can also add CC and BCC addresses, attach a subject line to the message, and ev en
include message text.

VIDEO 5.8

Open a Link in a New Window


Construct a link that opens a page in a new window.

LINK TARGETS
Before we wrap up the chapter, there’s one more
attribute you should know about, and that’s target.
Y ou’ve likely browsed websites on which the links
opened in new tabs or windows. A common reason is
that the webpage author hopes the user will close the
new tab when they’re done and return to their site.
That’s achieved by using the target attribute and the
value blank. For example, to open casabona.org in a
new tab, use this link:
Click h er e to v iew code im a g e

<a href="https://casabona.org"
→target="_blank">Link that opens in a
→new tab</a>.

Other Link Targets


While not as common as _blank, sev eral other link targets can be used in HTML:

_self opens the link in the same window (the def ault).

_parent: If the current page was opened in a new window, y ou can use
this to open subsequent links in the original window.

_top opens the page in the f ull body of the window (usef ul if using the
<iframe> element).

An <iframe> is a way to embed the content of one page into another, and
is now used much less of ten than in the past. Today, y ou’re most likely to
encounter them when y ou embed a YouTube v ideo on a page, which y ou’ll
learn about in Chapter 7.

framename opens the page in a specif ic <iframe>.

To create a link that opens in a new window:


1. In y ou r HTML file, ty pe <a href= "https://google.com".
2. Ty pe target="_blank">.
3. Ty pe Visit Google</a>.
4. Sa v e th e file.
5. Open th e file in y ou r br ow ser a n d click th e lin k to see it open
th e h om e pa g e of g oog le.com in a n ew w in dow .

While it’s considered best practice to open links in the


same window, there might be legitimate reasons to send
the user to a new window. If you do decide to open links
in new windows, you should at least let the user know
what to expect. Y ou can do so by adding simple text (like
“new window”) to the link label or by adding an icon, as
shown in FIGURE 5.5.
Figure 5.5 An example of a new window indicator
icon from CodePen (codepen.io/svinkle/pen/BreKRJ)

WRAPPING UP
With your knowledge of formatting, organization, and
now linking, you’re ready to move into the structure and
layout side of HTML.

In the next chapter, you’ll learn about the building


blocks that are used to lay out a webpage.
6

Structure and Layout with


HTML
In This Chapter

Webpage Layout
Block vs. Inline Elements

Page Sections
Building a Blog Article Layout

Wrapping Up

Aside from formatting text, HTML gives us a set of tools


for defining areas of a webpage. While they don’t affect
the way a page looks (that’s what CSS is for), it’s yet
another way to apply semantic meaning to webpages for
users and anything else that’s reading the page.
In this chapter, you’ll learn the kinds of areas you can
create on a page, find out more about block versus inline
elements, and get a preview of the CSS box model. Let’s
dive in!

WEBPAGE LAYOUT
If you’ve been to any website, you’ll know that the items
on a page are grouped into areas with specific functions,
such as a header, a footer, a main area (which can
contain several elements), and a sidebar. As an example,
take a look at the home page of the New York Times
with a box drawn around each item (FIGURE 6.1).
Figure 6.1 The layout for the New York Times home
page

Each of these boxes is an area defined in HTML and


styled with CSS. But the browser knows how to arrange
the areas thanks to the HTML elements used to define
them.
If you’d like to see how a page is structured in the
Chrome browser, you can do so using the Web
Developer extension. This extension adds a number of
developer-friendly tools to Chrome, including options for
drawing an outline around individual webpage elements.
Y ou’ll start by downloading the extension from the
Chrome Store and installing it.

VIDEO 6.1

Preview of the Box Model


The term box model is used f or CSS. It def ines the box around each element—its
padding (spacing f rom content to borders), margins (spacing around the outside of the
box), borders, and content. It’s integral to understanding how to best sty le a page.
But its building blocks (pun a little intended) are here in the HTML. Each element can
be considered its own box. How it looks, and how it’s positioned, is def ined by the
CSS.

To outline webpage elements in Chrome:


1. Open th e Goog le Ch r om e w eb br ow ser a n d g o to th e
Ex ten sion s section of th e Ch r om e Stor e:
ch r om e.g oog le.com /w ebstor e/ca teg or y /ex ten sion s (FIGURE
6.2).
Figu r e 6.2 Th e Ch r om e Stor e offer s a w ide r a n g e of
ex ten sion s th a t a dd fu n ction a lity to th e br ow ser .

2. En ter Web Dev el oper in to th e Sea r ch field a n d pr ess


Retu r n /En ter . Th e pa g e displa y s th e r esu lts of th e sea r ch
(FIGURE 6.3).

Figu r e 6.3 Sea r ch in g for “ Web Dev eloper ” r etu r n s a lon g


list of r esu lts.

3. Fin d Web Dev eloper by ch r ispeder ick.com in th e r esu lts (it


sh ou ld be n ea r th e top) a n d click it to loa d its pa g e in to th e
br ow ser (FIGURE 6.4).
Figu r e 6.4 Th e Web Dev eloper pa g e in th e Ch r om e Stor e

4. Click th e A dd To Ch r om e bu tton a n d follow th e in sta lla tion


in str u ction s.
Wh en th e in sta lla tion is com plete, y ou ’ll n otice a n ew cog
icon in th e toolba r .

5. Click th e cog icon . A ta bbed set of con tr ols a ppea r s.


6. Click th e Ou tlin e ta b. A m en u lists sets of elem en ts th a t ca n
be ou tlin ed (FIGURE 6.5).

Figu r e 6.5 Select Ou tlin e Block Lev el Elem en ts on th e


Ou tlin e ta b to dr a w a box a r ou n d ea ch block-lev el
elem en t.

7. Click to select th e elem en ts y ou w a n t to ou tlin e. Ou tlin e


Block Lev el Elem en ts is a g ood sta r tin g poin t, so select th a t
item in th e m en u .
A n ou tlin e is dr a w n a r ou n d ea ch block-lev el elem en t on th e
pa g e (FIGURE 6.6).
Figure 6.6 The home page of nytimes.com with
elements outlined using the Web Developer extension
in Chrome

VIDEO 6.2

Outlining Elements with the Web Developer Extension


In this v ideo, y ou’ll see how to use the Web Dev eloper extension f or Chrome to
outline elements of a webpage.

VIDEO 6.3

Outlining Block and Inline Elements Together


The Web Dev eloper extension doesn’t outline inline elements, so here I apply CSS to
block and inline elements so that y ou can see more clearly how they work with each
other.

BLOCK VS. INLINE ELEMENTS


Chapter 4 touched on this a bit, but there are essentially
two kinds of HTML elements: block elements and inline
elements. The best way to think about them is by how
much page width they take up.

Block elements take up the full available width, thus


creating their own block on a page. Style-wise, each
element fits into the box model and has its own spacing.
A paragraph is a block element (FIGURE 6.7).

Figure 6.7 A paragraph takes up the full available


width.

Inline elements, on the other hand, take up only the


width they need. Again, looking at this stylistically, by
default there is no spacing applied directly to inline
elements. <strong>, <em>, and <a> are all inline
elements (FIGURE 6.8).

Figure 6.8 A link takes up only the width that it


needs to take up.

All the elements that we consider “layout elements” in


the next section are block elements.

Tip
One caveat, which will come up in the CSS chapters: you can change the
default type of any element. So if you want to turn links into block elements,
adding a little CSS will make it happen.

PAGE SECTIONS
Before diving into the actual elements, it’s important to
define (at least loosely) the areas that will be included in
the page design. A good way to get an idea of a page’s
design and layout is to sketch out a wireframe. A
wireframe is a blueprint or a general framework of a
webpage. Its focus is on content priority and lacks the
niceties of visual design, like text styling or colors. In
short, it should tell us where content and elements go. A
typical webpage layout includes a few basic areas
(FIGURE 6.9).

Figure 6.9 A wireframe of a webpage that uses


common page sections

Now that you have a better understanding of how a


page is laid out, here are the seven HTML elements that
define these areas.
VIDEO 6.4

Walking Through the Wireframe


This wiref rame has sev eral areas that are worth pointing out, along with some cav eats
and nice-to-knows. Let’s take a closer look at it.

Header, footer, nav

The first areas to examine are the header, footer, and


navigation. They are grouped because you can have
each on a macro (site-wide) level and a micro (area-
specific) level.

The header is the area that contains information at the


top of a webpage or section of a webpage. A site’s header
generally includes the site title and maybe a tagline or
logo. Other elements, like articles, can also have a
header tag, which might include the title, date, and
author’s name. The navigation is also usually found in
the header. The tag for this element is <header>.

The navigation includes links to other important pages


on the site. On a micro level, groups of pages or articles
can have their own navigation (if an article is spread
across several pages, for example). Its tag is <nav>.

The footer is at the bottom of the page or section of a


page and is generally used to provide extra information.
For a section of a page, it could display the date it was
published or tags or keywords. For the entire site, the
footer can include additional links, copyrights, or other
legal disclosures. Y ou can get really creative with this
section! Its tag is <footer>.

Both the header and footer can be pretty flexible as far as


content and layout, but navigation tends to follow a
more specific structure. That’s because unordered lists
(which use the <ul> element) are recommended for
navigation, since they are an unordered list of links!

Lists for Navigation


Over the years, the use of unordered lists for navigation
has been hotly debated. There are several arguments for
and against.
The recommendation here comes from the HTML5
specification explicitly using lists in their nav examples
(html.spec.whatwg.org/multipage/sections.html#the-
nav-element) and from accessibility experts stating their
importance in relation to screen readers.

Several years ago, CSS-Tricks published an article about


it that garnered a lot of strong opinions. Their
postmortem on the article is a great summary of the
pros and cons of lists in nav: css-tricks.com/wrapup-of-
navigation-in-lists/.
A simple site navigation element might have links to the
home, about, and contact pages (FIGURES 6.10 and
6.11).

Figure 6.10 The HTML markup for a simple


navigation element
Figure 6.11 The simple navigation element as
rendered in a web browser

To create simple site navigation:


For this task, assume there are three pages: a home page
(index.html), an about page (about.html), and a contact
page (contact.html).
1. Ty pe <nav to cr ea te th e open in g of th e n a v ig a tion elem en t.
2. Ty pe th e a ttr ibu te role="main" beca u se th is w ill be th e
pa g e’s pr im a r y n a v ig a tion elem en t.
3. Ty pe > to close th e open in g ta g .
4. Ty pe <ul> to beg in th e u n or der ed list of lin ks to oth er pa g es
in th e site.
5. Cr ea te a n a v ig a tion item for th e h om e pa g e by ty pin g

<li><a href="index.html">Home </a></li>.

6. Do th e sa m e for th e a bou t pa g e; ty pe

<li><a href="about.html">About </a></li>.

7. A dd th e la st lin k, for th e con ta ct pa g e. Ty pe

<li><a href="contact.html"> Contact</a></li>.

8. Ty pe </ul>.
9. Ty pe </nav>.

Tip
If you’re creating links but you don’t have a target URL or file name yet, you
can use the hash symbol (#). This tells the browser “this is a link, but it
doesn’t go anywhere.”

Section, article, aside, main


With the more general areas of a website covered, let’s
move to the content that changes with each page.
A section (tag: <section>) is any discrete area of a
website with related content. For example, on a home
page there might be an “about me” section, an “articles”
section, and a “photo gallery” section. Y ou have a lot of
flexibility here.
An article (tag: <article>) is an area that is often self-
contained and can stand on its own (and is often related
to syndication). Blog posts or a page’s main copy are
usually described as articles.

An aside (tag: <aside>) is auxiliary information that’s


related to, but not integral to, the main content. Asides
are often described as “sidebars,” but they don’t need to
be physically to the side of the content. The tips in this
book can be considered asides.

VIDEO 6.5

Making a Header with Navigation


Take y our site nav igation one step f urther and put it in a f ull header, with a site title.

ID and class
id and class are two attributes that can be applied to any element. They ’re used to
apply some def inition to the element they ’re assigned to.
Generally, each ID is unique (as in, only one element has a specif ic ID), and a class
can be assigned to multiple elements.

In practice, IDs are usually used by Jav aScript, and classes are used by CSS.
With all of our building blocks in place, y ou can create a simple blog lay out. You can
use a sample content generator (like loremipsum.io) or come up with y our own.

To match the aside tag, there’s also a <main> tag,


which would denote the main content of the page. This
will likely be a wrapper for your articles or sections.

If you’re looking at other websites’ markup, you might


have noticed a very common tag: <div>. This tag, short
for “division,” predates the ones we’ve talked about and is
often used for areas of a website that don’t have an
otherwise clearly defined purpose. Really, it’s an all-
purpose tag, if you’re not sure what to use.
Tip
I’d recommend giving divs an ID or class to make it clearer to those reading
your code what kind of content they’re looking at.

BUILDING A BLOG ARTICLE LAYOUT


Now that you have all the building blocks (pun totally
intended), you can put together a simple blog article
page (CODE 6.1). Anything not relevant to this chapter
is omitted and replaced with three dots (...).

To create a page header:


1. Ty pe <header to open th e header ta g .
2. Ty pe role="banner".
3. Ty pe > to close th e open in g h ea der ta g .
4. On a n ew lin e, ty pe <h1 id="site-title">Welcome to my
Site!</h1>.
We’v e a dded th e ID site-title to tell br ow ser s a n d sea r ch
en g in es “ th is is th e n a m e of th e site.”
5. A dd th e n a v ig a tion cr ea ted ea r lier in th is ch a pter .
6. Ty pe </header> to close th e pa g e h ea der ta g .

Tip

As you become familiar with more samples of code from pages around the
web, you might notice that sometimes they use “id,” and sometimes they use
“role” instead. That’s because there are specific roles defined for
accessibility. We’ll talk about that more in Chapter 24, but for now, you can
get a full list of roles at developer.mozilla.org/en-
US/docs/Web/Accessibility/ARIA/ARIA_Techniques.

Tip
Some HTML elements will not have a role assigned to them, because they
already communicate a role. For example, we don’t need to assign the role
“main” to the <main> element.

To create the main article section:


1. Open th e w r a pper for th e con ten t by ty pin g <div
class="wrapper">.
You ’r e open in g th e w r a pper div elem en t h er e, bu t y ou ’ll
close it w h en w e cr ea te th e <aside> elem en t.
2. Open th e m a in section by ty pin g <main>.
3. Ty pe <article>.
4. Ty pe <header> to open th e a r ticle’s h ea der .
5. A dd a h ea dlin e u sin g th e <h2> ta g : ty pe <h2>10 Reasons
HTML is so great!</h2>.
Use a n h2 ta g h er e beca u se th e site title sh ou ld be th e on ly h1
on th e pa g e.
6. Ty pe </header>.
7. Ty pe a ll of th e con ten t for th e a r ticle. Th is sh ou ld in clu de
tex t like pa r a g r a ph s, lists, im a g es, a n d h y per lin ks.
8. Ty pe <footer> to open th e a r ticle’s footer .
9. Th e pu blish da te w ill g o h er e. Ty pe <p>Published March 6
at 11:06pm</p>.
10. Ty pe </footer>.
11. Ty pe </article> a n d th en </main> to close ou t th e r est of
th e elem en ts.

CODE 6.1 The markup for a simple blog article


Click h er e to v iew code im a g e

<html>
...
<body>
<header role="banner">
<h1 class="site-title">Welcome
to my site!</h1>
<nav>
<ul role="main">
<li><a
href="index.html">Home</a></li>
<li><a
href="about.html">About</a></li>
<li><a
href="contact.html">Contact</a></li>
</ul>
</nav>
</header>

<div class="wrapper">
<main role="main">
<article role="article">
<header>
<h2>10 Reasons
HTML is so great!</h2>
</header>
...
<footer>
<p>Published March
6th at 11:06pm</p>
</footer>
</article>
...
</main>

<aside>
<h3>Related Articles</h3>
<ul>
<li><a
href="/articles/css.html">Wait until you
see CSS</li>
...
</ul>
</aside>
</div>

<footer>
<p>Copyright Joe Casabona</p>
</footer>
</body>
</html>

To create a sidebar:
1. Ty pe <aside>.
2. Ty pe th e h ea din g <h3>Related Articles </h3>.
3. Cr ea ted a n u n or der ed list of a r ticles. Ty pe <ul>.
4. A dd th e fir st item : ty pe <li><a href=
"/articles/css.html">Wait until you see CSS</a>
</li>.
5. A dd a s m a n y r ela ted a r ticles a s y ou ’d like.
6. Ty pe </ul>.
7. Ty pe </aside> to close th e aside elem en t.
8. Ty pe </div> to close th e w r a pper div.

To create a site footer:


1. Ty pe <footer>.
2. A dd on e pa r a g r a ph for th e copy r ig h t lin e. Ty pe
<p>Copyright [YOUR NAME]</p>.
3. Ty pe </footer>.

For the complete markup, see Code 6.1. To see the page
rendered in a browser, see FIGURE 6.12.
Figure 6.12 A sample blog article page containing a
header, site navigation, a main article section, a
sidebar, and a footer

Tip
Reminder: all the source code for this book can be found at
GitHub.com/jcasabona/html-css-VQS.

WRAPPING UP
Y ou now have the basic HTML elements that are
necessary to semantically lay out a page. Y ou can find a
complete list of semantic elements available in HTML5
at
www.w3schools.com/html/html5_semantic_elements.a
sp.

Up until now we’ve focused a lot on text and how it’s laid
out. Now let’s turn our attention to something more
visually appealing: media.

VIDEO 6.6

Building a Blog Article Layout


In this v ideo, y ou’ll go through all the markup that’s required to create a single blog
article. You’ll also see how the article looks in the browser.
7

Media
In This Chapter

How Does Media Work on the Web?


Images

Adding Images to a Page


Responsive Images: Considering Different Devices and
Connections

The <picture> Element

Using SVG

Other Media
Embedding Video

Embedding Audio
Storing Multimedia Files

Wrapping Up

Y ou’ve learned how to add text and create semantic


layouts, and that’s great! But media—images, video, and
audio—is what makes websites really stand out.
Media in this case refers to any non-plain-text file. And
in this chapter, you’ll learn how to embed images,
videos, and audio. Y ou’ll also learn the ins and outs of
finding good resources and where to host multimedia.

HOW DOES MEDIA WORK ON THE


WEB?
The nice thing about using media on a webpage is that
all you have to do is store the media files on your web
server and insert links to them into your HTML files. The
browser will know how to open most common forms of
media (FIGURE 7.1).

Figure 7.1 An image open in a browser window

But if you use HTML tags to tell the browser the type of
media you’re linking to, you can display that media
directly on the page—without having to open separate
windows or applications (FIGURE 7.2).

Figure 7.2 An image embedded on a page

This is known as embedding the media file. The media


can be viewed, watched, or listened to without the user
leaving the page.
Thanks to features of HTML5, you can tell the browser
how to handle images, video, and audio. Y ou can embed
them directly into the page, and even give some
instruction on how to display or control them—play,
pause, mute, rewind, and more.
Other forms of media, like Microsoft Word documents,
PDFs, and presentation software slide shows, can be
linked in the browser but not embedded. The browser
will rely on another program on the device to handle
opening the file.

Web Image Format Acronyms


The image f ormats most commonly used on websites are usually ref erred to by
cry ptic acrony ms. Here they are, along with what they stand f or:

JPG/JPEG: Joint Photographic Experts Group, in honor of the organization


that inv ented the f ormat

GIF: Graphics Interchange Format

PNG: Portable Network Graphic

SVG: Scalable Vector Graphic

IMAGES
Chances are that of all the types of media, you’ll work
with images the most, so that’s a fantastic starting point.

Types of images
There are lots of different types of image that can be
stored in a variety of file formats; these formats serve
different purposes. For example, the most common type
of image used on webpages is photos. They are typically
in JPEG format, which compresses them so that their
file sizes are not gigantic. Simple animated images will
be in GIF format. Lightweight graphics will often be in
PNG format; they can use transparent backgrounds.
And more complex graphics that need to be displayed at
several different sizes are usually in scalable vector
format (or SVG). Y ou can resize SVGs without worrying
that you will lose image quality.
The types of images supported in HTML are determined
by the browser, and as a result, certain file types will
work only in certain browsers.
Pixel vs. Vector Graphics
As f ar as the web is concerned, there are two basic categories of graphics: pixel
(JPEG, PNG, GIF) and v ector (SVG).

Pixel graphics are made up of a grid of colored dots (pixels, short f or “picture
elements”), so an 800×600 pixel graphic is 800 dots wide by 600 dots tall. If y ou try
to display a pixel graphic at a bigger size (“Scale it up”), y ou’ll run into pixelation. In
other words, the browser will actually increase the size of each pixel, so y ou will start
to see big colored squares.

Vector graphics aren’t stored as those dots. They are a set of instructions to the
browser f or how to draw the image. That means that there’s no inherent size
associated with it. You tell the browser the image dimensions y ou want, and it will
adjust the instructions accordingly.
While pixel graphics are great f or images with continuous tones of color like photos,
v ector graphics are much better f or sharp-edged graphics like logos, icons, and
images representing data.

VIDEO 7.1

Scaling SVGs
To understand why SVGs are an important part of web design, y ou’ll see the ef f ects
of scaling a JPEG v ersus scaling an SVG.

The most common image types will work in all


browsers: JPEG, GIF, PNG, and SVG. These images use
the file name extensions .jpg, .gif, .png, and .svg,
respectively (FIGURE 7.3).
Figure 7.3 This image of space is called space.jpg.

Tip
For a full table of image types, file name extensions, and supported
browsers, see developer.mozilla.org/en-US/docs/Web/HTML/Element/img.

ADDING IMAGES TO A PAGE


Once you’ve got the images you want to use in the right
format, it’s time to add code to your HTML to insert the
images into the page’s flow. Next, you’ll learn about two
elements you can use to place an image on a page:
<img> and <figure>.
The <img> tag
For all supported image types except SVG (that’s coming
later), you will use the image embed tag <img>. This tag
is unique because in addition to requiring an attribute
(src), it has no end tag. Here’s some sample markup:
Click h er e to v iew code im a g e

<img src="space.jpg" alt="A view


→of the Andromeda Galaxy"
→title="A view of the Andromeda
→Galaxy" />.

All images should also include an alt attribute, whose


value is text that describes the image. While this isn’t
required for the tag to work, it is required to make your
website accessible (for more on website accessibility, see
Chapter 24).
The title attribute can also include this text. The main
difference (besides semantic meaning) is that the title
will appear in a tool tip when you hover over an image
(FIGURE 7.4).

Figure 7.4 The image’s title showing on hover


VIDEO 7.2

Adding an Image to a Webpage


You will see how to add an image to a page, as well as how to design the f older
structure of the website to make sure the image appears properly.

To add an image to a webpage:


1. Ty pe <img to open th e im a g e em bed ta g .
2. Ty pe src= follow ed by th e pa th to th e im a g e. In th is
ex a m ple, ty pe "space.jpg".
3. A dd th e alt a n d title a ttr ibu tes. Ty pe alt="A view of
the Andromeda Galaxy" title="A view of the
Andromeda Galaxy".
4. Close th e img ta g by ty pin g />.
5. Sa v e th e file a n d open it in y ou r br ow ser to see th e r esu lt
(Fig u r e 7 .2 ).

The <figure> tag


If you want to make meaningful additions to the flow of
your page, or group an image with a caption, you’ll use a
figure with an optional caption element. Its tag is
<figure>, and to associate a caption with it you insert
the element <figcaption> inside it. The structure
looks like this:
Click h er e to v iew code im a g e

<figure>
<img src="space.jpg" alt="A view
→of the Andromeda Galaxy" />
<figcaption>A view of the
→Andromeda Galaxy</figcaption>
</figure>

Note these points about the use of the figure tag:

You ca n pu t m or e th a n on e im a g e in a <figure> ta g if
th ey m a ke sen se tog eth er in con tex t.

Ev er y th in g in side th e open in g a n d closin g <figure>


ta g s cr ea tes a sin g le, self-con ta in ed u n it.

Sin ce fig u r es a r e self-con ta in ed, y ou sh ou ld be a ble to


m ov e a fig u r e u p or dow n on a pa g e w ith ou t ch a n g in g
th e m ea n in g of th e pa g e.
That last point also means that not all images are
figures.

Figures: Not Just for Images


As it turns out, the <figure> tag can be a pretty f lexible element. Since it’s a self -
contained piece of content that should add v alue to the document, a f igure doesn’t
just need to be an image or set of images.
You can put code, audio, v ideo, or ev en ads (which can hav e their own specif ic
requirements) in f igures.

To add a figure to the page:


1. Ty pe <figure> to open th e figure elem en t.
2. A dd th e im a g e fr om ea r lier , w ith ou t th e title a ttr ibu te.
Ty pe <img src="space.jpg" alt="A view of the
Andromeda Galaxy." />.
3. Ty pe <figcaption>A view of the Andromeda Galaxy.
</figcaption> to a dd a ca ption to th e im a g e.
4. Ty pe </figure> to close th e figure elem en t.
5. Sa v e th e file a n d open it in y ou r br ow ser (FIGURE 7.5).

Figure 7.5 Our photo of the Andromeda galaxy, now


with a caption
VIDEO 7.3

Using Figures for Code Samples


Figures aren’t just f or images. In this v ideo, y ou learn how to use the <code> tag to
add a f igure that contains code to a webpage.

RESPONSIVE IMAGES: CONSIDERING


DIFFERENT DEVICES AND
CONNECTIONS
One of the biggest issues with adding images to
webpages is that, depending on the file size of the
images, they can unnecessarily bloat the site and make it
very slow to download. Here’s an example: the full size
of the space image is 6200×6200, coming in at 4.2MB
(4200KB).
If we resize it to 1920×1920, 30 percent of the original
size, the file size is 415KB. That’s 9 percent of the original
file size!

That size difference will have a considerable effect on the


time it takes to download the page, and it will have little
to no effect on how most visitors see the image; 1920
pixels is still overkill if you consider that most mobile
screen sizes are considerably smaller.

VIDEO 7.4

Image Download Test


Seeing is believ ing! Here’s a download test comparing the perf ormance of dif f erent
image sizes and connection speeds.

VIDEO 7.5

Resizing an Image
Using the srcset attribute requires that multiple v ersions of the same image be
av ailable to the browser. In this v ideo, y ou’ll learn how to use a couple of popular
applications to resize an image.
However, you might wonder what happens if someone is
viewing the page on a big monitor or even a TV, where
they would rather take advantage of the full size of the
screen. That’s where the srcset attribute comes in.

This attribute tells the browser that it has a range of


image files to choose from when rendering the <img>
element.

Here’s an example:
Click h er e to v iew code im a g e

<img srcset="
space-original.jpg 4x,
space-large.jpg 3x,
space-medium.jpg 2x,
space-small.jpg 1x"
src="space-medium.jpg" />

Note that src is included to provide a fallback for


browsers that don’t support srcset yet.

Within the srcset attribute, include a comma-


separated list of different images (or the same image at
different sizes). For each image, provide its path as well
as a relative size value (that is, 4 times, 3 times, etc.)
notated as 4x, 3x, etc. (Note that 1x is implied and not
required).
These numbers represent the pixel density of the user’s
browser (the number of pixels available in a chosen area
of the display), and they tell the browser how to choose
which image to download and serve to the user
depending on the device’s pixel density. If the device has
a very high pixel density, it can choose to display the 4x
image. If its display has a lower resolution, it might
download and display only the 2x or 1x image. This will
save on load time and bandwidth.

Alternatively, you can specify the image widths in pixels


instead of expecting the browser to use pixel density to
decide which file to use. So you would replace 4x with
6200w (6200 pixels is the original image’s width), 3x
could be replaced with 4650w, and so on. This gives the
browser more information about the image, so it can
replace the images while taking into account both the
characteristics of the device and the image width.

To add an image using srcset:

1. Cr ea te th r ee sizes for y ou r im a g e: 1 02 4 , 8 00, a n d 6 00 pix els


w ide.
See V ideo 7 .5 to lea r n h ow , if y ou n eed to.
2. Sa v e th em in th e sa m e folder a s y ou r HTML file.
For th e pu r poses of th is ta sk, n a m e th e im a g es follow in g th e
pa tter n spa ce-[size].jpg, w h ich g iv es u s spa ce-
or igin a l .jpg, spa ce-1024.jpg, a n d so on .
3. In y ou r HTML docu m en t, ty pe <img srcset=".
4. On th e n ex t lin e, ty pe space-original.jpg 6200w,.
5. Pr ess Retu r n or En ter , th en ty pe space-1024.jpg 1024w,.
6. Pr ess Retu r n or En ter , th en ty pe space-800.jpg 800w,.
7. Pr ess Retu r n or En ter , th en ty pe space-600.jpg 600w".
8. We a lso n eed a fa llba ck for older br ow ser s th a t don ’t su ppor t
srcset. Ty pe src="space-1024.jpg".
9. Ty pe /> to close th e im a g e ta g .

Tip

If you want to learn a lot more about optimizing images, especially for
mobile, Smashing Magazine has a fantastic write-up:
www.smashingmagazine.com/2019/10/imagekit-guide-optimizing-images-
mobile/.

THE < P I C T U R E > ELEMENT


If you want more fine-grained control of when images
show up, you could use the <picture> element. It’s
very similar to using srcset, but the markup is a bit
different.

One thing it makes use of is media queries, which you’ll


learn more about in Chapter 17. The quick explanation is
that you can use CSS to get information about the
browser, like screen width, and then adjust the display of
your website based on that information.
To use the <picture> element to show different
images:
1. Cr ea te th r ee sizes for y ou r im a g e: 1 02 4 , 8 00, a n d 6 00 pix els
w ide.
See V ideo 7 .5 to lea r n h ow to cr ea te th ese v er sion s of y ou r
im a g e if y ou n eed to.
2. Sa v e th em in th e sa m e folder a s y ou r HTML file.
For th e pu r poses of th is ta sk, th e im a g es w ill be n a m ed
follow in g th e pa tter n spa ce-[size].jpg, w h ich g iv es u s
spa ce-or igin a l .jpg, spa ce-1024.jpg, a n d so on .
3. In y ou r HTML docu m en t, ty pe <picture>.
4. On a n ew lin e, ty pe <source.

VIDEO 7.6

Seeing srcset in Action


This v ideo shows y ou how to add a responsiv e image using srcset, and then
y ou’ll see what happens as the browser is resized.

5. Ty pe media="(min-width: 1025px)".
Th is is th e m edia qu er y . It sa y s, “ If th e br ow ser h a s a
m in im u m w idth of 1 02 5 px , u se th is im a g e.”
6. Ty pe srcset="space-original.jpg">.
7. On a n ew lin e, ty pe <source media="(min-width:
801px)" srcset="space-1024.jpg">.
8. On a n ew lin e, ty pe <source media="(min-width:
601px)" srcset="space-800.jpg">.
9. On a n ew lin e, ty pe <img src="space-600.jpg" />.
Th is ser v es a s a fa llba ck in tw o ca ses: for br ow ser s th a t don ’t
su ppor t th e picture a n d source elem en ts, a n d for w h en
ev er y m edia qu er y r etu r n s false. In th is ca se, it’s for w h en
th e br ow ser w in dow h a s a w idth of 6 00px or sm a ller .
10. Ty pe </picture>.

Ultimately, there’s no major difference between srcset


and picture, except that srcset does a bit more of the
work for you; srcset is the method more commonly
used today.

USING SVG
If you can use Scalable Vector Graphics (SVG), that
would go a long way in saving you on file size. But SVGs
may not be as straightforward to use, mostly because
they have to be designed in a program like Adobe
Illustrator.
SVGs are best used for illustrations or logos and can’t be
used for photographs (FIGURE 7.6). These are
computer-generated graphics that are more abstract
than photographs, which accurately depict real life.
Illustrations and logos can be described as rules more
efficiently.

Figure 7.6 This image is a good example of an SVG.

The reason for that is the same reason they scale so well:
the image data is stored not as pixels, but by
mathematical instructions for drawing the image. That
means that if you resize the image, the display pixels are
recalculated for the resolution of the screen. So the
image is sharp and crisp at any size, without pixelation.
See FIGURE 7.7 for an example of the source code for
Figure 7.6.

Figure 7.7 A sample of source code for an SVG

Another nice thing about SVGs is that they can be


treated like any other image, using the img tag. Here’s
the HTML for including Figure 7.6 on a webpage:
Click h er e to v iew code im a g e

<img src="rocket.svg" alt="my rocket


→ship" />

But when you add a size to it, the graphic scales


appropriately (FIGURE 7.8):

Figure 7.8 What happens when you scale an SVG to


over 9000px. Notice there is no pixelation.

Click h er e to v iew code im a g e

<img src="rocket.svg" width="9001px"


→alt="my rocket ship" />
Y ou can also add an SVG directly to a webpage using the
<svg> tag. Here’s what that could look like:
Click h er e to v iew code im a g e

<svg>
<circle cx="100" cy="100" r="50"
→fill="red" />
</svg>

The result is shown in FIGURE 7.9.

Figure 7.9 Embedding an SVG circle directly on a


webpage

VIDEO 7.7

Experimenting with SVG


In this v ideo, y ou’ll take drawing SVG one step f urther by seeing how changing the
v alues (including the shape element) af f ects the SVG.

To use SVG to draw a square:

Here, you’ll make a blue square.


1. Ty pe <svg id="square">.
Th e id ca n be a n y th in g . I u sed square to clea r ly descr ibe
w h a t is bein g dr a w n .
2. On th e n ex t lin e, ty pe <rect.
3. Ty pe x="0" y="0".
Th is tells th e br ow ser th e sta r tin g coor din a tes of th e sh a pe.
In th is ca se, y ou w a n t th e sh a pe to be in th e u pper -left cor n er
of th e pa g e, so y ou ca n sta r t a t 0, 0 (a s in 0 pix els to th e left,
a n d 0 pix els dow n ). I en cou r a g e y ou to ex per im en t w ith
th ese n u m ber s to see w h a t th ey do.
4. Ty pe width="100" height="100".
Th is sets th e dim en sion s of th e squ a r e.
5. Ty pe fill="blue".
Th is defin es th e color of th e fill.
6. Close th e rect elem en t by ty pin g />.
7. Close th e SV G by ty pin g </svg>.

See the resulting image in FIGURE 7.10.

Figure 7.10 Y our code created this blue SVG square.

Tip
SVG is a great format to use for icons on your website because their code is
lightweight. The other way is to use icon fonts, which you’ll learn about in
Chapter 13.

HTML Shapes
To help draw SVGs, HTML has a set of elements f or basic shapes. They are circle,
rect (f or rectangles), line, polyline, polygon, and path. You can learn more about
each of these at https://dev eloper.mozilla.org/en-
US/docs/Web/SVG/Tutorial/Basic_Shapes.

This book does not go into depth about these elements, because in general y ou can
use tools like Illustrator to create SVGs.

OTHER MEDIA
Aside from images, you can embed videos and audio
directly into a webpage. In this section, you’ll learn not
only how to do that, but also the kinds of video and
audio files that can be displayed by common modern
web browsers. Y ou’ll also learn about factors to consider
when storing large media on your server.

Video and audio file “formats”


When web developers talk about embedding video and
audio files in webpages, they generally refer to a file’s
format to distinguish one kind of file from another. Y et
web developers use “format” in a general sense to
describe a combination of characteristics of a file,
whereas video and audio professionals use the word in a
stricter sense. These divergent uses of the word can lead
to confusion and misunderstanding, so it’s worth taking
a moment to try to sort out the issue.

What distinguishes one kind of media file from another


is a complex mix of technical parameters, which can be
broken down into file type, codec, and format:
File type: Also called a file container, this is the way
that the video or audio data is packaged into a file that a
computer can read. Anything with a file extension is a
file type, like .MOV, .MP4, etc. Each of these file types
can contain video or audio data stored in one of several
different ways (or even other kinds of data, like image
data, subtitles, etc.). These file types are often called
“formats,” even though the video in one .MP4 file, for
example, might be of a very different type from the video
in another .MP4 file.

VIDEO 7.8

Creating a Graphic with Canva


In this v ideo, y ou’ll learn how to use Canv a to make a simple image, which y ou can
then use on y our website.

Finding and Making Images


Finding the right images has gotten considerably easier ov er the last f ew y ears, but
it can still be a slog.

First and f oremost, don’t just do a Google search. The images y ou’ll f ind that way
can be subject to copy right, and it’s not alway s the saf est way to get what y ou’re
looking f or: roy alty -f ree images. These are images y ou can get f or f ree, or pay f or,
and use on y our own websites.
A great source f or f ree roy alty -f ree images is Unsplash (https://unsplash.com).
There’s lots of f antastic stuf f here. If y ou don’t f ind what y ou’re looking f or there,
both https://depositphotos.com/ and https://istock.com are good sources, but y ou will
hav e to pay.
If y ou want to make y our own images, apps like Photoshop and Af f inity Photo are
popular choices. But I lov e https://canv a.com. You can easily create graphics of any
size, use their templates, and f ind great stock photos there too. You can use it f or
f ree, and y ou can pay f or upgrades that giv e y ou more f eatures.

Codec: Recording video or audio data directly from a


camera or a microphone produces truly vast amounts of
digital data. To make this data more manageable, it’s
almost always compressed for storage, then
decompressed when it’s needed for editing or playback.
The media industry uses numerous standards for this
process; these are known as codecs short for
“compressor/decompressor.” Y ou can think of the codec
as the “language” in which the video or audio data is
stored. H.264 is a very common video codec, and MP3 is
an audio codec. Confusingly, H.264 video is usually
stored in a .MP4 or .MOV file, but MP3 audio is often
stored in a .MP3 file. (Note that not all video in a .MP4
or .MOV file uses the H.264 codec).
Format: This refers to the internal structure of the
media data. For video, this includes frame size, frame
rate, and pixel aspect ratio. Features of audio formats
include the number of channels and configuration of
those channels (whether stereo, multiple-mono, 5.1
surround-sound, etc.).

Like most of the web world, in this book I’ll use “format”
in a more general sense. When I talk about files in the
MP4 format, I mean “video encoded using the H.264
codec and using MP4 as the file type.”
When you embed video or audio in your webpage, take
care to choose files in formats that the most common
browsers support. The best solution for video is usually to
choose MP4, because all browsers support it, with some
exceptions (TABLE 7.1).

Table 7.1 Video Formats


Format Supported Brow sers

MP4 A ll (In ter n et Ex plor er , Fir efox , Ch r om e, Sa fa r i,


* Oper a )

Web Ch r om e, Fir efox , Oper a


M

Og g Ch r om e, Fir efox , Oper a

*Except for H.265-encoded video

If you use MP4, be sure your video is encoded with


H.264. Quite a bit of video created on Apple iPhones
since 2017 uses the H.265 codec (or HEVC) which is
incompatible with some browsers. Y ou might also
consider either Ogg or WebM for performance or for
reasons of personal preference.
As with embedding video, when you embed audio in
your webpage you need to be mindful of the formats
that are supported. WAV is supported by all browsers
except Internet Explorer. The MP3 format is supported
by all browsers (TABLE 7.2).

Table 7.2 Audio Formats

Format Supported Brow sers

MP A ll (In ter n et Ex plor er , Edg e, Fir efox , Ch r om e,


3 Sa fa r i, Oper a )

W Ch r om e, Fir efox , Sa fa r i, Oper a , Edg e


AV

Og Ch r om e, Fir efox , Oper a


g
Y ou’ll notice that Ogg is both a video and audio format.

Tip
It’s possible WebM will overtake Ogg because it has big names (like Google)
behind it. There are also some clear performance benefits to using it.

EMBEDDING VIDEO
Y ou can embed a video on your webpage with the
<video> element. There are a few attributes to know as
well: width, height, and controls. The controls
attribute has no value, but adding it tells the browser to
include the play, pause, and volume buttons (FIGURE
7.11).

Figure 7.11 This webpage has an embedded video


with playback controls displayed.

Tip
Current browsers don’t natively support responsive (i.e., resizeable) videos
like they do with images, but there are a few third-party options you can try.
The best option at the time of this writing is the JavaScript library fitvids.js:
fitvidsjs.com/.

Between the opening and closing <video> tags, you


need to include the video source.
Luckily, you can add multiple video sources (which can
use different formats), and the browser will pick the best
one.
Y ou should always include an MP4, since that is
supported by all browsers.

To embed a video on a webpage:

Tip
If you need a free stock video for this task, check out
www.pexels.com/videos. Here, the file is named moon.mp4.

1. Ty pe <video.
2. Ty pe width="800px".
You ca n skip th e height a ttr ibu te sin ce th e br ow ser w ill
in tellig en tly r esize th e v ideo to th e a ppr opr ia te h eig h t ba sed
on th e w idth .
3. Ty pe controls>.
4. Ty pe <source src="moon.mp4".
5. Ty pe type="video/mp4">.
Th is is n ot com pletely n ecessa r y in m oder n br ow ser s, bu t it’s
still g ood to in clu de, especia lly if y ou u se m u ltiple sou r ces.
6. Ty pe </video>.

The final result is what you see in Figure 7.11.

VIDEO 7.9

Embedding a Video
In this v ideo, in addition to adding a v ideo to y our webpage, y ou’ll see how dif f erent
attributes af f ect the display.

VIDEO 7.10

Converting and Embedding Audio


In this v ideo, y ou’ll not only add an audio f ile to y our webpage, y ou’ll also see how to
conv ert an audio clip to the MP3 f ormat.

EMBEDDING AUDIO
Adding audio to a webpage is very similar to adding
video. The HTML is formatted exactly the same, except
you’ll use the <audio> tag instead of the <video> tag:
Click h er e to v iew code im a g e

<audio controls>
<source src="small-step.wav"
→type="audio/wav">
<source src="small-step.mp3"
→type="audio/mp3">
</audio>

Tip
Note that in this code sample I covered my bases by using both WAV and MP3
sources. If you don’t have an MP3 version of your audio, you can use a free
online converter like online-audio-converter.com/. Free programs like
Audacity (which is also cross-platform) can also do it for you. You can
download it from www.audacityteam.org.

To embed audio on a webpage:


1. Ty pe <audio.
2. Ty pe controls>.
3. Ty pe <source src="small-step.wav"
type="audio/wav">.
A s a r em in der , th is r ela tiv e pa th m ea n s th e WA V file is in
th e sa m e dir ector y a s th e HTML file.
4. Ty pe <source src="small-step.mp3"
type="audio/mp3">.
5. Ty pe </audio>.

The result will display a simple audio player in the page


(FIGURE 7.12).

Figure 7.12 This is the player for an embedded audio


clip.

Tip
If you need audio for this task, check out www.free-stock-music.com/. The
sample file here is from NASA and is named small-step.mp3.

STORING MULTIMEDIA FILES


Small files like images, SVGs, and PDFs can be stored
directly on your server, in the same folder as your
website. That’s because these files don’t require the user
to interact with them and therefore are not resource
intensive. In other words, they don’t require a lot of
computing power (as would playing a video game), so
they won’t cause stress on your website.
Multimedia—audio and video—will use considerable
resources and bandwidth that your web server is likely
not specialized for. This can lead to your website
crashing or quickly running out of storage and
bandwidth.

Instead, you should use specialized services to host your


media, and then embed links to those services into your
website using the embed code provided by the service.
Y ou can also get plain links (directly to an .mp3 or .mp4
file) and embed them using the audio or video
element.
For video, many great services are available. Both
Y ouTube (FIGURE 7.13) and Vimeo are free. If you
need more in terms of features or control, Vimeo also
offers paid plans (FIGURE 7.14).
Figure 7.13 Y ouTube provides a great service for
hosting free videos.

Figure 7.14 Vimeo offers hosting plans at a variety of


price points.

For hosting audio, things are a little tough. SoundCloud


is a popular free option, but it comes with limitations.
Podbean is a podcasting service that has a free tier, but
you’re probably better off paying for a service.
Libsyn is a great audio hosting service that starts at $5 a
month (FIGURE 7.15).

Figure 7.15 Libsyn offers a variety of audio hosting


plans.
Any of these services will save you time and bandwidth
(and probably a little strife too).

VIDEO 7.11

Using Libsyn to Host Audio


In this v ideo, y ou’ll get a quick look at using Libsy n f or audio hosting, and y ou’ll learn
how to embed a Libsy n f ile on a website.

Tip
A bonus of Libsyn (and most audio hosting services) is that you’ll get a
direct download link. This is a full URL that you can use with the <audio> tag
to embed the audio in your webpage. You’re not required to use Libsyn’s
embeddable player, like with some services.

To embed a YouTube video on your site:


1. Go to You Tu be.com a n d fin d a v ideo y ou ’d like to em bed.

2. Click th e Sh a r e bu tton ( ) to open th e Sh a r e


dia log (FIGURE 7.16).
3. Click Em bed. Th e Em bed V ideo dia log open s (FIGURE 7.17).
4. Copy th e code in th e top h a lf of th e dia log (it sta r ts w ith
<iframe a n d en ds w ith </iframe).
5. Open y ou r HTML file.
6. Pa ste th e em bed code y ou ju st copied in to th e HTML file a fter
th e open in g <body> ta g , a n d sa v e th e file (FIGURE 7.18).
7. Open th e HTML file in a w eb br ow ser .
You sh ou ld see y ou r You Tu be v ideo a ppea r on a w ebpa g e a s
sh ow n in FIGURE 7.19.
Figure 7.16 The Y ouTube share dialog

Figure 7.17 The Y ouTube Embed screen with embed


code

Figure 7.18 The Y ouTube embed code in an HTML


file

Figure 7.19 A Y ouTube video embedded on a


webpage
VIDEO 7.12

Embedding a YouTube Video


This v ideo will show y ou how to grab any public YouTube v ideo and embed it on y our
webpage.

WRAPPING UP
Phew! That was a lot to take in—but now you know how
to add all sorts of media to your website. This will make
it more visually appealing and interactive, and it will add
something beyond just text. After all, a picture’s worth a
thousand words, right?
8

Tables and Other Structured


Data Elements
In This Chapter

Tables
Description Lists

Why Is Structured Data Important?


Wrapping Up

The main goal of HTML is to structure, define, and


describe content. At this point you’ve seen most types of
data: paragraphs and headings, images and other media,
links, and layout elements. But there’s a whole world of
data out there that enhances websites by being described
properly.

In this chapter, you’ll learn about some of the more


advanced types of structured data, like tables and
definition lists. Y ou’ll also learn about schemas, a way
for you to describe your own data.

TABLES
Tables have been used on webpages as long as there
have been webpages. They are used to display “tabular”
data, which is data that is presented in rows and
columns (FIGURE 8.1).
Figure 8.1 A basic table in HTML

Tip
Before the adoption of CSS and more modern web standards, tables were
used for layout. This is considered very bad practice now. As you saw in
Chapter 6, there are a whole host of tags dedicated to creating semantic
layouts.

Table markup
Several elements go into making a table:

<table>: Th is is th e pa r en t elem en t. A ll th e da ta in th e
ta ble w ill be w r a pped in th e open in g a n d closin g table
ta g s.

<caption>: Specifies a title or ca ption for th e ta ble. If


in clu ded, th is sh ou ld be th e fir st ch ild elem en t of th e
ta ble.

<thead>: Th is sta n ds for “ ta ble h ea der ” a n d w ill con ta in


th e colu m n h ea din g s.

<tbody>: Sta n ds for “ ta ble body ” a n d con ta in s th e


pr im a r y con ten t (or da ta ) of th e ta ble.

<tr>: Sh or t for “ ta ble r ow .” Ea ch r ow of da ta g oes in


betw een open in g a n d close tr ta g s.

<td>: Th is is a cell of da ta (td sta n ds for “ ta ble da ta ” ).

<th>: If con ta in ed in side <thead>, th (ta ble h ea din g )


ca n r epla ce td a s th e ta ble cell. Da ta ta g g ed w ith <th>
w ill u su a lly a ppea r in bold by defa u lt.
<tfoot>: Th e “ ta ble footer ,” th is con ta in s th e ta ble’s
footer (ex a m ple in FIGURE 8.2).

Figure 8.2 This table shows the sum of the values in


each column at its bottom, so using <tfoot> for the
totals is appropriate.

The <span> Element


As y ou learn about more specif ic ty pes of elements, note that there’s one that is
used almost like a wildcard: the <span> element.

This is a generic inline element that has no inherent meaning, much like <div> at the
block lev el. It’s of ten used to apply classes or other helpf ul attributes to content, in
the ev ent that there is not a specif ic HTML element f or it.

CODE 8.1 The HTML markup behind the baseball table shown in FIGURE 8.3
Click h er e to v iew code im a g e

<table border="1">
<caption>Baseball players with their
→ teams and numbers.</caption>
<thead>
<tr>
<th>Player</th>
<th>Team</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>Derek Jeter</td>
<td>Yankees</td>
<td>2</td>
</tr>
<tr>
<td>David Ortiz</td>
<td>Red Sox</td>
<td>34</td>
</tr>
<tr>
<td>Roy Halladay</td>
<td>Phillies</td>
<td>34</td>
</tr>
<tr>
<td>Mike Piazza</td>
<td>Mets</td>
<td>31</td>
</tr>
</tbody>
</table>

Figure 8.3 A table of baseball players, their teams,


and their numbers

Sample table markup


CODE 8.1 shows the markup for a simple table that lists
baseball players, the teams they were on when they
retired, and their uniform numbers.

A quick note on this code: the border attribute is


actually deprecated in HTML5. Y ou should use CSS to
define borders. It’s used here only so you can see the
different cells in the table.
Let’s take it one section at a time, beginning with the
header. Adding this header will make three columns
with bold text, denoting column headings (FIGURE
8.4).

Figure 8.4 The header for the baseball players table


as it will appear when rendered in a browser

A table header and a table row will look very similar in


markup, but both should be included. We’ll walk
through both so you can see how a table is built. The
main difference is that th cells will appear in bold.

Tip
You can use CSS to move the caption to the bottom of the table.

To create the table header:


1. Ty pe <table border="1">.
Th e border a ttr ibu te h er e w ou ld n or m a lly be ex clu ded in
fa v or of a ddin g it v ia CSS, bu t it w ill m a ke r ea din g th e ta ble
m u ch ea sier for th e pu r poses of th is ex a m ple. Th e 1 m ea n s “ 1
pix el” a n d it w ill cr ea te a bor der a r ou n d th e en tir e ta ble a n d
a r ou n d ea ch cell a n d h ea der .
2. Ty pe <thead> to beg in th e h ea der .
3. Ty pe <tr> to sta r t th e r ow w ith in th e h ea der .
4. Ty pe <th>Player</th> to en ter th e fir st of th e th r ee colu m n
h ea ds.
5. Ty pe <th>Team</th>.
6. Ty pe <th>Number</th>.
7. Ty pe </tr> to close off th e r ow of colu m n h ea ds.
8. Ty pe </thead> to m a r k th e en d of th e h ea der .

To create a table row:


1. Ty pe <tbody>.
2. Ty pe <tr>.
3. Ty pe <td>Derek Jeter</td>.
4. Ty pe <td>Yankees</td>.
5. Ty pe <td>2</td>.
6. Ty pe </tbody>.
7. Ty pe </table>.

Tip
To avoid repetition, I’ve shown you how to code only the first row of the
table. Repeat these steps (changing the data in the cells each time) to add as
many rows as you’d like!

VIDEO 8.1

Building a Table
In this v ideo, y ou will see in real time what happens as I build a table in CodePen.

CODE 8.2 The full code for the table, with important areas highlighted
Click h er e to v iew code im a g e

<table border="1">
<thead>
<th colspan="4">Aaron Judge</th>
<th>RF</th>
</thead>
<tbody>
<tr role="header">
<td>Year</td>
<td>Team</td>
<td>BA</td>
<td>HR</td>
<td>RBI</td>
</tr>
<tr>
<td>2017</td>
<td rowspan="3">NYY</td>
<td>.284</td>
<td>52</td>
<td>114</td>
</tr>
<tr>
<td>2018</td>
<td>.278</td>
<td>27</td>
<td>67</td>
</tr>
<tr>
<td>2019</td>
<td>.272</td>
<td>27</td>
<td>55</td>
</tr>
<tfoot>
<tr>
<td colspan="2">Totals:
</td>
<td>.278</td>
<td>106</td>
<td>236</td>
</tr>
</tfoot>
</table>

Extending rows and columns


Y ou aren’t limited to strictly structured rows and
columns. Thanks to the attributes colspan and
rowspan, which accept a numeric value for the number
of cells the column or row should span (or take up), you
can tell the table “this cell should take up two columns”
or “this cell should take up three rows”:

<th colspan="2">
<th rowspan="3">

These attributes come in handy when you want to build


a more complicated table—one that mimics a baseball
card, for example (FIGURE 8.5 and CODE 8.2).

Figure 8.5 A complex, baseball card–like table for


Aaron Judge (batting average, home runs, and runs
batted in). However, the table header has the player’s
name spanning four columns. The Totals cell in the
footer spans two columns. And since he’s played for
the same team for his entire career, the first Team
entry takes up three rows.

Doing this takes a little bit of math to get right, but it can
make your tables look better and help you align data just
the way you want to.
Miscalculating the rowspan can make a trainwreck of
your table (FIGURE 8.6). Since the table is expecting
another cell to fill the 2019 row, the cells no longer line
up and there’s a random blank space.

Figure 8.6 What happens when a rowspan is short


by one row

Similar problems arise when a column spans one too


many cells (FIGURE 8.7). In this instance, the browser
creates an entirely new column with a single cell to
account for the overflow.
Figure 8.7 What happens when a colspan spans
one column too many

To add colspan to a table header:

1. Ty pe <thead>.
2. Ty pe <tr>.
3. Ty pe <th bu t don ’t a dd th e closin g >.
4. Ty pe colspan="4">.
Sin ce th e h ea d h a s tw o colu m n s bu t it’s a fiv e-colu m n ta ble,
th is colspan sh ou ld be 4—on e for th e cell a n d th r ee for th e
cells th a t a r e skipped.
5. Ty pe Aaron Judge.
6. Ty pe <th>RF</th>.
7. Ty pe </tr>.
8. Ty pe </thead>.

The result is the heading you see in Figure 8.5.

VIDEO 8.2

Experimenting with colspan and rowspan


In this v ideo y ou will start with a basic table and incorporate rowspan and colspan
into the code to see how the table changes in real time.
Figure 8.8 A description list of baseball terms and
their definitions

CODE 8.3 The markup that creates the description list in Figure 8.8
Click h er e to v iew code im a g e

<dl>
<dt>Batting Average (BA):</dt>
<dd>The total number of hits divided
→ by the number of at-bats.</dd>

<dt>Home Run (HR):</dt>


<dd>A fair hit that allows the batter
→ to round all of the bases and cross
→ home.</dd>

<dt>Runs Batted In (RBI):</dt>


<dd>Any run credited to a specific
→ batter that results from a fair hit
→ ball or base on balls.</dd>
</dl>

DESCRIPTION LISTS
A description list is a fantastic example of structured,
defined data. It’s an element that contains a list of terms
and descriptions (or definitions) for those terms. A
glossary is a perfect example (FIGURE 8.8).

Tip
Prior to HTML5, description lists were called definition lists.

The markup for a description list includes three tags:

<dl>: Th is is th e con ta in er for th e en tir e list. dl sta n ds


for “ descr iption list.”
<dt>: Th e dt (descr iption ter m ) is th e ter m bein g
descr ibed.

<dd>: Th is is th e “ descr iption deta ils.” It’s th e tex t th a t


descr ibes th e ter m .

CODE 8.3 shows you the code for the description list in
Figure 8.8.
Description lists aren’t limited to definition/term lists.
Y ou can also use them for recipes, upcoming events, or
dialogue (like in a script).

Semantically, a <dd> will be associated with the


preceding <dt>. That means that you can have multiple
<dd> elements following a single <dt>, and vice versa.
If you have two <dt>s in a row, the very next <dd> will
be associated with both of them.

To create an events list using a description list:


1. Ty pe <dl> to sta r t th e list.
2. Ty pe <dt>Opening Day</dt> to en ter th e fir st ter m to be
descr ibed.
3. Ty pe <dd>April 1, 2021</dd> to en ter th e descr iption for
th e ter m y ou ju st a dded.
4. Ty pe <dt>All-Star Game</dt> to a dd a n ew ter m to th e
list.
5. Ty pe <dd>July 13, 2021</dd>.
6. Ty pe <dd>Game held at Truist Park, home of the
Atlanta Braves</dd> to a dd a secon d lin e of in for m a tion
a bou t th e ter m .
7. Ty pe <dt>Postseason</dt>.
8. Ty pe <dd>October 2021</dd>.
9. Ty pe <dd>Rounds: Wild Card, Division Series,
League Championship, World Series</dd>.
10. Ty pe <dd> The winners in each league will play in
the World Series. </dd>.
11. Ty pe </dl> to close th e descr iption list.

The resulting list is shown in FIGURE 8.9.


Figure 8.9 A description list of upcoming events in
Major League Baseball

This example shows that, by default, every <dd> is


indented under the most recent <dt>, creating a nice
visual hierarchy of terms and descriptions.

Tip
You can even use other HTML elements, like <p> or <ul>, inside description
lists!

VIDEO 8.3

Writing a Script with a Description List


Ev en though description lists are not of ten used, they hav e many applications that
can be creativ e as well as practical. This v ideo will show y ou how to use one to write
dialogue in a TV script.

On Indenting Your Code


HTML does not require that code use any particular sty le of indentation. I add indents
manually in my code. Some HTML editing sof tware will add them f or y ou.
Through the book, y ou’ll notice the use of indentation f or each child element, like so:

<parent>
<child>
<grandchild>

This makes the code easier to f ollow, and y ou can quickly locate opening and closing
tags.

WHY IS STRUCTURED DATA


IMPORTANT?
Y ou might be wondering why we need to use specific
structures for different kinds of data. After all, we could
easily use an unordered list for description lists.
But using the right tags to define data is important for
browsers, users, and search engines. A great example of
defining data in HTML is the <address> tag:

<address>
Yankee Stadium<br/>
1 E 161 St.<br/>
The Bronx, NY 10451
</address>

… which renders as FIGURE 8.10.

Figure 8.10 The <address> tag in action

Aside from it being italicized, there’s not much visually


different about an address. Y ou could easily use a <p> or
<div>. But the <address> tag tells the browser and
search engines, “This is the contact information for this
page.” Even better, if the <address> tag is nested in an
<article> tag, it indicates contact information
specifically for that article.

What this ultimately leads to is better, more informative


search results for users. Here’s what happens if you
search online for “Y ankee Stadium address” (FIGURE
8.11).
Figure 8.11 The answer shows up directly on the
search results page.

Without semantic meaning applied to the text (in this


case, as an <address> tag), Google would have a much
harder time knowing which data on the page contained
the correct answer.

Using Schema.org vocabulary for custom


structured data
This is a bit beyond the scope of “basic HTML and CSS,”
but it’s important to know in the context of this
conversation.
There are a number of different ways of annotating your
structured content. By annotating your data, you help
search engines better understand your page content and
enable them to display your site with interesting search
appearance elements. While there are several types of
specifications, Schema.org is the commonly used type
we’ll use in this book. These sets of markup are called
schemas. Driven primarily by Schema.org, these
schemas provide a vocabulary that search engines can
potentially use to better understand what you’re
presenting.

Tip

Yoast, a company that specializes in search engine optimization (SEO), has a


fantastic write-up on schema: yoast.com/structured-data-schema-ultimate-
guide/.

Common examples of schemas drive search engine


results that you regularly see: information on movies
and TV shows, recipes, and so on (FIGURES 8.12 and
8.13).

Figure 8.12 Google uses movie schema from several


different sites (IMDB, Wikipedia, and Y ouTube, to
name a few) to build a special display for movies to
show up in searches.

Figure 8.13 Recipes show up in a card format on


Google, allowing users to see what looks best to them
and then click through to the recipe.
If you wanted to, you could create a more meaningful
event list. The main driver is an attribute called
itemscope, which states that the element is about a
specific item. Then we’d use the attribute itemtype to
get the right schema from Schema.org to go with it. We
can add more information to an element with
itemprop, which allows you to set item properties
based on the type of data represented (e.g., events will
have a date; recipes will not).

Tip
Two hugely helpful resources are schema.org/docs/gs.html, for getting
started, and schema.org/docs/full.html, which lists all the types of data.

VIDEO 8.4

Walking through Schema Examples


In this v ideo, y ou’ll get a closer look at dif f erent ty pes of schemas and how they
af f ect search results.

To create an event with Schema.org vocabulary:


This task uses the following markup for an event that,
alas, never took place:
Click h er e to v iew code im a g e

<dt>Field of Dreams Game</dt>


<dd>August 13, 2020</dd>
<dd>Game held in Dyersville,
→Iowa</dd>
<dd>Yankees vs. White Sox</dd>

1. A fter <dt, ty pe itemscope.


2. Ty pe itemtype={"https://schema.org/SportsEvent">.
3. A fter th e fir st <dd ta g (th e on e con ta in in g th e da te), ty pe
itemprop="startDate" content="2020-08-13T19:00">.
Th is is a m a ch in e-r ea da ble v er sion of th e da te a n d tim e.
4. Repla ce Dyersville, Iowa w ith <span
itemprop="location">Dyersville, Iowa</span>.
5. Repla ce Yankees w ith <span
itemprop="awayTeam">Yankees</span>.
6. Repla ce White Sox w ith <span
itemprop="homeTeam">White Sox </span>.

The resulting markup is shown in CODE 8.4.


CODE 8.4 Our miniature baseball database, now with Schema.org vocabulary
added
Click h er e to v iew code im a g e

<dt itemscope
itemtype="https://schema.org/SportsEvent">Field
of Dreams Game</dt>
<dd itemprop="startDate"
content="2020-08-13T19:00">August 13,
2020</dd>
<dd>Game held in <span
itemprop="location">Dyersville,
Iowa</span></dd>
<dd><span
itemprop="awayTeam">Yankees</span> vs.
<span itemprop="homeTeam">White Sox
→ </span></dd>

While this doesn’t affect the display of your webpage, it


gives search engines much more valuable information.
Y ou can imagine someone searching “Who is the home
team for the Field of Dreams game?” Now search
engines can find the answer in our tiny database.

WRAPPING UP
Y ou covered a lot of ground in this chapter, learning
about important structures like tables and description
lists. Y ou also have a better understanding of structured
data and its importance in creating a better, more user-
friendly web.
9

Web Forms
In This Chapter

Interacting with Webpages


How a Web Form Works

Components of an HTML Form


The <form> Element

Form Fields
Labeling Fields

Setting Up a Basic Form


Creating Select Boxes

Creating Radio Buttons


Creating Checkboxes

Creating Email Forms


Special Field Types

The <meter> Element

Validating Forms

Wrapping Up

So far, everything you’ve learned about webpages and


HTML has taught you how to build a one-way street.
That is, you can post information to a webpage, but the
website visitors have no way of interacting with you.
That’s where web forms come in.

Web forms are the primary way users interact with


websites. From contact forms to Google’s search box,
forms drive engagement and make the web a more
interactive place.

INTERACTING WITH WEBPAGES


Forms allow users to submit information to your
website. Y ou then have the option to store the data or
otherwise do something with it. Some examples of
popular web forms:

Con ta ct for m s

Com m en ts

For u m s

Log in box es

Post box es (on socia l m edia w ebsites)

Sea r ch box es

Ch eckou t pa g es, A dd To Ca r t bu tton s, a n d pa y m en t


su bm ission s for on lin e stor es

Ch a tbots

Popu p opt-in box es

Y ou’ve no doubt seen lots of forms (FIGURES 9.1, 9.2,


and 9.3).

Figure 9.1 Google’s iconic minimalist home page,


with only a search box
Figure 9.2 Checkout form on an ecommerce site

Figure 9.3 Twitter’s login page

VIDEO 9.1

Interacting with Forms


There are lots of dif f erent f orms y ou can build, as well as many dif f erent way s users
can interact with those f orms. In this v ideo y ou’ll see some unique web f orms and
learn how they work.

HOW A WEB FORM WORKS


There are several steps to building and processing a web
form (FIGURE 9.4):

Figure 9.4 The flow of the data that is entered into a


web form

1. Bu ild th e for m u sin g HTML.


2. V a lida te th e for m to m a ke su r e a ll da ta is su bm itted
pr oper ly .
3. Su bm it a n d pr ocess th e for m .
Pr ocessin g ca n h a ppen in sev er a l w a y s. You cou ld sim ply
em a il th e con ten ts of th e for m som ew h er e, y ou cou ld stor e it
in a da ta ba se, y ou cou ld u se it to ch a n g e y ou r site in r ea l
tim e, a n d m u ch m or e.
4. Displa y con fir m a tion to th e u ser .

Keep this in mind as you read this chapter, though:


you’re learning how to build the form in HTML, and
you’re using HTML elements to perform basic validation
of the input data.
But with regard to submitting the data, you can’t do as
much with just HTML. Submission often requires the
use of another programming language, which goes
beyond the scope of this book. That said, you will learn
basic form processing to email the form contents. In
Chapter 10, you’ll even learn a simple technique for
storing the data.

COMPONENTS OF AN HTML FORM


Every form is wrapped in a <form> element, which
consists of the opening <form> tag and the closing
</form> tag.

The bulk of the form itself is made up of fields that can


accept data from users. Most of these elements are
created with <input> tags, though there are others
you’ll also learn about.

Tip
Webpages can include more than one form, so placing fields inside the
opening and closing form tags signals to a browser that all the fields belong
to the same form.

THE < F O R M > ELEMENT


Every form needs an opening <form> tag and a closing
</form> tag, which together define a form element.
The form element requires an action attribute, and it
should have method and name attributes as well:
Click h er e to v iew code im a g e

<form name="search-form"
→ method="GET" action="process.php">

The name attribute is a simple way to uniquely identify


the form (each form should have a unique name).
Webpages can contain more than one form, and the
name attribute allows you to easily reference the form in
both CSS and JavaScript.
The method attribute determines how the form data
should be sent, and can take one of two values.

GET is the default value. This method transmits data


from one page to another in a URL as name-value pairs
(FIGURE 9.5).

Figure 9.5 Using the GET method, you can see the
results of a form in the URL.

Attributes are a good example of name-value pairs. They


have a name (like the role attribute) and a value (like
“main”). In a URL, name-value pairs appear in this
format: role=main.

When a user fills out your form and clicks Submit, the
browser takes all the data from the form and then inserts
it into the URL. In the above example, the URL would
look something like this: process.php?
name_of_field=value_the_user_input.

The other method value is POST. In this method, data is


transmitted in the HTTP request and is not shown in the
URL. The data is sent, in this instance, to process.php
via the server.

VIDEO 9.2

Comparing the GET and POST Form Submission Methods


To get a better idea of how each action behav es, here y ou’ll see what happens with a
GET method compared to a POST method.

The action attribute tells the browser where to send the


form information. It’s what does the form processing,
whether that’s emailing its contents or storing it in a
database. If you do not include the action attribute,
modern browsers will assume the current page will also
process the form.

Tip
Forms are often processed using a server-side language like PHP, Python, or
C#. While that’s outside the scope of this book, you can download the
process.php file from the Github repo (short for repository, or a place where
we can store our code for others to download) for this book (see “Code" in
the Introduction).

Tip
Privacy and data storage laws are becoming stricter around the world.
Depending on where you live, you may need to alert the user to how you’re
using the data or ask them to explicitly give your website permission to let
you store it.

Deciding Between GET and POST


Both GET and POST hav e pros and cons. With GET, the data entered by the user is
v isible in the URL, so y ou should never use it to pass sensitiv e data, like passwords.
But using GET (and theref ore allowing f orm data to be v isible) is great if y ou want to
make the results shareable or if y ou want to let the user sav e them. An example that
uses GET is Google search results.
On the other hand, the length of a GET request is limited, ranging f rom 2000 to 8000
characters, depending on the serv er and browser conf igurations.
There is no limit on results when using POST, and it’s more secure, but the results
pages cannot be shared, nor can the results of a specif ic f orm submission be sav ed.

FORM FIELDS
There are several form fields that you can define in
HTML, and each allows the user to interact with the
form in a different way.

Input fields
The most common tag you’ll find between the opening
and closing <form> tags is <input>. This element
creates a field into which users can insert data. It looks
something like this:
Click h er e to v iew code im a g e
<input type="text" name="search"
→ value="" />

Let’s take each attribute one by one.

The type attribute determines the kind of data a user


can input. While text is the most common (and the
default when the type attribute is not defined), there are
lots of values the type attribute can have. Y ou’ll see
most of them throughout this chapter.

Tip
For a complete (and regularly updated) list, check out
developer.mozilla.org/en-US/docs/Web/HTML/Element/input.

The name attribute assigns a name to the input field.


Remember those name-value pairs from earlier? The
name is derived from the name attribute. It should be
unique to prevent overriding data.

The value part of the name-value pairs is derived from


the value attribute. Notice that the value attribute in
the above example is blank. Y ou can add one, but
whatever the user inputs will overwrite it (FIGURE
9.6).

Figure 9.6 A text field with the value attribute

With some form fields—namely, those that take on the


appearance of a textbox (a single-line white field with
gray border, which accepts a limited amount of text)—
there is another attribute. Instead of setting the value
attribute, you can use the placeholder attribute. This
adds grayed-out text to the field, to suggest the type text
that can go in the field.
If the user does not fill out the field, it will have no value
(FIGURE 9.7).

Figure 9.7 A field with the placeholder attribute

Each form should also have a submit field, which has


its own input type. When the browser sees this input
type, it will generate a button for the user to click, in
order to send the form’s data using the method and
action you defined in the opening <form> tag.

Although you can set the value of a submit input type, it


is immutable outside of markup, so the user cannot
change it.

Putting it all together, you get this:


Click h er e to v iew code im a g e

<form name="search-form" method="GET"


→ action="process.php">
<input type="text"
→name="search-term" />
<input type="submit" name="submit"
→value="Search" />
</form>

… which looks like FIGURE 9.8 in the browser.

Figure 9.8 A simple search form

Tip
You can use type="search" for input on search forms as well, and a submit
button will automatically be included.
If a user were to enter Atlantis into the search form, the
URL would look like this:
Click h er e to v iew code im a g e

yoursite.com/process.php?search-term=
→ Atlantis

Input types
Text and submit are not the only types of input available.
Y ou can submit data using a variety of formats
(FIGURE 9.9, CODE 9.1):

Figure 9.9 What each input type looks like

text: A sin g le lin e of tex t.

password: A field desig n ed for u ser s to a dd pa ssw or ds or


oth er sen sitiv e tex t. Th is field obfu sca tes in pu t, u sin g
dots to h ide its con ten ts.
radio: A bu tton (ty pica lly cir cu la r ) u su a lly cr ea ted in
g r ou ps. On ly on e of th e bu tton s in a g r ou p ca n be
selected a t a tim e, w h ich m a kes r a dio bu tton s th e idea l
w a y to offer y ou r u ser a r a n g e of option s fr om w h ich
th ey m u st ch oose on e.
Use th e checked a ttr ibu te to select a defa u lt v a lu e.

checkbox: A set of squ a r e box es th a t pr esen t th e u ser


w ith sev er a l option s. On e or m or e ca n be selected.
Use th e checked a ttr ibu te to select a defa u lt v a lu e.

email: Th is in pu t ty pe tells th e br ow ser to m a ke su r e


th e u ser h a s en ter ed a pr oper ly for m a tted em a il a ddr ess.

file: A tex t field w ith a Ch oose File bu tton . Clickin g th e


bu tton open s a file n a v ig a tion dia log box th e u ser ca n
u se to fin d a n d select a file on th eir com pu ter for u ploa d
to a ser v er .

submit: A bu tton th a t, w h en clicked, sen ds th e for m for


pr ocessin g .

image: Wor ks ju st like th e su bm it bu tton , bu t y ou ca n


u se a n im a g e y ou pr ov ide in stea d of th e sta n da r d
br ow ser -r en der ed su bm it bu tton .
Du e to a dv a n cem en ts in CSS, y ou see th is u sed a lot less
th a n it on ce w a s.

hidden: Cr ea tes a for m field th a t ca n n ot be seen or


edited by u ser s. Th is is often u sed to ca ptu r e
dy n a m ica lly g en er a ted con ten t, like a tim esta m p or ID.
For ex a m ple, on a blog post, a com m en t for m w ou ld
h a v e a h idden field w ith th e ID of th e post so th a t th e
blog pu blish er kn ow s w h ich post th e com m en t belon g s
to.

There are also a few fields that act like text fields but
require specific kinds of text. They are email, date,
search, tel, and url. Y ou will learn more about them
in the “Validating Forms” section of this chapter.
CODE 9.1 The HTML code used to generate the inputs in Figure 9.9
Click h er e to v iew code im a g e

<form name="input-reference" method="get"


action="process.php">
<input type="text" name="text" value="This
is text"/>
<textarea name="textarea">This is a
textarea</textarea>
<input type="password" name="password"
value="This is password"/>

<p>Radio Buttons:</p>
<input type="radio" name="radio-option"
value="1st option" />1st option
<input type="radio" name="radio-option"
value="2nd option" checked />2nd option
<input type="radio" name="radio-option"
value="3rd option" />3rd option

<p>Checkboxes:</p>
<input type="checkbox" name="check-
option1" value="Atlantis" /> 1st option
<input type="checkbox" name="check-
option2" value="Snow White" /> 2nd option
<input type="checkbox" name="check-
option3" value="Aladdin" /> 3rd option

<select name="select">
<option>This is a Select
Box</option>
<option value="1st
option">1st option</option>
<option value="2nd
option">2nd option</option>
<option value="3rd
option">3rd option</option>
</select>

<p>File Upload:</p>
<input type="file" name="file"
/>

<input type="submit"
name="submit" value="Submit" />

<input type="image"
name="image-submit" src="submit-img.png"
alt="Submit" />
</form>

Other field types


Aside from the <input> tag, there are two other field
elements worth mentioning.
A <textarea> field allows users to enter a block or
paragraph of text; it also uses a closing </textarea>
tag. The default text of this field goes in between the
opening and closing tags. See Code 9.1 for an example.

The <select> element creates a dropdown menu, or


list of options. By default, only one option in the list can
be selected. Y ou can allow the reader to select more than
one option by including the multiselect attribute.
To populate a <select> field, you’ll need to include the
<option> element between the opening and closing
<select> tags. In this instance, <select> should
include the name attribute, but each <option> tag
should have its own value attribute.

See Code 9.1 for an example. Y ou’ll create your own


select box in an upcoming task!

Tip
You can also use the select="selected" attribute on any <option> element to
set that as the default option. By default, it will be the first option listed.

Why Use Hidden Fields?


You might be wondering why someone would use a hidden f ield on their f orm if a user
can’t see it. There are sev eral possible reasons, but the main use case is gathering
extra inf ormation about the user’s v isit, like the time of day, the URL they were
v isiting, or the user’s IP address.

A hidden f ield can also be used to def end against spam. If the f ield is f illed out,
there’s a good chance a spambot did it, not a person. You can then throw out those
submissions.

LABELING FIELDS
Although the placeholder attribute does a reasonable
job of communicating the kind of information the user
should enter into many form fields, there’s a better, more
semantic way: use a <label> element with your
<input> elements.
Click h er e to v iew code im a g e

<div>
<label for="first_name">First
→ Name:</label>
<input type="text"
→ name="first_name"
→ id="first_name" placeholder=
→ "Milo" />
</div>

In the browser, this code is rendered as a text box labeled


with the kind of data the user is expected to enter
(FIGURE 9.10).
Figure 9.10 A form field with label

Y ou’ll notice that the label has a for attribute. That


attribute matches the id attribute on the input element.
This tells the browser, “This label belongs to the
<input> element whose ID matches the for attribute.”

Aside from improving user experience, labeling your


input fields provides accessibility benefits:

If a v isitor to y ou r site is u sin g a scr een r ea der , it ca n


r ea d th e tex t of th e la bel ou t lou d w h en th e in pu t
elem en t h a s u ser focu s (for ex a m ple, w h en th e u ser ta ps
it or clicks it w ith a m ou se).

Beca u se clickin g th e la bel a ctiv a tes th e for m field, th e


ov er a ll “ h it a r ea ” for th e for m elem en t is in cr ea sed. Th is
ca n m a ke it ea sier for u ser s w ith decr ea sed m obility to
a ctiv a te th e in pu t fields.

SETTING UP A BASIC FORM


Before moving on and creating examples of form inputs,
you’ll write a simple form skeleton, to which you can
add the example inputs you create in the rest of the
tasks.

Tip
Even when labels are applied to inputs throughout a webpage, it’s common
to omit them for submit buttons.

To create a form skeleton:


1. Ty pe <form name="example-form".
2. Ty pe method="GET">.
3. Lea v e a bla n k lin e betw een th e pr ev iou s lin e a n d th e n ex t
lin e.
4. On th e n ex t lin e, ty pe <input type="submit"
name="submit" value="Submit" />.
5. On th e n ex t lin e, ty pe </form>.

Y ou should now have this:


Click h er e to v iew code im a g e

<form name="example-form"
→ method="GET">

<input type="submit" name="submit"


→value="Submit" />
</form>

CREATING SELECT BOXES


Select boxes are an intuitive way to allow your users to
pick from a list of items. There are two ways a select box
can work: as a simple dropdown menu, which allows
only one option to be selected, or as a multiselect box,
where several items can be selected. The following tasks
will show you how to build both. Using the form
skeleton you created in the previous task, insert the code
you will build in the following task right after the
opening <form> tag.

To create a select box:


1. Fir st, cr ea te th e la bel for th e select box . Be su r e to in clu de th e
for a ttr ibu te w ith th e ID for th e la bel. For th is ex a m ple, ty pe
<label for="next-movie">What movie do you want to
see next?</label>.
2. Ty pe th e open in g ta g for th e select box : <select.
3. Giv e th e box a n a m e a n d a ssig n its ID by ty pin g
name="next-movie" id="next-movie">.
Nex t, defin e th e <option> elem en ts th a t w ill be listed on th e
m en u . Th is ex a m ple u ses m ov ie titles.
4. Ty pe <option value="Toy Story 4"> Toy Story
4</option>.
5. Ty pe <option value="Onward">Onward </option>.
6. Ty pe <option value="Fast 9">Fast 9 </option>.
7. Ty pe </select>.

This creates a box that lists three options, from which


the user can pick one (FIGURE 9.11).
Figure 9.11 A select box with all options showing

VIDEO 9.3

Converting a Select Box to a Multiselect Box


In this v ideo, y ou’ll see what happens when y ou conv ert a select box into a
multiselect box, and how each f ield works.

To create a multiselect box:


1. Ty pe <label for="seen-movies">What movies have you
seen?</label>.
2. Ty pe <select name="seen-movies" id="seen-movies".
3. Ty pe multiple> a n d pr ess Retu r n /En ter .
Ea ch of th e follow in g option elem en ts belon g s on its ow n
lin e.
4. Ty pe <option value="Atlantis"> Atlantis</option>.
5. Ty pe <option value="Snow White">Snow
White</option>.
6. Ty pe <option value="Aladdin"> Aladdin</option>.
7. Ty pe </select>.

This creates a box that lists three options. The user can
hold the Shift key while clicking to select more than one
contiguous option, or they can hold Command
(macOS)/Ctrl (Windows) to select multiple
noncontiguous options (FIGURE 9.12).
Figure 9.12 A multiselect box with two options
selected

CREATING RADIO BUTTONS


Radio buttons are another way to present a user with
options and have them pick one (the select box is the
first way). Once a radio button is selected, it cannot be
deselected without selecting another radio button.

Using the form skeleton you created in a previous task,


place the following code from the task right after the
opening <form> tag.

To create radio buttons:


1. If y ou w a n t to pr ov ide a title or oth er in tr odu ctor y tex t for
y ou r bu tton s, in clu de it in a pa r a g r a ph elem en t. For th is
ex a m ple, ty pe <p>What is your favorite movie?</p>.
2. Ty pe <input type="radio" name= "favorite-movie"
id="atlantis" value="Atlantis" /> <label
for="atlantis">Atlantis</label>.
3. Ty pe <input type="radio" name= "favorite-movie"
id="snow-white" value="Snow White" /> <label
for="snow-white">Snow White </label>.
4. Ty pe <input type="radio" name= "favorite-movie"
id="aladdin" value="Aladdin" checked /> <label
for="aladdin">Aladdin</label> (FIGURE 9.13).

Figure 9.13 A set of radio buttons with the default


option selected

Note the checked attribute on this input.

Notice the value of the name attribute of all three


buttons is the same. That’s to tell the browser, “These
buttons belong together.”

CREATING CHECKBOXES
Checkboxes are a great way to present the user with
multiple options and allow them to accept more than
one. Unlike radio buttons, where the user can only
choose one, there is generally no limit on the number of
checkboxes a user can select.
Using the form skeleton you created in a previous task,
place the following code from the task right after the
opening <form> tag.

To create checkboxes:
1. Ty pe th e in tr odu ctor y tex t, if a n y ; in th is ca se, u se <p>What
movies do you want to see?</p>.
2. Ty pe <input type="checkbox" name="want-to-see-1"
id="atlantis" value="Atlantis" checked/> <label
for="atlantis">Atlantis</label>.
Note th e ch ecked a ttr ibu te.
3. Ty pe <input type="checkbox" name= "want-to-see-2"
id="snow-white" value="Snow White" /> <label
for="snow-white">Snow White </label>.
4. Ty pe <input type="checkbox" name="want-to-see-3"
id="aladdin" value="Aladdin" /> <label
for="aladdin">Aladdin</label> (FIGURE 9.14).

Figure 9.14 A set of checkboxes

Notice that the names of these checkboxes have a


number appended. If they were named the same, they
would all effectively represent one option because as we
learned earlier, the name attribute of each form field on
a page must be unique. This rule does not apply to radio
buttons, of course.

Tip

It’s possible to use advanced programming languages like PHP to name a


group of checkboxes the same and still keep them as a group, but that’s
beyond the scope of this book.
VIDEO 9.4

Creating Checkboxes and Radio Buttons


Checkboxes and radio buttons act a little dif f erently f rom other input ty pes. In this
v ideo y ou’ll learn how to write them, see what their dif f erences are, and learn when to
use each.

CREATING EMAIL FORMS


Email forms are super common online, as are inputs to
capture email in general. That’s why the email input
type exists. It will self-validate to make sure the user is
entering an email address that’s in the proper format
(but it won’t know whether the email address actually
exists).

To create a simple email opt-in form:


1. Ty pe th e open in g ta g for th e form elem en t, m a kin g su r e to
in clu de th e name or id, method, a n d action a ttr ibu tes. For
th is ex a m ple, u se <form name="optin" method="GET"
action="process.php">.
Ou r ex a m ple for m in clu des tw o <input> elem en ts, ea ch w ith
a label: a text in pu t for th e u ser ’s fir st n a m e, a n d th e
email in pu t.
2. Cr ea te th e la bel for th e u ser ’s n a m e: <label for="first-
name">First Name:</label>.
3. Ty pe <input type="text" name="first_name"
id="first-name" placeholder="First Name" />.
4. Ty pe <label for="email-address"> Email Address:
</label>.
5. Ty pe <input type="email" name="email_address"
id="email-address" placeholder="Email Address" />.
6. Ty pe <input type="submit" name="submit"
value="Join the List!" />.
7. Ty pe </form> (FIGURE 9.15).

Figure 9.15 A simple email opt-in form


SPECIAL FIELD TYPES
There is a set of input types that add special controls and
selectors. They offer a better way for users to insert
properly formatted data. This reduces the need to take
separate measures to validate and makes the input more
reliable.

Tip
You can view a more comprehensive list of these special inputs at
www.w3schools.com/html/html_form_input_types.asp.

Date
The date input type (FIGURE 9.16) brings up a
calendar for users to pick a date from (FIGURE 9.17).
The browser display (what you see in the box) depends
on the user’s locale (where they are located, based on
what the browser knows). The date is always sent in the
format YYYY-MM-DD.

Figure 9.16 The date field, with a locale of “en-US”


for English, United States
Figure 9.17 The date picker, as implemented by
Google Chrome

<input type="date"
→ name="release-date" />

Y ou can constrain a user’s selection to a specific range of


dates by using the min and max attributes:
Click h er e to v iew code im a g e

<input type="date" name="release"


→ min="1937-12-21" max="1992-11-11" />

Note that the min and max attributes affect the date
picker, but a user will be able to manually set any date,
even if it’s outside the range. This is a good use case for
validation with JavaScript.

VIDEO 9.5

Building a Rental Application


To get y ou more f amiliar with the v arious input ty pes, in this v ideo y ou’ll build a small
application f or someone who’s looking to rent an apartment.
VIDEO 9.6

Working with Dates on Forms


In this v ideo y ou’ll see the date f ield in action on f orms, as well as how the dates are
f ormatted once a user submits the f orm.

VIDEO 9.7

Picking Colors
In this v ideo y ou’ll see how the color picker works in Chrome and what kind of data is
passed f or processing.

Finally, there are a few other date- and time- related


inputs:

datetime-local: Th is a llow s th e u ser to select a da te


a n d tim e w ith ou t in clu din g th e tim e zon e. Th a t m ea n s
th a t ev en if y ou ’r e in New Yor k a n d y ou r u ser is in
Lon don , y ou ’ll both see th e sa m e da te a n d tim e in pu ts.

time: A llow s th e u ser to select a tim e w ith n o tim e zon e


in clu ded.

month: A llow s th e u ser to select a m on th a n d y ea r .

week: A llow th e u ser to select a w eek n u m ber a n d y ea r .

Tip
At the time of this writing, month and week have only partial browser
support, but they are supported by all major browsers. They are displayed as
text fields if a browser does not support them.

When capturing times in a form, since time zones are


not supported, you’ll need to capture them a different
way. Y ou can use a hidden field for this if you don’t
want the user to change the time zone (this works best
for local events or appointments). If you want them to
select their own time zone, you can use a select box.

Color
The color input type allows users to select a color
through use of a color picker (FIGURE 9.18):
Figure 9.18 The color picker, as implemented by
Google Chrome

Click h er e to v iew code im a g e

<input type="color" name="carpet-color"


→ value="#FF0000" />

The value is a seven-character code in hexadecimal


format (which you’ll learn all about in Chapter 14). The
default value of color is black unless you specify a
different value.

Range
The range input type creates a slide controller that
allows users to adjust the value of a parameter by sliding
the controller along a scale. Y ou can set min and max
attributes to limit the possible range of values (FIGURE
9.19). The default values for min and max are 0 and
100, respectively.
Figure 9.19 The range field, as implemented by
Google Chrome

Click h er e to v iew code im a g e

<input type="range" name="rating"


→ min="0" max="10" />

Y ou can also use the step attribute, which allows you


to set a specific increment by which values can change.
The default value is 1. The step attribute happens to be
supported for date inputs as well, but it is best for
imprecise values, as in a volume controller.

VIDEO 9.8

Using Range
In this v ideo y ou’ll see how the range f ield is implemented in Chrome. Included is a
small bit of Jav aScript so y ou can see the v alue change in real time.

Grouping Fields Together


If y our f orm is lengthy, y ou can make it easier f or y our users to scan it by using two
elements f or organization: <fieldset> and <legend>.

You can place any number of f orm f ields and labels into a <fieldset> element. By
def ault, they will hav e a grey border around them.
You can then use the <legend> element to caption the <fieldset>. The <legend>,
by def ault, will appear aligned in the middle of the top border of the <fieldset>
(FIGURE 9.20).

Figure 9.20 The <fieldset> element with <legend>

CODE 9.2 Markup for two <meter> elements: one with, and one without, min
and max values defined.
Click h er e to v iew code im a g e

<label for="fuel">Fuel level:</label>


<meter id="fuel" value="0.2">
At 20%
</meter>

<label for="donations">Donations:</label>
<meter id="donations" min="0" max="100000"
→ value="60000">
at $60,000
</meter>

THE < M E T E R > ELEMENT


One pretty nifty element is <meter>, which graphically
represents a value over a range. It accepts several
attributes, but the ones to know about are value, min,
and max. The attributes min and max are optional. If
they are not specified, they default to 0 and 1,
respectively, and value is a fraction. If min and max are
defined, they determine the scale for value. Y ou can see
<meter> in action in FIGURE 9.21, which is
generated by CODE 9.2.

Figure 9.21 The two <meter> elements created by


Code 9.2

VALIDATING FORMS
Validation is an incredibly important part of any form.
There are three primary ways to validate forms:
T h e bu il t -in HT ML5 v a l ida t ion for specific fields like
em a il, URL, ph on e n u m ber , a n d m or e, a s w ell a s th e
v a lida tion a ttr ibu tes required a n d, if n eeded, pattern.

You ca n u se Ja v a Scr ipt to v a lida te da ta w h en it is


in pu t by th e u ser , especia lly if th a t da ta isn ’t
a u tom a tica lly v a lida ted by on e of th e in pu t ty pes. On e
ex a m ple in th e US is th e zip code; th ey sh ou ld follow a
specific for m a t, bu t th er e is n o in pu t ty pe defin ed for
th em .

A ser v er -side scr ipt w r itten in a la n g u a g e like PHP.


V a lida tin g a t th is sta g e m a kes su r e a ll da ta is in th e
r ig h t for m a t, a n d th a t th er e a r e n o m a liciou s a ttem pts
a t h a ckin g befor e y ou pr ocess it. Wh ile y ou don ’t n eed to
kn ow ser v er -side v a lida tion for th e ex a m ples in th is
book, on ce y ou sta r t lea r n in g h ow to w r ite ser v er -side
code, y ou w ill n eed to keep th is in m in d a s y ou pr ocess
for m s.

For the purposes of this book, using the built-in HTML


validation works well. As you begin to do more advanced
form processing, knowing how to validate with both
JavaScript and a server-side language is important.

Javascript and PHP are outside the scope of this book,


but there are a couple of helpful files in the Github repo
for this book.
Instead, here’s how to apply some great form validation
with HTML5 only.

The most basic validation you can add is to ensure that


required fields are filled out. That is as simple as adding
the required attribute:
Click h er e to v iew code im a g e

<div>
<label for=first_name">First Name*:
→ </label>
<input type="text" name="first_name"
→ id="first_name" placeholder="First
→ Name" required/>
</div>

Tip

It’s also a good practice to provide a visual indicator that a field is required.
Common methods include adding an asterisk (*) or the word required in
parentheses next to the label.
VIDEO 9.9

Building and Testing a Valid Form


Testing webpages is just as important as building them, and in this v ideo, y ou’ll see
how to build a small f orm using the v alidation methods, and then y ou’ll test it to make
sure it works properly.

If the required field is not filled out, modern browsers


will display an error message (FIGURE 9.22).

Figure 9.22 The error message when a required field


is not filled out

Similarly, there is a set of input types that have


automatic validation:

email: Looks for a v a lid em a il a ddr ess (FIGURE 9.23).

Figu r e 9.23 Th e er r or m essa g e w h en a v a lid em a il is


n ot en ter ed

url: Looks for a v a lid URL for m a t.

number: Looks for a v a lid n u m er ica l v a lu e. Usin g th e


min a n d max a ttr ibu tes w ill v a lida te on a specific r a n g e:
Click h er e to v iew code im a g e

<input type="number" name="age"


→ mix="13" max="150" />
tel: Looks for a teleph on e n u m ber .
Th is r equ ir es th e pattern a ttr ibu te.

The final piece of validation that can be applied in HTML


is the pattern attribute. This requires knowledge of
regular expressions (regex), but it allows you to supply
the description of a pattern, which all input can be
validated against. Here’s an example of a US telephone
format:
Click h er e to v iew code im a g e

<input type="tel" name="phone_number"


→ id="phone_number"
→ pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"/>

Tip

Regular expressions are a way of performing complex searching of text by


describing what they should look like. For example, the regex [0-9]{3} means
“any three digits between 0 and 9, inclusive of 0 and 9.” A great resource for
learning regex is regexone.com/.

WRAPPING UP
There’s a lot to know about forms, but thanks to HTML5
and advances in browser technology, you can do a lot
more with plain HTML today than you could even just a
few years ago.

I encourage you to experiment with all the different


inputs and data types to learn exactly how they work.
Y ou’ll find that you can build some pretty impressive,
and interactive, webpages.
10

Advanced and Experimental


Features
In This Chapter

It’s All About Browser Support


Advanced Elements

Experimental Features
Wrapping Up

HTML is constantly changing and evolving to meet the


needs of modern web developers, users, and devices. A
perfect example of this is the srcset attribute, which
allows the use of multiple images with the <img> and
<source> elements.

This wasn’t part of the original HTML5 spec, but it was


added because enough people requested and voted on the
proposal. In this chapter, you’ll learn about some of the
cool advanced features built into HTML5, what’s coming
down the pike, and how to start using those
experimental features today.

IT’S ALL ABOUT BROWSER SUPPORT


Hopefully it’s clear by now that how webpages render
and work is highly dependent on the browser on which
your end user views them. A page with one set of
markup will render differently in two different browsers
(FIGURE 10.1).
Figure 10.1 A website rendered in Chrome compared
to its rendering in Firefox

That’s a result of the fact that some browsers support


new features before others, and the way a new feature is
implemented in one browser might be totally different
from its implementation in another.
The HTML specification (or spec) is the document that
describes new features in HTML and how they should
work. Then it’s up to browsers to implement that spec.
Things have gotten a lot better in recent years, with
browser developers working together to make sure
there’s not a lot of disparity between them.
But you should still be mindful that some browsers
might support new features sooner than others, and
until a feature is marked as an official part of the HTML
spec, its functionality could change from browser to
browser.

VIDEO 10.1

Rendering Elements Differently in Different Browsers


To driv e home this idea, I’ll show y ou a f ew liv e examples of how dif f erent browsers
implement dif f erent HTML elements.

Checking browser support with “Can I Use …”


The best place to check browser support is the website
caniuse.com (FIGURE 10.2).

Figure 10.2 Caniuse.com

Caniuse.com allows you to look up an HTML or CSS tag


or attribute, and it gives you a full report on how it’s
used and what browsers support it. It will also give you
helpful information like global usage statistics, whether
some browsers provide partial support, and known
issues.

Tip
You’ll find caniuse.com especially handy when you start to use CSS.

Checking this site is a good idea if you want to


implement something (especially for new and
experimental features) and you’re not sure how widely
supported it is.

Fallbacks and polyfills


In the event that you want to use a feature of HTML
that might not be supported by all browsers, as a
contingency plan you can implement fallbacks or
polyfills.

A fallback is code or content used in the event that the


original code or content isn’t supported by the current
browser. It’s a way of saying to the browser, “If you
don’t understand the main code, use this other code
instead.”
HTML is very forgiving, so unsupported markup is just
ignored. This is great for you as a web designer, because
it means that if you want to use something like srcset,
you can. Just make sure to include a standard src
attribute as a fallback for browsers that don’t yet support
srcset.

The same goes for most elements. Either there’s a default


fallback (like unsupported form elements defaulting to
the text input type) or you can define your own
fallback (as in the srcset/src example). In features
you’ll see later in the book, you can even define an error
message that users will see if their browser doesn’t
support the feature. Each of these prevent your website
from completely breaking in older browsers.
Y ou can also add a polyfill. Mozilla (the creators of the
Firefox browser) defines it like this: A polyfill is a piece of
code (usually JavaScript on the Web) used to provide
modern functionality on older browsers that do not
natively support it.

Basically, you add code that you can download to older


browsers to support newer elements. While writing
JavaScript is outside the scope of this book, one example
is using a polyfill to add srcset support to old browsers.
Y ou can download the polyfill, called Picturefill.js, from
scottjehl.github.io/picturefill/. Include a reference to the
code in the head of your HTML document by using the
<script> element, which allows you to pull in code
that is not HTML or CSS. It’s most commonly used for
JavaScript, and it works very similarly to the <style>
element, which you’ll learn about when you get to the
CSS section of the book. For the examples in this
chapter, the script element is being used to pull in an
external JavaScript file.
Assuming the file picturefill.js is in the root
directory, add the highlighted code to the <head>
element:
Click h er e to v iew code im a g e

<head>
<script src="picturefill.js">
→</script>
</head>

This script will do the heavy lifting of checking the


browser to see if srcset is supported and, if it’s not,
creating the attribute for you to use.

What Are Progressive Web Apps (PWAs)?


PWAs are websites written in such a way that they prov ide on a mobile dev ice an
experience that f eels like that of a nativ e mobile application.
They use some combination of HTML, CSS, and Jav aScript, while also getting help
f rom the browser and operating sy stem.
The Product Feedback app on apple.com, Smashing Magazine, Twitter, and Uber all
use PWAs f or their mobile sites.

VIDEO 10.2

Examples of the <canvas> Element in Use


The <canvas> element is good at more than just drawing shapes. In this v ideo y ou’ll
see f antastic interactiv e examples of <canvas> being implemented.

ADVANCED ELEMENTS
So what exactly qualifies as an advanced HTML
element? For me, it’s any element that is supported by
HTML5 but requires something extra (usually
JavaScript) to work. Everything you should know about
JavaScript would certainly fill more than one book, so
there won’t be much JavaScript here.

The <canvas> element


The <canvas> element allows you to create drawings
by writing JavaScript (FIGURE 10.3). In more
advanced examples, you can even allow website visitors
to use their mouse cursor to draw in real time.

Figure 10.3 A house drawn with the <canvas>


element

This is an example of an element that requires heavy


JavaScript to use. HTML5 basically gives you a way to
execute JavaScript in real time to draw things, and then
a set of functions to help you draw. This demonstrates
how powerful HTML and the browser have become.

Adding support for offline storage


One great feature of HTML5 that has evolved as a result
of its use on mobile devices is support for offline storage.
This allows you to tap into the browser’s local storage
and keep content there in case the user’s device goes
offline (FIGURE 10.4).
Figure 10.4 When viewed with a broken internet
connection, the Twitter mobile site uses offline storage
to show most of the page.

Designing your website to allow offline storage also lets


you store assets on the user’s device and helps the site to
load faster.
While offline storage does use some JavaScript to store
and retrieve data, the code is very readable. This task
demonstrates the basic idea. It builds on the example
you saw in the Chapter 9 section “Input fields” which
gave you the code for building a search box.

To store data offline:


1. In betw een th e open in g a n d closin g <head> ta g s, ty pe
<script>.
Th is ta g tells th e br ow ser th a t th e follow in g m a r ku p is
Ja v a Scr ipt a n d sh ou ld be pr ocessed a s su ch .
2. Ty pe localStorage.setItem ("lastSearch",
"Atlantis");.
In Ch a pter 9 , y ou cr ea ted a sea r ch box a n d en ter ed th e ter m
“ A tla n tis.” You ’r e bu ildin g on th a t sa m e code ex a m ple h er e.
localStorage.setItem cr ea tes a key n a m e-v a lu e pa ir .
You ’ll lea r n m or e a bou t v a r ia bles in a la ter ch a pter , bu t for
th e pu r poses of th is ta sk, kn ow th a t w e a r e stor in g som eth in g
n a m ed “ la stSea r ch ” a n d it h a s a v a lu e of “ A tla n tis.”
3. Ty pe </script>.

This produces no visible change on the webpage, but it


tells the browser, “Store this, just in case you go offline.”
Retrieving information is just as straightforward.

VIDEO 10.3

Store Form Data in Offline Storage


In Chapter 9, y ou learned how to build web f orms. In this v ideo, y ou will store some
of that data using of f line storage.

VIDEO 10.4

How Twitter Uses Offline Storage


One of the clearest examples of of f line storage is the Twitter mobile web app. Once
it’s loaded, most areas, like the header, logo, and nav igation, will not need to ref resh,
because they ’re stored on-dev ice. The site will just load new tweets. Here’s what that
looks like in action.

To retrieve offline storage data:


1. A fter th e open in g <body> ta g , ty pe <div id="last-
search">.
You ’r e u sin g th e g en er a l-pu r pose div h er e beca u se it’s n ot a
specific section of th e w ebsite. Th e id a ttr ibu te pr ov ides
con tex t for w h a t in for m a tion it con ta in s.
2. Ty pe <script>.
3. Ty pe document.write( localStorage.
getItem("lastSearch") );.
document.write tells Ja v a Scr ipt to displa y tex t in th e
br ow ser for th e u ser to see. Un like w ith HTML, w h ich w ill
displa y a n y th in g th a t isn ’t a ta g , y ou n eed to ex plicitly tell
Ja v a Scr ipt w h en som eth in g sh ou ld be displa y ed.
localStorage.getItem tells Ja v a Scr ipt to r etr iev e th e item
y ou stor ed in th e la st ta sk.
4. </script>.
5. </div>.
6. Open y ou r HTML file in th e br ow ser to v iew th e r esu lts
(FIGURE 10.5).

Figure 10.5 The data retrieved from offline storage

sessionStorage
If y ou’re looking f or a way to store content online or of f line that’s a bit more
temporary than localStorage, look at sessionStorage, which has been part of
HTML much longer.
A page session lasts as long as the browser is open. It can ev en persist through
page reloads. If y ou v isit a site, ref resh a page, and see that it remembers certain
data y ou’v e prov ided, it might hav e been stored as session data.
sessionStorage works similarly to localStorage, but with localStorage, the data
is stored on the user’s dev ice and surv iv es ev en if the browser is closed.
sessionStorage is deleted when the browser is closed or the dev ice is restarted.

EXPERIMENTAL FEATURES
The HTML5 spec is a living document that is constantly
changing and being updated based on proposals from
developers, companies, and individuals like you.
It’s often hard to nail down what new features are being
worked on, what’s been accepted, and what’s going to
become official.

Caniuse.com can be a good resource for this, especially


the news page: caniuse.com/#info_news.
Many advanced features being developed for HTML
today are application programming interfaces (APIs).
These APIs, like Canvas and Local Storage, are aided by
JavaScript. But there’s one fantastic feature that is as
easy to implement as an attribute is.

Lazy loading
Lazy loading is a technique used to download and
display only the parts of your webpage that a user sees in
the browser window. This allows the browser to
download only what it needs, making webpages load
faster.
Traditionally this has been done with JavaScript or
another scripting language. However, native support for
the feature is now being added to browsers (FIGURE
10.6).
Figure 10.6 The caniuse.com page for native lazy
loading

VIDEO 10.5

Using Lazy Loading on Images


In this v ideo y ou’ll get to see the impact the loading attribute has on website load
times, and what it looks like in Chrome.

To add lazy loading to images:


1. Ty pe <img src="space.jpg".
2. Ty pe loading="lazy".
Th is a ttr ibu te is w h er e th e m a g ic h a ppen s! You ’r e tellin g th e
br ow ser th a t th is im a g e sh ou ld be la zy -loa ded. Sin ce th e
br ow ser h a s th is in for m a tion , it ch ecks to see w h eth er th e
im a g e is sh ow in g in th e u ser ’s v iew por t (th e br ow ser
w in dow ), a n d if it is, th e im a g e w ill be loa ded.
3. Ty pe alt="This is outer space."/>.

That’s it! Now the browser will download and display


this image only if the user has scrolled to its vicinity.

WRAPPING UP
With that look at some of the more advanced features of
HTML, you’ve come to the end of the HTML section of
this book. Y ou can now mark up a page, display text and
media, and build forms!
But that’s only half the battle. Now that you have the
“function” aspect of a website down, it’s time to look at
the “form” aspect: making websites look good with CSS.
11

Introduction to CSS
In This Chapter

What Are Styles?


What Does Cascading Mean?

CSS Syntax
Using CSS on Y our Webpage

External Style Sheets


Commenting Y our CSS Code

Wrapping Up

So far, you’ve learned all about HTML and how to


structure a website. But you may have noticed that we
haven’t talked much about style or design. If HTML
provides the function of a webpage, then CSS provides
the form.
CSS is used to change the look and feel of webpages by
targeting HTML elements and applying different styles.
As you’ll soon learn, you can change fonts, colors, sizes,
and so much more with CSS. But it’s also used for
positioning elements, layout, and even printed pages.

WHAT ARE STYLES?


What exactly do we mean when we talk about styles on
websites? Back in Chapter 1 you learned how using
HTML to structure a web document relates to
structuring a document created in Microsoft Word.
If you’ve ever applied custom formatting to the text in a
Word document, like changing the color of the text or
picking a new font, you’ve applied styling to the text.
Microsoft Word makes it easy to do this: just select some
text and choose a menu command or click a button, and
the text changes appearance! Y ou can also style text on
webpages, but there are no handy menu commands or
buttons.
Word-processing applications also let you save sets of
formatting characteristics that you might want to apply
to more than one item; these sets are called styles. Y ou
might want all of your headings to use 20-point boldface
font and be bright blue, for example. Rather than
choosing those formatting options by hand for each
heading, you can define the style you want for headings
and apply it very easily.

Much as we write HTML code to give overall structure to


a webpage, we write code of a different type to change
the styling of text on a webpage. That’s where CSS
(Cascading Style Sheets) comes in.
CSS uses code to define the styles that should be applied
to each element in your webpage. A collection of these
code statements is a style sheet, and style sheets can be
stored in the HTML document they apply to or in
separate text files.

CSS styles can be applied to both inline elements and


block-level elements. To continue the analogy with word
processors, a style applied to an inline element is akin to
a character style (which applies only to specific letters or
words), and a style applied to a block-level element is
similar to a paragraph style (which affects an entire
paragraph).

WHAT DOES CASCADING MEAN?


An important concept of CSS is the “cascading” part of
the name. One can imagine that “style sheets” are files
where the styles are defined. But what exactly does
“cascading” mean?
The word might conjure the idea of a waterfall, since
that’s what it’s most commonly associated with.
Generally, a cascade is a waterfall that drops in
successive steps.
When applied to style sheets or any information, it
means that previous information is built upon or
successively passed on.

In short, the “cascading” part of CSS means that styles


are generally applied in the order in which they’re
encountered by the browser, from the top of the style
sheet to the bottom. If you define on line 1 that
paragraphs should have red text, and on line 10 you say
they should have green text, the paragraphs will have
green text.

VIDEO 11.1

Demonstrating the Cascade in CSS


In this v ideo, y ou’ll see the cascade in action when we change the color of text by
adding dif f erent sty les below the original sty les. You’ll see them update in real time as
y ou edit them in CodePen.

Why is this important?


Understanding how styles cascade is integral to styling
websites as well as to troubleshooting. Not only do styles
used later in a document take precedence over those
used earlier, but styles can also be built upon. This is
especially evident while setting font sizes.

Tip
“CSS” and “style sheets” are often used interchangeably.

In CSS, you can say something like “I want paragraph


text to be two times bigger than the default font size.”
Without understanding the cascade, you will get
unexpected results in your styles (FIGURE 11.1).
Figure 11.1 In this example, the nested list uses a
bigger font than the main list because of an error in
the CSS.

With that out of the way, it’s time to learn how to write
some CSS!

Tip
Not all web browsers handle cascading styles the same way. See “Browser
Support” at the end of Chapter 16 for more information.

CSS SYNTAX
A CSS statement, also referred to as a ruleset, contains
several parts. Here’s an example of a ruleset:

p {
font-size: 20px;
color: red;
}

Here you’ll find the selector followed by an opening curly


brace, then the property, a colon, and the value. Taken
together, the property and the value make up a
declaration (FIGURE 11.2). Each declaration ends
with a semicolon. A ruleset can have several
declarations. It’s a good practice, for readability, to have
one declaration per line.
Figure 11.2 A simple diagram of a ruleset, with each
section labeled

After the declarations, you find a closing curly brace.


Everything between the opening and closing curly braces
is called a declaration block.
The selector is the HTML element you want to style with
the CSS (this is also referred to as targeting an element).
There are lots of ways to target elements. For this
chapter, you should focus on using the element name (p,
h1, and so on). However, as you’ll learn in Chapter 12,
you can also target elements based on their attributes—
most notably, their class name.
With CSS, you have a ton of flexibility to design pretty
much anything you want on a website. And there’s no
better demonstration of that than CSS Zen Garden
(FIGURE 11.3).
Figure 11.3 CSS Zen Garden (csszengarden.com) is a
popular website that clearly demonstrates the power
of CSS.

The idea behind CSS Zen Garden is that several people


submitted style sheets for the same HTML markup. The
goal was to make the styles as different from each other
as possible. If you click through the submissions, you’ll
see they accomplished that goal! Bounce back to Chapter
1 to see CSS Zen Garden in action in Video 1.2.

Tip
To make your rulesets more readable, have only one declaration per line.
Most text editors will not do this for you unless you create a custom workflow
(which could be complicated), so doing it manually will help form the habit!

Tip
In Chapter 12, you’ll learn about targeting elements, and in the following
chapters you’ll learn about a variety of properties and their values.

USING CSS ON YOUR WEBPAGE


There are two principal ways of adding CSS to any
webpage:

A s a n internal s tyle s heet in th e HTML docu m en t

A s a n external s tyle s heet in a sepa r a te file


Internal style sheets
To use an internal style sheet (that is, one that’s
embedded in the page that it applies to), you use the
<style> tag. This is most commonly placed between
the opening and closing <head> tags, but it can be
referenced anywhere before the </html> tag. It will
look something like this:

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

Y ou would use this format for one-off references—styles


that apply only to the page you’re using it on.

Tip
Before HTML5, you would use the type attribute with the <style> tag to
explicitly tell the browser you’re writing CSS, like this: <style
type="text/css">. In HTML5, text/css is the assumed value.

VIDEO 11.2

Using an Internal Style Sheet


In this v ideo, y ou will use an internal sty le sheet to add CSS to a webpage and see
how the page changes in real time.

To add CSS to your webpage using an internal


style sheet:
Y ou can use any HTML file you’ve created for this task.
If you’d like a starting point you can use the file found at
github.com/jcasabona/html-css-vqs/ch11/starter.html.
1. On th e lin e befor e th e closin g </head> ta g , ty pe <style>.
2. Ty pe th e selector for th e elem en t y ou a r e sty lin g —in th is
ca se, p.
3. Ty pe a left cu r ly br a cket ({) to beg in th e decla r a tion block.
Nex t, y ou ’ll a dd th e pr oper ties for th e size of th e fon t a n d its
color . En ter ea ch on e on its ow n lin e.
4. Ty pe font-size: 20px;.
5. Ty pe color: red;.
6. Ty pe } to close th e decla r a tion block a n d th e sty le r u le.
7. Ty pe </style>.
Th e r esu ltin g m a r ku p w ill look som eth in g like FIGURE 11.4.

Figure 11.4 An internal style sheet CSS added to an


HTML file

Inline Styles
There is a third method of using CSS, but its use is f rowned upon these day s. If y ou
want a sty le to apply only to a single element, y ou can use an inline style. With inline
sty les y ou embed the sty le inf ormation directly in the element’s tag.

For example, if y ou want to f ormat just one paragraph to make it stand out f rom the
rest of the page, y ou could giv e it a v iv id color and super-size the f ont. The code
would look something like this:
<p style="color: chartreuse; font-size: 64px;">
The sy ntax is similar to “normal” CSS, but it uses the style HTML attribute right
af ter the element’s opening tag, and the v alue of the attribute is presented as a
series of CSS property -v alue pairs.

Inline sty les are not considered good practice, because they mix up the sty le
inf ormation with the HTML and the content, making rev ising or maintaining the code
more dif f icult.

Depending on the contents of the file, the page will look


something like FIGURE 11.5.
Figure 11.5 The result of adding the above CSS to a
webpage, along with what the page looked like before
the styles were added
This is great if you are designing a single page or have
page-specific styles. But what if you want to use styles
across multiple pages? That’s what .css files are for!

EXTERNAL STYLE SHEETS


Y ou can take all of the CSS in between those <style>
tags and place it in a separate file with the extension
.css. Y ou’ll then reference that file in the head of your
HTML file by using the <link> tag.

If you name the file style.css, that might look


something like this:

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

The <link> tag is using two attributes here:

rel specifies th e r ela tion sh ip betw een th e cu r r en t


docu m en t a n d th e lin ked docu m en t. In th is ca se, th e
lin k is a sty le sh eet.

href is a r ela tiv e or a bsolu te URL.

In the actual style.css file, you will have only the


CSS rulesets—no <style> tags required!

Tip
There are lots of ways to organize your CSS. Many people create a separate
folder for the styles and organize them by section. For the purposes of this
book, all CSS goes in one file.

VIDEO 11.3

Moving Internal CSS to an External File


See the prev ious task in action. You’ll create a new f ile and mov e internal CSS to it.

To move internal CSS to an external file:


1. In th e HTML file, copy a ll th e CSS th a t’s betw een th e
<style> a n d </style> ta g s.
In th e a bov e ex a m ple, it w ou ld be:
p {
font-size: 20px;
color: red;
}

2. Cr ea te a n ew file in y ou r tex t editor ca lled style.css. Sa v e


it in th e sa m e folder a s y ou r HTML file.
3. Pa ste th e copied sty les in to style.css.
4. Ba ck in y ou r HTML file, delete ev er y th in g fr om <style> to
</style>.
5. Ty pe <link rel="stylesheet" type="text/css"
href="style.css" />.

That’s it! Y ou’re now referencing your CSS from an


external file. From here on out, that’s how all our CSS
will be written, unless otherwise specified.

COMMENTING YOUR CSS CODE


Just as with HTML, you can include nonfunctional text
inside your CSS (whether it’s internal or external). This
allows you to make notes and document your styles.
Here’s a CSS comment:

/* This is a CSS Comment */

Each comment starts with a forward slash (/) and


asterisk (*), followed by the comment text, and closes
with another asterisk and forward slash. What you see
above is a single line comment, but you can also add
multiple-line comments:

/* This is
a comment that spans
multiple lines. */

Y ou can use CSS comments to add descriptions of the


styles, note the specific purpose of the css file, credit the
file’s author, or create sections in your CSS file (this can
be helpful if your style sheet is especially long).

VIDEO 11.4

Review of the new File System


Bef ore mov ing on, we rev iew how the website directory is organized.

WRAPPING UP
CSS opens up a whole world of opportunity for you to
take a website and make it your own through design.

In the next several chapters, you’ll see how to customize


everything, create stunning layouts, and even learn a
few shortcuts to save you some time.
But first, you need to learn how to target all the
elements.
12

Targeting Elements
The crux of styling websites is understanding which
elements to target and how targeting them affects the
rest of your style sheet.

In This Chapter

Targeting Elements by Tag

Targeting Elements by Class


The Cascade, Inheritance, and Parent-Child
Relationships

Selecting Elements by their Relationships


Specificity and Precedence in the Cascade

Targeting Elements with Specific Attributes


Advanced Targeting
Wrapping Up

At face value, you can target any HTML element and


apply a set of styles to it. However, you can also target
elements within other elements, elements with specific
attributes, and much more.

As you’ll see, you can get incredibly specific with how


you target elements on a webpage.

TARGETING ELEMENTS BY TAG


The clearest way to target any element in HTML is by its
tag—namely, p, h1, ul, or any other HTML tag. The
example you saw in Chapter 11 worked this way, and
doing this will target every instance of that element. So if
you target the <p> tag and have seven paragraphs, all of
them will adopt the styles you have defined for the
paragraph element.

Tip
This is also referred to as a type selector.

To target an element by its tag:


1. In y ou r style.css file, ty pe th e ta g for th e elem en t y ou
w a n t to ta r g et, w ith ou t th e < a n d > ch a r a cter s. For th is
ex a m ple, u se p.
2. Ty pe { to open th e sty le decla r a tion block.
Ev er y r u leset is con ta in ed betw een { a n d }.
3. Ty pe color: (th e pr oper ty y ou w ish to defin e).
4. Ty pe green; (th e v a lu e of th e color pr oper ty ).
5. Ty pe } to close th e sty le decla r a tion .
Th is tu r n s a ll pa r a g r a ph tex t g r een (FIGURE 12.1).

Figure 12.1 All the paragraphs on the page adopt the


style of green text.

Targeting multiple elements


Y ou can also target multiple elements, as long as they’re
separated by commas. So if you want all paragraphs,
unordered lists, and ordered lists to have green text, the
CSS code in Figure 12.1 would look like this:

p, ul, ol {
color: green;
}
This would change the page to look like FIGURE 12.2.

Figure 12.2 Now all paragraphs and lists (ordered


and unordered) have green text.

VIDEO 12.1

Setting Basic Styles on HTML Elements


In this v ideo, y ou’ll learn some of the most common CSS properties y ou’ll use f or
sty ling elements, and y ou’ll set baseline sty les f or y our website.

TARGETING ELEMENTS BY CLASS


The best way to target some instances of an element
without targeting all of them is to use a descriptor on all
the elements you want to target. The class attribute is
used for this:

<p class="standout">

I chose the value (or name) standout for the class


attribute because I’m going to style any elements with
this class to make them stand out more. Y our class
names can be anything, but web developers increasingly
argue that they should be semantically descriptive, not
stylistically descriptive. For example, don’t set
class="green" merely because the text is green. If the
text needs to be red sometime in the future, the class
name will no longer make sense.

Then in your style sheet, you can target any class by


preceding the value with a period (.), like this:
.standout {
color: green;
}

This says, “For any element with the class standout,


make the text color green.”

Y ou can also get more specific by combining element


and class to say, “Only paragraphs with the class
standout should be targeted”:

p.standout {
color: green;
}

To make the first paragraph of a page bigger:


1. In y ou r HTML file, fin d th e fir st pa r a g r a ph a n d a dd to it a
class a ttr ibu te w ith a v a lu e of “ in tr o” by ty pin g <p
class="intro">.
A ssig n in g th e intro cla ss to th e fir st pa r a g r a ph of ea ch pa g e
a llow s y ou to sty le it differ en tly fr om th e oth er pa r a g r a ph
elem en ts.
2. In y ou r CSS file, on th e n ex t bla n k lin e, ty pe p.intro {.
Th is lim its th e sty le decla r a tion to pa r a g r a ph s of cla ss
intro.
3. Ty pe font-size: 24px;.
Th e defa u lt fon t-size for m ost br ow ser s is 1 6 px , so th e tex t in
a n y <p> elem en t w ith th e cla ss intro w ill be la r g er th a n th e
defa u lt size for th e pa g e.
4. Ty pe }.
5. Sa v e th e files a n d open th e HTML file in th e br ow ser to see
th e r esu lt (FIGURE 12.3).

Figure 12.3 With the new class and style, the first
paragraph on the page is now bigger than the others.
Classes are a powerful way to add extra specificity to
your styles and to highlight certain text.

VIDEO 12.2

Targeting Specific Classes


In this v ideo y ou’ll create an HTML page with v arious classes on it, then write CSS to
target those classes.

VIDEO 12.3

Creating a Set of Alert Elements


In this v ideo y ou’ll create a set of alert classes to use throughout y our website.

About Naming Classes


Naming conv entions f or CSS classes hav e been hotly debated. The schools of
thought mov e between “the class name should describe the content of the element”
and “the class name should describe the sty les being applied.” As more semantic
HTML has emerged, along with more CSS f rameworks, a strong argument exists f or
sty le-descriptiv e names.
You’ll notice that the examples in this chapter use both. The truth is, it depends. If
y ou’re working on rulesets that can be applied specif ically to achiev e a certain sty le,
then they should be named appropriately (.green-text is a good example of this).
But if y ou’re making a ruleset to create a specif ic ty pe of element and the sty le can
change, a more descriptiv e class is appropriate (.button and .alert are good
examples).

Targeting multiple classes


Just like with elements, you can target multiple classes
with a single style by using a comma-separated list:

.intro, .outro {...}

And you can target elements if, and only if, they have
multiple classes by “daisy-chaining” them, like this:

.class-one.class-two {...}

A good example of why you might want to do this is if


you have a base style but want to alter a single instance
of that style. Say we have a class called alert, with
these properties (FIGURE 12.4):
Figure 12.4 Here’s the simple alert class, applied to
a paragraph.

.alert {
background: red;
color: white;
font-weight: bold;
padding: 5px;
}

Assume that you’ve defined this as the default style for


alerts on the site. But perhaps there is a single instance
where you want to use a background color of blue. To
achieve that, start by creating a new class whose
background color is styled blue:

.alert.blue-background {
background: blue;
}

Then combine the two styles. In the HTML file it will


look like this: <p class="alert blue-
background"> (FIGURE 12.5).

Figure 12.5 The alert element, now with a blue


background

This technique can also work without combining the


styles in the CSS. So if you wanted more than just alerts
to have blue backgrounds, you could target the rule like
this:

.blue-background {
background: blue;
}

In this case, you don’t have to change the HTML, and


everything will still work as expected!
Tip
There is one caveat to the less specific method: you need to make sure the
generic class (in this case, .blue-background) comes after the class you want
to change in the CSS (in this case, .alert). Otherwise, the less specific class
will override the generic class, thanks to the cascade.

THE CASCADE, INHERITANCE, AND


PARENT-CHILD RELATIONSHIPS
In Chapter 11, you were introduced to the idea of the
cascade, the principle that the lower on a CSS style sheet
a ruleset is, the more likely it is that it will be used to
style the element it’s targeting. But that’s only part of the
story.

Throughout this chapter, you get the other part of the


story: styles are applied depending on how you target
elements. Y ou’ve learned how to target elements and
classes, and soon you’ll see how to be really specific with
your targeting. But before we get to that, you need to
understand inheritance and the family tree of HTML
elements (FIGURE 12.6).
Figure 12.6 A simple family tree. Descending
elements fall “under” their parent elements, inheriting
styles that aren’t specifically overridden by a
declaration.

Just about any set of HTML markup will include


elements in parent-child relationships. In fact, all the
HTML markup on a given page is a descendant of the
<html> element, which is considered the root of the
document—the topmost level, or the start of the family
tree.
FIGURE 12.7 will help you visualize the family tree
structure. In this example, <article> is the parent
element of the elements between its opening and closing
tags. It has three children: <h1>, <p>, and <p>. The first
<p> contains one child element, which is <a>. The
second <p> has two children: <span> and <b>. And
<a>, <span>, and <b> are also grandchildren, or
descendants, of <article>. CODE 12.1 shows how
these relationships might appear in HTML.

Figure 12.7 This chart should help you visualize the


“family” terms that are applied to HTML elements.

Another way to think of children and descendants is that


they exist within another element. Siblings exist next to
each other. So in Figure 12.7, <h1>, <p>, and <p> are
siblings. So are <span> and <b>.
CODE 12.1 A sample of HTML demonstrating the family relationships shown in
Figure 12.7.
Click h er e to v iew code im a g e

<article>
<h1>Welcome to Joe’s Website!</h1>
<p><a href="https://casabona.org">Joe
Casabona</a> is an accredited college
course
→developer and professor.</p>
<p>He also has his <span>Master’s
Degree in Software Engineering</span>, is
a <b>Front End
→Developer</b>, and hosts multiple
podcasts.</p>
</article>
SELECTING ELEMENTS BY THEIR
RELATIONSHIPS
Y ou can select elements according to their relationships
with other elements in the same family tree. For
example, you can choose to target only the descendants
of a particular parent element.

To target only the descendant of a particular


element:
1. Ty pe th e selector of th e a n cestor elem en t. For ex a m ple, to
ta r g et on ly lin ks in side pa r a g r a ph s, y ou w ou ld fir st ty pe p.
2. Ty pe a spa ce (th is is v er y im por ta n t).
3. Ty pe th e n a m e of th e descen da n t elem en t, w h ich in ou r
ex a m ple is a.
4. Ty pe th e decla r a tion block for th e sty le.

Our complete example looks like this:

p a {
background: lightgrey;
color: darkblue;
}

This turns gray the backgrounds of all anchor tags inside


paragraphs (FIGURE 12.8).

Figure 12.8 Notice that links in paragraphs have a


gray background, but links in unordered lists (<ul>)
do not.

Targeting specific types of elements works well if you


want to apply styles uniformly across those elements,
and it’s often used to define what are referred to as
“base” styles. Those can include:

Site-w ide tex t color s

Fon t fa ce/ty pog r a ph y

Fon t sizes

Spa cin g betw een elem en ts

Hea din g sizes

… and anything else you want to define on a global level.


But what happens when you only want to target certain
elements? There are a few ways to do that.
CODE 12.2 The two <a> elements are child elements of different parents.
Click h er e to v iew code im a g e

<footer>
<p>This is the footer with a
→<a href="#">link in it</a></p>
<a href="#">Click here to learn
more</a>
</footer>

Selecting a child element (>)


Using a child selector says, “Target any elements that are
direct children of a specific element.” This is slightly
different from the descendant selector because with child
selectors, there can be no other element between the
element on the left side of the child selector and the right
side. In CODE 12.2, <p> and the second <a> are
children of <footer>, but the first <a> is a child only of
<p>.

To target only the direct child of a particular


element:
1. Ty pe th e selector of th e pa r en t elem en t. Bu ildin g on th e
ex a m ple in Code 1 2 .2 , u se footer.
2. Ty pe a g r ea ter -th a n sy m bol >.
3. Ty pe th e selector of th e elem en t th a t is th e im m edia te ch ild
of th e pa r en t. In th is ca se, u se a.
4. Ty pe th e decla r a tion block for th e sty le.
This is how you would style only links that are direct
children of the footer element (in our example, the
second a element):

footer > a {...}

But footer a {...} would not work. It is not specific


enough, and all links inside the <footer> tag would be
styled.

Selecting an adjacent sibling (+)


To target an element that immediately follows another,
use the adjacent sibling selector. For example, you would
use an adjacent sibling selector to apply a style to the
first paragraph after the heading in the following HTML,
but not to the second:

<h1>Here's the Scoop!</h1>


<p>...</p>
<p>...</p>

To target an adjacent sibling element:


1. Ty pe th e selector for th e fir st elem en t—in th is ca se, h1.
2. Ty pe a plu s sig n +.
3. Ty pe th e selector for th e siblin g to w h ich y ou w a n t th e sty le
to a pply . In ou r ex a m ple, th a t’s p.
4. Ty pe th e decla r a tion block for th e sty le.

Tip

This is a more succinct way to style a single paragraph than using the
custom intro class style, as we did earlier in the chapter.

Using a general sibling selector (~)


Similarly, if you do want to target all paragraphs that
are siblings of the h1, rather than just the first one, use
the general sibling selector, like so: h1~p {...}.

Tip
As of CSS3, child and descendant selectors are officially called child
combinator and descendant combinator, but many people still use the old
terminology.

VIDEO 12.4

Putting Child and Sibling Selectors to Work


The best way to understand these selectors is to see them in action, and in this
v ideo, y ou’ll get a single HTML example to see how the dif f erent selectors af f ect it.

SPECIFICITY AND PRECEDENCE IN


THE CASCADE
Throughout this chapter, the topics of specificity and
precedence have been unavoidable. CSS relies heavily on
both to apply the appropriate styles to elements.
Precedence of a style is based on two criteria:

Th e or der of sty les in th e sty le sh eet

Specificity of th e selector

If a ruleset comes later in the style sheet, it takes


precedence over earlier styles that target the same
element, unless the earlier style is more specific. Things
can get a little confusing at this point, but in general,
here are some reasons a ruleset is more specific:

It h a s m or e selector s (p a is m or e specific th a n a).

A cla ss is a pplied (p.alert is m or e specific th a n p).

Mu ltiple cla sses a r e a pplied ( .alert.blue-background


is m or e specific th a n .alert).

Whenever you’re troubleshooting CSS, always check to


make sure another style isn’t taking precedence over the
style you expect to be applied.
Note that elements will inherit any styles that aren’t
explicitly changed with a more specific or more recent
selector. For example, text (in most browsers) defaults to
color: black; and font-size: 16px; until you
change it in CSS.
VIDEO 12.5

A Look at Styles and Precedence


In this v ideo y ou’ll see how changing specif icity and order af f ect precedence,
demonstrated by apply ing sty les to elements and changing them in real time on
CodePen.io.

!important: Proceed with Caution


In y our trav els, y ou might come across the v alue !important at the end of CSS
declarations, like this:

p {
color: blue !important;
}

The !important tag say s, “Nev er ov erride this sty le, ev en if another ruleset takes
precedence.” In this example it means y our paragraph text will alway s be blue.
This may seem like an easy f ix when y ou can’t f igure out why y our CSS isn’t
working, but it is of ten unnecessary and makes y our CSS unmanageable. My rule is
that if y ou use !important, y ou need to add a comment to the sty le sheet
explaining why y ou used it.

Styling with IDs

Tip

A tip right off the bat! This section is included for completeness, since you
might see CSS out in the wild using IDs. But as you’ll see, you shouldn’t use
them to target elements.

In the early days of CSS, there was another way to


target elements for CSS, and that was with the id
(identifier, or ID) attribute:

<p id="intro">

To use an ID in your CSS, instead of prepending the


value with a . (period), as you do with classes, you’d use
#:

#intro {
font-size: 24px;
}

While this method works, you should not use IDs in


your CSS unless you have a rock-solid reason (if I were
to use the word never in programming/computing, I’d
use it here).
That’s because when it comes to precedence, ID trumps
pretty much everything.

Instead, classes should always be used for styles. Today,


IDs are more often used to target elements in JavaScript.

VIDEO 12.6

Trying to Override IDs in CSS


To demonstrate why y ou shouldn’t use IDs in CSS, this v ideo demonstrates what
happens when one is used, and how hard it is to ov erride.

TARGETING ELEMENTS WITH


SPECIFIC ATTRIBUTES
So far you’ve learned how to use type and class selectors
to target elements, and how to get more specific by
targeting descendants and multiple classes. But even
more options are available.

Classes aren’t the only attributes you can target. In fact,


you can target any attribute with this syntax:
element[attr], where attr represents the name of
an attribute. The name of the attribute is enclosed in
square brackets. So to target all images with an alt
attribute, use this:

img[alt] {
background: blue;
}

The Difference Between ID and Class


There’s a semantically signif icant dif f erence between classes and IDs that giv e
some insight into why IDs take so much precedence.
Classes can be assigned to multiple elements on a page. You might f ind the class
alert or button sev eral times on a webpage.

IDs, on the other hand, should be completely unique to a single element on the page.
You should only f ind an ID once on a webpage.

Y ou can even target attributes with specific values; the


value is also inside the square brackets and follows the
attribute. So to apply a specific color to links that go to a
specific URL, you would use something like this
example:

a[href="https://google.com"] {
color: green;
}

Lastly, a few selectors let you search on attribute values


by inserting a special character before the equals sign
(=). For example, adding an asterisk (*) to the attribute
tells CSS to find any attribute whose value contains the
text after the equals sign. So to highlight all images with
the word dog in the alt tag, you would use the following:

img[alt*="dog"] {
background: red;
}

To highlight links that go to sites in the .org domain, use


the dollar sign ($) attribute selector to search for URLs
that end in .org:

a[href$=".org"] {
background: yellow;
}

Tip
There’s a lot more you can do with attribute selectors. Check out MDN for a
comprehensive guide: developer.mozilla.org/en-
US/docs/Web/CSS/Attribute_selectors.

ADVANCED TARGETING
In addition to targeting specific elements and classes,
you can use a set of advanced selectors known as
pseudo-selectors. Right now, we’ll focus on a specific
subset of these selectors known as pseudo-classes. There
are two types of pseudo-classes: those that focus on state
and those that focus on order.

The pseudo-classes that are based on a particular state of


an element allow us to target elements based on how a
user is interacting, or has interacted, with the element.
They are always preceded by a colon (:). Here’s an
example:

a:link

Tip

There are a lot of pseudo-classes! This chapter introduces the idea and
points out some popular ones, but you can see a comprehensive list at
developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes.

User interaction states


Likely the most common pseudo-classes you’ll use are
those for link states. They allow us to give the user a
visual cue as to how they are interacting with an
element. For example, these states tell the user if they
have or have not clicked a link:

:link for lin ks th a t h a v e n ot been clicked or v isited

:visited for lin ks th a t h a v e been clicked or v isited

The following states, which allow us to tell a user if they


are currently interacting with an element, are most
often associated with links but can be applied to any
element:

:hover for w h en a v isitor ’s poin ter is h ov er in g ov er th e


ta r g et elem en t.

:active is u sed w h en a n elem en t is “ a ctiv a ted” by a


u ser . A g ood ex a m ple of th is is a bu tton click.

:focus is u sed w h en a u ser clicks, ta ps, or u ses th e


key boa r d to select a n elem en t. Th is is kn ow n a s g iv in g
th e elem en t focu s, a n d it’s often u sed w ith for m
elem en ts.

To style link states:


1. Ty pe a, a:link {.
2. Ty pe color: green;.
3. Ty pe font-weight: bold;.
4. Ty pe }.
5. Ty pe a:visited { .
6. Ty pe color: grey;.
7. Ty pe }.
8. Ty pe a:focus, a:hover, a:active {.
9. Ty pe color: red;.
10. Ty pe }.
Th is cr ea tes lin k sta tes in w h ich n on -v isited lin ks a r e g r een ,
v isited lin ks a r e g r a y ed ou t, a n d a ctiv e/h ov er ed-on lin ks a r e
r ed (FIGURE 12.9).

Figure 12.9 The user has already visited the first link
on the page (now colored gray) and is hovering over
the “Creator Courses” link, giving it focus. They have
not visited the Podcasting link, so it is green.

Order-based selectors
Another common set of pseudo-classes is based on the
order of the elements. There can be a lot of combinations
for these, but here are the ones you’ll see most:

:first-child for th e fir st ch ild of a specific elem en t


w ith in th e pa r en t.

:last-child for th e la st ch ild of a specific elem en t


w ith in th e pa r en t.

:nth-child(even) or :nth-child(odd) for th e ev en or


odd ch ild of a specific elem en t w ith in a pa r en t.

:nth-child(x), w h er e x is a n in teg er , ta r g ets th e


n u m ber x ch ild on a specific elem en t w ith in a pa r en t.

:first-of-type for th e fir st ty pe of a specific elem en t


w ith in a pa r en t.

Tip
The difference between :first-child and :first-of-type can be confusing, but it
boils down to this, using p:first-child and p:first-of-type as an example: if the
first child of some element—say, <article>—is a <p>, first-child and first-of-
type will be the same. However, if the first child is <h1>, first-child styles
won’t apply to the p, only first-of-type styles will.

VIDEO 12.7

Reimagining the p.intro Class with Advanced Selectors


Now that y ou hav e a f ew more tools in y our selector kit, y ou’ll see where y ou can
remov e classes and instead target by using pseudo-selectors.

To create a list with alternating background


colors:
1. Ty pe ul li:nth-child(even) {.
Th is ta r g ets in sta n ces of <li> th a t a r e descen da n ts of <ul>.
2. Ty pe background: lightgrey;.
3. Ty pe }.
4. Ty pe ul li:nth-child(odd) {.
5. Ty pe background: lightblue;.
6. Ty pe }.
Ev en -n u m ber ed list item s n ow h a v e a lig h t g r a y
ba ckg r ou n d, a n d odd-n u m ber ed item s h a v e a lig h t blu e
ba ckg r ou n d (FIGURE 12.10).

Figure 12.10 Using nth-child, you can create a list


with alternating background colors.

This is a great way to style tables!

The universal/wildcard selector (*)


There’s one more selector you should know about it, but
use it with caution—the universal selector:

* { ... }
This targets all elements on the page, and it could have
unexpected results. Y ou can also get slightly more
specific with it and target everything within a certain
element:

article * { ... }

This is often used to set site-wide styles for font face, size,
or other items that need to be the same.

CSS Resets
A common practice is to use a CSS reset. Because each browser has its own def ault
sty le sheet applied, y ou can get mixed results af ter apply ing y our sty les. A CSS
reset makes sure ev ery browser starts at the same point with regard to sty les.

It might be tempting to use the * selector to reset ev ery thing in one f ell swoop. But
then y ou’ll also reset important def ault sty les like bold and italic text, or possibly link
colors, padding, and more.
You should be more surgical with CSS resets. A great and v ery popular reset is Eric
Mey er’s, which y ou can get at mey erweb.com/eric/tools/css/reset/.

WRAPPING UP
Y ou got a lot of information in this chapter, and it’s okay
if some of it hasn’t sunk in yet! I suspect you’ll regularly
refer to this chapter. I know I will!

But it provides important groundwork for the chapters to


come. Now that you know what’s possible in terms of
targeting, it will be easier to envision how the styles
you’re about to learn can transform your websites.
13

Styling Text
In This Chapter

Choosing Fonts
Google Fonts

Including External Fonts with @font-face

Sizing Text

Formatting Text
Formatting for Readability

Wrapping Up

When it comes to styling text, you have a ton of freedom


to make it look however you like. But understanding the
effect it makes is important. How you style your text can
have the biggest impact on the general design of your
site.
Typography is a huge part of design, and getting it right
can take your site to the next level. While this book
doesn’t go into a full study of typography, you will get
everything you need to customize the text on your site
with CSS.

CHOOSING FONTS
When you’re thinking about which font (or typeface) to
use on your website, first consider which fonts are
actually available to you.
Today, the world is your oyster when it comes to fonts.
But there used to be only a small number of cross-
platform fonts that you could be confident the user
would see correctly. They are still called web-safe fonts.
The following are fonts that have traditionally been
considered web-safe:

A r ia l

Cou r ier New

Geor g ia

V er da n a

Tr ebu ch et MS

Tim es New Rom a n

Tip
By default, browsers use Times New Roman as the font for text. This is a very
safe font that comes on pretty much every device.

That’s why we have the syntax for font handling that we


do today—you list the main font you want to use, and
then provide one or two fallback choices. This is also
called a font stack.

In CSS, the property used to specify the font used for an


element is font-family. The value of font-family is
a comma-separated list of fonts you want to use, from
highest to lowest priority. The font you want to use is
listed first, followed by the fallbacks in the order in which
you want to use them.

Tip
While it might seem like font-family refers to the overall list of the individual
fonts you want to use, that’s not the case. A font, also known as a typeface,
should include several styles, such as roman, bold, italic, and so on. The
entire set of styles taken together is the font family.

Here’s an example:
Click h er e to v iew code im a g e

p {
font-family: Cambria, "Times New
→Roman", serif;
}
This says, “Use the font Cambria. If that’s not available,
use Times New Roman. If that’s not available, use the
system’s default serif font.”

Tip
You’ll learn about popular sources for fonts later in the chapter. But first,
you should know about what types of fonts are available to you.

Tip
Nowadays, “font” and “typeface” are generally used interchangeably. In
earlier times, though, when typesetting was done with metal or wood, they
had distinct meanings. A typeface was the overall design of a set of
letterforms (Garamond), but a font was subset of that collection of a specific
style and size (Garamond Italic 14-point).

Types of fonts
Always try to group a font with fallbacks that look
similar. That’s because in the event that a fallback is
used, you want your site to look as close as possible to
what you originally intended.

Fonts used with CSS are broken down into a few


categories, based on their style (FIGURE 13.1):

Figure 13.1 An example of each major font style

VIDEO 13.1

Using Distinct Styles for Heading and Body Elements


In this v ideo, y ou apply dif f erent f onts to dif f erent sections of y our site. A common
practice is to hav e dif f erent f onts f or the headings and the body copy.
Ser if, w h ich is a fon t th a t h a s ex tr a str okes on th e en ds of
ea ch letter .

Sa n s ser if, w h ich la cks th e ex tr a str okes.

Mon ospa ce, or fon ts w h er e ev er y ch a r a cter h a s ex a ctly


th e sa m e w idth . Th ese fon ts a r e often r em in iscen t of
cla ssic ty pew r iter tex t. Th ey ’r e a lso com m on ly u sed to
r epr esen t com pu ter code.

Cu r siv e, w h ich a r e fon ts desig n ed to look like


h a n dw r itin g .

Fa n ta sy , w h ich a r e h ig h ly decor a tiv e fon ts.

To set the default font for a whole website:


1. A t th e top of y ou r style.css file, ty pe body {.
Th is ta r g ets th e <body> ta g . A ll th e elem en ts w ith in th is ta g
w ill in h er it th e fon t sty les th a t w e a ssig n to it.
2. Ty pe font-family:.
3. Ty pe Futura, Helvetica, Arial, sans-serif;.
Fu tu r a is a g r ea t sa n s ser if fon t bu t is in sta lled by defa u lt
on ly on m a cOS, so th is fon t sta ck pr ov ides fa llba cks th a t a r e
m or e w idely a v a ila ble.
4. Ty pe }, sa v e th e file, a n d open it in y ou r br ow ser .
Th e tex t on th e pa g e is n ow displa y ed in a sa n s ser if fon t
(FIGURE 13.2).

Figure 13.2 Viewed in macOS, the page now uses


Futura, with a fallback to more common fonts on
other systems.

Pairing Fonts
When pairing f onts (choosing multiple f onts to display on a page), try to f ind ones
that complement each other.
Your goal is to prov ide v isual distinction between dif f erent ty pes of text, such as
headings and body copy. Here are some tips:

Pair a serif f ont with a sans serif f ont.

Dif f erentiate using size and weight.

Don’t pick f onts within the same classif ication (f onts that look similar).

Giv e each f ont its own role. If y ou’re using one f or the heading (say,
Futura bold), don’t also use it f or the body.

There’s a lot to know around ty pography and f ont theory —more than this book can
cov er. But one really great resource is On Web Typography, by Jason Santa Maria
(abookapart.com/products/on-web-ty pography ).

GOOGLE FONTS
While the main source for fonts is the user’s device, there
are also many ways to use fonts from other sources. It’s
now possible to use basically any font you like.

A common source of fonts is Google Fonts, a library of


free open source fonts that anyone can include on their
website (FIGURE 13.3). There are tons of fonts to
choose from, as well as recommended pairings and
more!

Figure 13.3 The Google Fonts (fonts.google.com)


homepage

Tip
There are other services that work similarly to Google Fonts, like Adobe
Fonts (fonts.adobe.com) and H&Co for the web
(www.typography.com/webfonts), but most of them cost money.

VIDEO 13.2

Browsing Google Fonts


A crash course on how to use Google Fonts, f rom f inding the f onts and creating
collections to getting the embed link.

To add Google Fonts to your website:


1. V isit fon ts.g oog le.com .
2. Fin d a fon t y ou like a n d click it.
For th is ta sk, I’ll u se Roboto (FIGURE 13.4).

Figu r e 13.4 Th e Roboto fon t option on fon ts.g oog le.com .


Clickin g th is ta kes y ou to a list of a ll th e sty les y ou ca n
select.

3. Click Select Th is Sty le for ea ch sty le y ou w a n t to in clu de (


).

I’ll select Reg u la r 4 00, Reg u la r 4 00 Ita lic, a n d Bold 7 00.


4. In th e Selected Fa m ily box th a t a ppea r s, click Em bed
(FIGURE 13.5).
Figu r e 13.5 Th e Em bed ta b on Goog le Fon ts. Th is is w h er e
y ou w ill fin d th e CSS code to copy .

5. Click @import.
6. Copy th e tex t betw een th e <sty le> ta g s, w ith ou t in clu din g
th e ta g s th em selv es.
7. Pa ste th e copied tex t in to y ou r style.css file, a t th e top.
8. Below th a t, ty pe body {.
9. Ty pe font-family: Roboto, sans-serif;.
10. Ty pe }, sa v e th e file, a n d open it in y ou r br ow ser .
You r w ebpa g es n ow u se Roboto a s th e defa u lt fon t for body
tex t (FIGURE 13.6).
Figure 13.6 An HTML page using the Roboto font

Tip
Google Fonts is a great way to include a nice-looking font for free, but be
aware that using too many fonts in your design increases the number of files
the browser needs to download, and it will slow down your site for users.

VIDEO 13.3

Embedding Fonts from Google Fonts


In this v ideo, y ou’ll explore ev en more options f or using Google Fonts on y our
website, plus some pitf alls to look out f or.

INCLUDING EXTERNAL FONTS WITH


@FONT-FACE

If you don’t find a font you want in one of the online


services, you can download and use an external font by
linking to it using the @font-face at-rule.

An at-rule is a CSS statement that tells CSS how to


perform or behave. All at-rules start with an at sign: @.
Y ou’ll see several at-rules throughout the rest of the
book. The @font-face at-rule tells CSS to use the
provided files as a font.
The statement begins with the at-rule, followed by an
opening curly brace. That’s followed by the font-
family property, which tells the browser how to
reference the font by creating a new font family to use.
Since it’s a declaration, it ends in a semicolon.
The font-family declaration is followed by another
property, src. It behaves much like the <srcset>
implementation of src. In this syntax, src is followed
by a colon and two values: url, encapsulated by
parentheses and single quotes, and format, also
encapsulated by parentheses and single quotes. The URL
can be relative or absolute. The format is the file
format, which will most likely match the font file’s
extension. More on font formats later in the chapter.

src can accept multiple sources separated by commas,


and the last source ends in a semicolon. Here’s an
example:
Click h er e to v iew code im a g e

@font-face {
font-family: 'Best Font';
src: url('bestfont.woff')
format('woff'),
url('bestfont.ttf')
format('ttf) ;
}

Reference the font like this in your CSS:


Click h er e to v iew code im a g e

font-family: 'Best Font', sans-serif;

In this instance, you’ll likely pay for a font, and they can
range from a few dollars to hundreds. However, you can
download free fonts from websites like Font Squirrel
(FIGURE 13.7).
Figure 13.7 The Font Squirrel (fontsquirrel.com)
homepage

Tip
Be aware of licensing issues! Even though you can technically upload any
font to your server for your website doesn’t mean you can legally. If you’re
using this technique, make sure you have a license to use the font on the
web.

There are two caveats to using this method. The first is


that different browsers support different font file
formats.
Luckily, it can pretty much be boiled down to two:
WOFF (Web Open Font Format) and WOFF2. Most
modern websites use WOFF2 because it offers 30 percent
compression gain over WOFF, making it faster for
browsers to download. Optionally, you can use TTF
(True Type Font).

In either case, you might have to convert your font into


one of the above formats. To do so, you can use a
webfont generator called Transfonter (FIGURE 13.8).
Figure 13.8 The Transfonter webfont generator
(transfonter.org)

VIDEO 13.4

Converting a Font with Transfonter


In this v ideo, y ou’ll download a f ont and then process it using the webf ont generator
at transf onter.org to output the f ont in the f ormats y ou need.

The other caveat is that you’ll need to include each style


of the font as a separate @font-face directive in your
style.css file. So regular, bold, and italic (as well as
other variations) all have their own files that need to be
included (FIGURE 13.9). This can make your style file
lengthy, but it might be worth it to get that perfect font.
Figure 13.9 JetBrains Mono is a font with many
styles.

Tip
The browser can fake certain styles, like bold and italic, but the text can end
up looking warped. It’s best to use the specifically designed style instead.

Tip
If you want to see this in action, open the Google Fonts import file to see lots
of @font-face inclusions. Do that by copying the URL in your @import
statement and pasting it into your browser.

To add a custom font to your CSS with @font-


face:

1. A t th e top of th e file style.css, ty pe @font-face { to beg in


th e @font-face r u le.
It’s a ssu m ed a ll fon ts for th is ta sk a r e in th e sa m e folder a s
style.css.
2. Ty pe font-family:.
3. Ty pe th e n a m e of th e fon t fa m ily y ou w a n t to in clu de—for
ex a m ple, 'JetBrains Mono';.
Use a n y fon t y ou like, a n d n a m e th e fon t fa m ily w h a tev er
y ou like.
4. Ty pe src: url('jetbrains-mono.woff2')
format('woff2'),.
5. Ty pe url('jetbrains-mono.woff') format('woff'),.
6. Ty pe src: url('jetbrains-mono.woff')
format('woff');.
7. Ty pe }.
8. Ty pe body {.
9. Ty pe font-family: 'Jetbrains Mono', Courier,
monospace;.
10. Ty pe }.

Now you’re ready to use a custom font on your website


(FIGURE 13.10)!

Figure 13.10 JetBrains Mono is now being used on


this page.

Now that you know how to choose the font, it’s time to
look at what else you do to style your text.

VIDEO 13.5

Using @font-face
In this v ideo, y ou’ll get an in-depth look at using @font-face, as well as at including
(v ersus excluding) multiple sty les.

SIZING TEXT
Y ou resize text using the font-size property, like this:

p {
font-size: 18px;
}

Several different units of measurement can be used for


font-size:
Pix els (px): Th is is a fix ed m ea su r em en t, w h ich m ea n s
1 8 px w ill a lw a y s be 1 8 px . Desig n er s like th is beca u se it
g iv es th em th e m ost con tr ol ov er th e fon t size.

Per cen ta g e (%): Th is is a per cen ta g e of th e pa r en t


elem en t’s fon t. In m ost br ow ser s, th e defa u lt size is 1 6 px ,
so if w e w a n t h ea din g s to be 3 2 px , w e cou ld specify a
fon t size of 200%.

Em (em): Tr a dition a lly in ty pog r a ph y , th is h a s m ea n t


“ th e size of a ca pita l M.” Toda y , it’s a w a y of m ea su r in g
font-size a s a m u ltiplier r ela tiv e to th e pa r en t. So
u sin g th e ex a m ple a bov e, if w e w a n t a 3 2 px h ea din g , w e
cou ld specify 2em (or tw o tim es th e pa r en t’s fon t size).

Root em (rem): Th is beh a v es ju st like em , ex cept it is


a lw a y s ba sed on th e r oot (or defa u lt) size. In th is ca se, it
is ba sed on th e font-size a pplied to th e body selector .
Th is m a kes th e r ela tiv e fon t sizes m u ch ea sier to keep
tr a ck of, beca u se y ou don ’t h a v e to w or r y a bou t
m u ltiplier s on ch ildr en or g r a n dch ildr en .

Tip
Many people use a CSS reset (see Chapter 12) to make the default font-size
value 10px, which makes for much easier font size arithmetic.

Tip
Relative font sizes (%, em, rem) were often favored by web designers because
they take custom user settings into account. This was an accessibility and
inclusion benefit for those who have trouble seeing. But now, modern
browsers zoom the entire page when a user increases the size of the visuals
on a page.

One way to use font-size is to establish a harmonious


relationship between the sizes of heading and body text
(FIGURE 13.11).
Figure 13.11 Notice that the h1 is double the size of
the body copy.

VIDEO 13.6

Font Size Demo


In this v ideo, y ou’ll see how each measurement unit af f ects f ont size.

To set the size of headings relative to the size of


body text:
1. In sty le.css, ty pe h1 {.
2. Ty pe font-size: 2em;.
3. Ty pe }.

Size isn’t the only thing you can change. In fact, there’s
a whole set of text formatting properties available to you.

VIDEO 13.7

Creating a Heading Hierarchy with Font Sizes


Using em or rem can make it easy to create a nice v isual hierarchy f or y our text and
headings—something called a ty pe scale. In this v ideo, y ou’ll do just that.

FORMATTING TEXT
There are lots of properties for formatting text, but here
are the most common ones.

font-weight
The font-weight property allows you to apply a
different boldness to text. There are two primary values:

normal, w h ich is u n bolded tex t

bold, w h ich cr ea tes bold, da r ker tex t

But as CSS has evolved, there are now some other values
to consider:

lighter m a kes tex t th in n er th a n th e n or m a l w eig h t.

bolder m a kes tex t th icker th a n th e bold w eig h t.

Nu m ber ed v a lu es: You ca n defin e a w eig h t a t 100, 200,


300, 400, 500, 600, 700, 800, or 900. 400 is a kin to
normal; 700 is a kin to bold (FIGURE 13.12).

Figure 13.12 Font weight variations

Tip
Depending on the font, many of these may depend on the style. If you don’t
have a font’s style for a 900 weight, the browser will default to the highest
weight you have.

For example, to make all your links bold, you would


define the style for the anchor element this way:
a {
font-weight: bold;
}

font-style
Next up is the font-style property, which italicizes
text (FIGURE 13.13). There are three values:

Figure 13.13 Font style variations

normal, w h ich is n or m a l, str a ig h t tex t.

italic, w h ich u ses th e ita lic sty le to sh ow ita lic tex t.

oblique, w h ich u ses th e obliqu e sty le if it ex ists. If th er e


is n o su ch sty le, th e br ow ser tilts n or m a l tex t slig h tly to
m a ke it look obliqu e.

Tip
Often italic and oblique look the same. If there is no italic style supplied, the
browser defaults to oblique. If neither is supplied, the browser simulates the
style.

Here’s an example:

h3 {
font-style: italic;
}

text-decoration
The text-decoration property allows you to add
emphasis lines to your text. There are several values
(FIGURE 13.14):
Figure 13.14 Text decoration variations

none: Th er e is n o ch a n g e to th e tex t.

underline a dds a lin e u n der th e tex t. Use th is to for ce


lin ks to be u n der lin ed (m ost m oder n br ow ser s displa y
lin k u n der lin es w h en th e u ser h ov er s ov er th em ).

overline a dds a lin e ov er th e tex t.

line-through a dds a lin e th r ou g h th e tex t (like a


str ike).

If you have an article or story with a byline, you can use


text-decoration to make the byline stand out a little
bit.
As an example, here’s one way to style a byline class:

.byline {
text-decoration: underline;
}

Y ou can make text-decoration accept multiple


values by listing them separated by spaces. So if you
want to have an overline and an underline, for example,
you can do the following:

.byline {
text-decoration: underline
→overline;
}

Finally, text-decoration is actually shorthand for


three other properties. Include them in this order,
separated by spaces:
text-decoration-line, w h ich u ses th e v a lu es y ou ’v e
seen a bov e.

text-decoration-style, w h ich ch a n g es w h a t th e lin e


looks like. Th e defa u lt v a lu e is solid; th e oth er option s
a r e double (tw o solid lin es), dotted (a lin e m a de ou t of
dots), dashed (a lin e m a de ou t of da sh es), a n d wavy (a
squ ig g ly lin e) (FIGURE 13.15).

Figu r e 13.15 Tex t decor a tion sty le v a r ia tion s

text-decoration-color, w h ich a ccepts a n y color .

This allows you to add more personality to the line


(FIGURE 13.16):

Figure 13.16 The byline class with a wavy blue line


instead of the standard solid black line

.byline {
text-decoration: underline
→wavy blue;
}

Y ou can take this example a little further and apply


some of the other properties you’ve learned as well.

To format a byline class:

1. In style.css, ty pe .byline to ta r g et th e byline cla ss.


2. Ty pe { to beg in th e sty le decla r a tion .
3. Ty pe font-style: italic;.
4. Ty pe font-weight: bold;.
5. Ty pe text-decoration: underline;.
6. Ty pe } to close th e sty le decla r a tion .
Now , tex t a ssig n ed th e byline cla ss is sty led bold, ita lic, a n d
u n der lin ed (FIGURE 13.17).

Figure 13.17 The byline class applied to the author


credit paragraph

FORMATTING FOR READABILITY


The styles in the previous section are mostly used to
apply emphasis or draw attention to text. But there are
also styles that improve text readability—things like line
and text spacing, alignment, and more. Here are the
common ones.

Alignment and justification


Using CSS, you can align text both horizontally and
vertically.
With the text-align property, you can align the edge
of the text to the left or right margin, center the text, or
even justify it.

Justified text expands every line (except the last line) so


that it takes up the full width of the container (FIGURE
13.18).
Figure 13.18 Justified text

With vertical-align, you can move elements


vertically as they line up next to each other. So when
you have two elements next to each other and one is
taller than the other (for example, an image next to
text), you can use vertical-align to line up their top
edges. It’s also useful for vertically aligning text in tables.

Tip
Don’t use vertical-align to set text in the middle or bottom of a container.
Other features of CSS, like flexbox (which you’ll learn about later), serve that
purpose.

vertical-align values include the following:

baseline a lig n s th e elem en t w ith th e ba selin e of th e


pa r en t (th e ba selin e is th e lin e on w h ich m ost letter s of a
fon t sit).

sub a lig n s th e elem en t w ith th e su bscr ipt ba selin e of th e


pa r en t (a bou t 5 0 per cen t below th e ba selin e).

super a lig n s th e elem en t w ith th e su per scr ipt ba selin e


of th e pa r en t (a bou t 5 0 per cen t a bov e th e ba selin e).

text-top a lig n s th e top of th e elem en t w ith th e top of its


pa r en t’s fon t.

text-bottom a lig n s th e bottom of th e elem en t w ith th e


top of its pa r en t’s fon t.

Along with the above, you can use the following values
for table cells:

top a lig n s th e tex t in th e cell w ith th e top of th e cell.

middle a lig n s th e tex t in th e cell in to th e m iddle of th e


cell.
bottom a lig n s th e tex t in th e cell w ith th e bottom of th e
cell.

You ca n see th em in FIGURE 13.19.

Figure 13.19 vertical-align values


demonstrated

Text spacing
Finally, there are several properties for spacing text, all
using the same unit measurements as font-size
(though em is popular for these properties):

line-height: Th e a m ou n t of spa ce a lin e ta kes u p,


in clu din g fon t size a n d lea din g (th e w h itespa ce betw een
lin es). For m ost fon ts, th is is a r ou n d 1 .2 em (or 1 .2 tim es
th e fon t size).

letter-spacing: Th e a m ou n t of spa ce betw een ea ch


letter (a lso kn ow n a s ker n in g ).

word-spacing: Th e a m ou n t of spa ce betw een ea ch w or d.

text-indent: In den ts th e fir st lin e by som e a m ou n t.


Most often , px is u sed h er e.

Tip
To figure out the line height, subtract the font-size value from the line-
height value. So if line-height is 20px and font-size is 16px, the space
between lines is 4px.

Tip

If you want to move text completely off canvas, you can apply a negative
text-indent value (like -9999px). This gives you the element to work with,
without the text. You might do this if you want to make text animate on a
hover state (you’ll learn more about animations in Chapter 18).

To set the internal spacing for paragraphs:


1. Ty pe p {.
2. Ty pe line-height: 1.5em;.
3. Ty pe letter-spacing: 0.1em;.
4. Ty pe word-spacing: 0.2em;.
5. Ty pe }.

Y ou can see in FIGURE 13.20 that this gives the text a


completely different feel.

Figure 13.20 Before and after adjusting line, letter,


and word spacing

VIDEO 13.8

Using text-indent to Hide Text


Using the text-indent property, y ou’ll learn how to hide written text and replace it
with a background image.
More Text-Related Properties
Ev en with all the ground this chapter cov ers, there are still more text-related
properties. Here’s a quick list of other helpf ul properties:

text-transform allows y ou to change the capitalization of an element’s


text.

hyphens specif ies whether text should be hy phenated at line breaks.

overflow-wrap specif ies whether the browser should insert line breaks into
otherwise unbreakable text (like long words).

white-space specif ies how to handle whitespace inside an element.

word-break specif ies whether to insert a line break when a word would f low
outside an element.

text-shadow allows y ou to apply drop shadows to text and adjust their


sty ling.

To learn more about these properties, check out dev eloper.mozilla.org/en-


US/docs/Learn/CSS/Sty ling_text/Fundamentals.

WRAPPING UP
Using these properties, you can completely transform
the look and feel of your site without doing much else.
FIGURE 13.21 shows a great-looking page that is 99
percent powered by the techniques you learned in this
chapter.
Figure 13.21 A beautiful website whose design is
created by text styles

But still, typography is only a small part of the vast


toolset you have in CSS. Another great way to customize
your site is with color, the subject of the next chapter.

VIDEO 13.9

Building the Page from Figure 13.21


In this v ideo, y ou’ll see how the page f rom Figure 13.21 was put together using
primarily ty pographic parameters.
14

Color in CSS
In This Chapter

How Computer Monitors Work


Representing Color in CSS

Gradients
The border Property

Wrapping Up

The web has come a long way since its beginning. It


used to be that the only way to get fun colors or complex
graphics into a webpage was by incorporating images.
But now that the web supports a wide range of colors—
along with gradients, patterns, and more—you can use
CSS to add a lot of color.
Finding the right color scheme for a website is key to
good design. In this chapter, you’ll learn all the CSS you
need to know in order to customize the colors of
elements, sections, and states.

HOW COMPUTER MONITORS WORK


Before jumping into choosing colors, you should know a
little bit about how computers represent colors. The
screens of computer monitors are made up of millions of
tiny squares called pixels.
When you turn a screen on, light shines through those
pixels to illuminate them, and each pixel colors the light
with a combination of red, green, and blue. A Venn
diagram (FIGURE 14.1) is a good way to show the
three primary colors—red, green, and blue—and the
colors they produce when combined.

Figure 14.1 A Venn diagram for combining red,


green, and blue

Y ou can see that as they overlap, they begin to form


other, secondary colors:

Com bin in g r ed a n d g r een pr odu ces y ellow .

Com bin in g g r een a n d blu e pr odu ces cy a n .

Com bin in g blu e a n d r ed pr odu ces m a g en ta .

Com bin in g a ll th r ee color s pr odu ces w h ite.

A la ck of color pr odu ces bla ck.

Armed with that information, you can generate a


numerical code for any color.

REPRESENTING COLOR IN CSS


In CSS, there are four ways you can define colors:
RGB: A com m a -sepa r a ted list of th e a m ou n t of r ed,
g r een , a n d blu e in a color , fr om 0–2 5 5 .

Hexa decim a l (or h ex) v a l u es: A six -ch a r a cter code


th a t defin es th e a m ou n t of r ed, g r een , a n d blu e in a color
pr eceded by a h a sh ta g (#).

Col or n a m es: Th er e is a set of pr edefin ed n a m es for


color s, like blue, aquamarine, a n d rebeccapurple. You
ca n see th e fu ll list of n a m es, a n d th eir color s, a t
h tm lcolor codes.com /color -n a m es/.

HSL: Th is defin es th e color in ter m s of h u e (a s a n a n g le


on th e color w h eel), sa tu r a tion (a s a per cen ta g e), a n d
lig h tn ess (a s a per cen ta g e). Th is is a n u n com m on
m eth od.

Both RBG and HSL can also accept an alpha value,


which defines the opacity of the color.

Hexadecimal colors
FIGURE 14.2 is a pretty basic table. In the top row, the
letters R, G, and B (representing red, green, and blue)
are at the heads of the columns. Underneath it, you have
six Fs, two in each column. This second row shows how
you represent colors in CSS.

Figure 14.2 Red, green, and blue divided into


columns

The three pairs of Fs represent hexadecimal values,


which are numbers in base 16. They include the standard
digits from base 10 (0–9) and continue up the scale
using the letters A–F to represent 10–15. A two-
character hexadecimal number can range from 00–FF,
or from 0–255 in decimal (base 10) notation.
Because these numbers cover a huge range of values
(over 16 million), you can use them to create almost any
color you’d like. The first two characters state how much
red goes into a color, the middle two how much green,
and the last two how much blue. A value of all Fs is
white, and all 0s is black. Y ou can think of all 0s as the
complete lack of any color, and all Fs as the maximum
amount of any color.
For example, “pure” red is #FF0000 (it has the most red
there can be, no green at all, and no blue at all). Purple
in this instance would be #FF00FF (maximum red, no
green, maximum blue).

To set a color for a style:


1. In style.css, ty pe th e n a m e of th e selector y ou w a n t th e
sty le r u le to a pply to—in th is ca se, body.
2. Ty pe { to beg in th e decla r a tion block.
3. Ty pe th e n a m e of th e pr oper ty y ou w a n t to defin e a n d th e
v a lu e of th a t pr oper ty . In th is ex a m ple, to tu r n th e pa g e
bla ck, ty pe background: #000000;.
4. Ty pe th e n ex t pr oper ty y ou w a n t to defin e a n d its v a lu e.
Her e, to m a ke th e body tex t w h ite, ty pe color: #FFFFFF;.
5. Ty pe } to close th e decla r a tion block a n d th e sty le r u le.

FIGURE 14.3 shows the result.


Figure 14.3 Using a CSS style rule to define the
background and text colors with hex values

VIDEO 14.1

Using a Color Picker


Aside f rom getting the color code, a good color picker will recommend complementary
colors to use in color schemes. You’ll learn about two tools that help y ou do that.

Color Contrast
Color contrast is an important concept to understand because bad contrast makes
y our website harder to read. It can also negativ ely af f ect those who hav e color
blindness. That’s why most books are white pages with black text—in most cases,
it’s easiest to read.
You want to get the right contrast between background and text colors to enhance the
legibility of the page. Make sure y our text stands out on the page, as f ar as color,
f ont size, and line height go. Dark text on a light background is generally pretty saf e.
If y ou want a dark background, darker gray s work best, along with increasing the line
height.

Of course, y ou’re not expected to know ev ery color’s hex code (or RGB/HSL v alue)
of f the top of y our head. Lots of tools can help y ou f ind the v alues f or the colors
y ou want to use. The website htmlcolorcodes.com has a f antastic one (FIGURE
14.4).

Figure 14.4 The color picker at htmlcolorcodes.com/color-picker/

Using RGB and RGBA to set color


Using RGB to set color is very much like using hex: you
specify numerical values for red, blue, and green, but in
decimal notation, not hexadecimal notation. For
example, to specify pure red, type rgb(255, 0, 0).
To specify purple (a mixture of red and blue), type
rgb(255, 0, 255).

Both hex and RGB share one big problem: there’s no


way to change the opacity of a color. Luckily, there’s a
variant of RGB that does allow you to set the opacity
level: RGBA.

The A in RGBA stands for alpha channel. It adds to the


color specification a component that lets you set the
opacity value from 0 (completely transparent) to 1
(completely opaque, the default value) (FIGURE 14.5).

Figure 14.5 A photo with a red overlay at different


stages of opacity

For example, to define a semitransparent red


background, you would type rgba(255, 0, 0, 0.5).

To define background color using RGBA:


1. Ty pe body {.
2. Ty pe background: rbga(0, 0, 0, 0.25);.
3. Ty pe }.

That gives you a page that looks like FIGURE 14.6.


Figure 14.6 A page with a semitransparent black
background

Y ou can also use the opacity property to change the


transparency of an element. This property accepts values
between 0 and 1, but that applies to the entire element—
including text, images, and anything else—and not just
its background.

VIDEO 14.2

Using Transparency to Make Text Stand Out


To demonstrate how transparency can make a section stand out, in this v ideo y ou’ll
learn how to create a semitransparent white box on a darker background.

Using HSL and HSLA


HSL is a relatively new way to define colors based on the
color wheel (FIGURE 14.7).
Figure 14.7 A color wheel for determining hue—the
H in HSL

The value of hue, or H, is its position on the color wheel,


which is measured in degrees from 0 to 360. This makes
it a little easier to figure out the color as you increment
or decrement the H value. Especially with hex, it might
be hard to look at a value and figure out what color it
will translate to. With HSL, thanks to the hue, beginners
have a better understanding of what color they’ll see
based on the value.
Saturation, or S, is the amount of gray in a color (or
conversely, how pure the color is). This is represented as
a percentage, where 0 percent is gray and 100 percent is
full saturation of the hue.

Lightness, or L, is the amount of white or black in the


color, again as a percentage: 0 percent is no light
(black), and 100 percent is full light (white). This is true
no matter what the hue or saturation. Using HSL, red
would be hsl(0, 100%, 50%).

Like RGB, HSL can also accept an alpha value for


opacity. So a semitransparent red would be hsla(0,
100%, 50%, 0.5).

With that, you’ve seen the most common properties for


controlling color in CSS: background (which changes
the background color) and color (which changes the
text or foreground color). But there are a few other ways
you can use color in CSS.

VIDEO 14.3

Generating HSL Values


Since HSL is a little dif f erent f rom hex and RGB, in this v ideo y ou’ll see how HSL
v alues are generated, and how they can be more intuitiv e to use than the f ormer
methods.

GRADIENTS
Using CSS you can generate a gradient to smoothly
transition between two or more colors, or color stops.
There are two types of gradients: linear-gradient()
(which transitions in a straight line) and radial-
gradient() (which transitions outward from the
center).
Tip
CSS also includes the conic-gradient() type, but at the time of this writing it
isn’t supported by all the major browsers.

Gradients in CSS are actually functions that generate a


background image. Because of that, there is a lot of
information you can send to them.

In their most basic form, you just need the type of


gradient you want to use and two colors. Each function
has built-in defaults to take care of the rest:
Click h er e to v iew code im a g e

background: linear-gradient(red, orange);


background: radial-gradient(red, orange);

The first line generates a red-to-orange linear gradient


(FIGURE 14.8). If direction isn’t assigned, top to
bottom is assumed.

Figure 14.8 A simple red-to-orange linear gradient

The second line generates a red-to-orange radial


gradient. By default, the first color listed is at the center
(FIGURE 14.9).
Figure 14.9 A simple red-to-orange radial gradient

Y ou have lots of other options when designing gradients:

Mor e th a n on e color

Dir ection

Color stops (a s in , stop r ed a t 1 0 per cen t a n d beg in th e


tr a n sition to or a n g e)

Size

Let’s take a look at the functions and the information


you can send to them.

Linear gradients
The linear-gradient() function accepts two types of
values: those for direction and those for a color list.

Here’s how to define direction with linear-gradient:

angle: Th e sta r tin g a n g le of th e g r a dien t. It defa u lts to


1 8 0 deg r ees.
A n g les ca n be defin ed u sin g fou r u n its: deg, grad, rad,
a n d turn. You ca n lea r n m or e a bou t ea ch u n it a t
dev eloper .m ozilla .or g /en -US/docs/Web/CSS/a n g le.

side-or-corner: Th is is a set of key w or ds th a t


cor r espon d to specific a n g les. Th is v a lu e sta r ts w ith th e
w or d to a n d th en con ta in s u p to tw o key w or ds: on e for
th e h or izon a l lin e (left or right) a n d on e for th e
v er tica l (top or bottom).
to bottom, to top, to right, a n d to left cor r espon d
to, r espectiv ely , 180deg, 0deg, 90deg, a n d 270deg.

To create a full two-color background using


linear-gradient():

1. Ty pe body {.
2. Ty pe background:.
3. Ty pe linear-gradient( to open th e fu n ction .
4. Ty pe to right.
Th is specifies th e dir ection th e g r a dien t sh ou ld g o. “ Fr om
left” is im plied.
5. Ty pe rgba(0,0,0,0.25) 68%,.
Th is defin es th e fir st color a s bla ck a t 2 5 per cen t opa city .
Th e color stops a t 6 8 per cen t of th e w idth of th e con ta in er .
6. Ty pe rgb(0,0,0) 69%.
Stoppin g th e secon d color 1 per cen t la ter g iv es a defin itiv e
bor der .
7. Ty pe ); to close th e fu n ction .
8. Ty pe } to close th e sty le decla r a tion .

The result is a background that serves as a content area,


with a black background for a sidebar (FIGURE
14.10).
Figure 14.10 Creating a background with sidebar
using linear-gradient

And here’s the code:


Click h er e to v iew code im a g e

body {
background: linear-gradient
→(to right, rgba(0,0,0,0.25)
→68%, rgb(0,0,0) 69% );
}

Radial gradients
With radial gradients, you define the color stop list in the
same way, but defining the gradient is a bit different.
Y ou can use these values to define radial-
gradient():

<position>: Th is is r ela tiv e to th e top left of th e


con ta in er , a n d ca n be top, bottom, left, right, or
center. It ca n a lso be a n u m er ic offset (tw o n u m ber s, on
th e x a n d y a x es).

<shape>: Th is is h ow th e g r a dien t w ill be dr a w n . You


ca n u se ellipses (th e defa u lt) or circle.

Tip
You can define how big a radial gradient is with <extent-keyword>, which is a
bit advanced. Read about it at developer.mozilla.org/en-
US/docs/Web/CSS/radial-gradient.

VIDEO 14.4

Experimenting with Gradients


There are many dif f erent properties y ou can assign to gradients. In this v ideo, y ou’ll
learn more about them and see what they do.

To create a radial gradient:


1. Ty pe body {.
2. Ty pe background:.
3. Ty pe radial-gradient(.
4. Ty pe circle at center,.
5. Ty pe red, blue.
6. Ty pe );.
7. Ty pe }.

The result is a background that looks like a long circle in


the middle, transitioning to blue around the edges
(FIGURE 14.11).

Figure 14.11 Creating a radial gradient

Tip
CSS Tricks has a very comprehensive writeup on gradients: css-
tricks.com/css3 -gradients/.

Just as with colors, there are helpful tools with which


you can generate the CSS code for gradients. One good
tool is cssgradient.io/ (FIGURE 14.12).
Figure 14.12 cssgradient.io

Background Images
Gradients are treated as background images in CSS (using the background-image
property ). The background property is shorthand, and the browser is smart enough to
f igure out what y ou mean.
But that means y ou can set images as backgrounds in CSS. Here’s the sy ntax f or
that:

background: url(‘url/of/image’);
You can also set parameters f or other v alues. One is position, which is measured
relativ e to the upper-lef t corner of the screen by def ault. You can prov ide x or y
coordinates or key words, like top, bottom left, right, and center.
You can also state whether y ou want the background to repeat, and more.

VIDEO 14.5

Background Images
Gradients are one implementation of background images, but there are sev eral more
background-related properties. These include background-position, background-
repeat, and background-size.

In this v ideo y ou’ll learn more about how to use images f or backgrounds.

THE B O R D E R PROPERTY
The other (much less complicated) CSS property that
uses color is border, which is shorthand for three
properties: border-width, border-style (from a set
of options; see FIGURE 14.13), and border-color.
The styles are as follows:
Figure 14.13 Border styles

solid

dashed

dotted

double

groove

ridge

inset

outset

hidden

none

A definition looks like this:

border: 1px solid #000000;

To define a border around paragraph elements:


1. Ty pe p {.
2. Ty pe border:.
3. Ty pe 1px.
4. Ty pe solid.
5. Ty pe red;.
6. Ty pe }.
Y ou end up with something like FIGURE 14.14.

Figure 14.14 A red border around a paragraph

Y ou can also use each of these properties, and the same


declarations, for each individual border, the top, bottom,
left, and right. Use the following syntax:

border-[side]
border-[side]-[property]

So if you want to style just the top border:

p {
border-top: 1px solid red;
}

or

p {
border-top-style: solid;
}

Tip
The main reason to use border instead of a text decoration like underline or
overline is that those apply only to the text; border includes the whole
container.

There’s a lot more you can do regarding borders or box


decorations in general.

VIDEO 14.6

Doing More with Borders


Aside f rom changing border sty le, width, and color, y ou could change border-radius,
giv ing elements a nice rounded/button ef f ect. You could also add a box-shadow. See
those CSS border properties and more in action.
VIDEO 14.7

Creating a Stylized Aside Section


With all of these nif ty new things y ou can do with colors, it’s time to see it all come
together. In this v ideo, y ou’ll sty le <aside> to stand out in a body of text.

WRAPPING UP
Understanding color is a fundamental part of creating
websites. Luckily, there are a lot of online resources
dedicated to making it easier.
With your color schemes, you can design pages that
come to life or even evoke an emotional response. With
this fundamental concept down, it’s time for you to start
manipulating the elements and laying them out just the
way you like them.
15

Using CSS for Page Layout


In This Chapter

The Box Model


Padding and Margins

Element Flow
Creating Layers and Overlapping Elements

Creating an Overlay Using z-index

A Note About Creating Layouts

Wrapping Up

Y ou’ve learned how to use CSS to change the


appearance of text and manipulate colors. Those are
likely the most common actions you’ll take with CSS, but
it is much more powerful than that.
Y ou can place elements wherever you want on a page
without changing the underlying CSS. In Chapter 6 you
learned about using HTML to structure a page. Now it’s
time to learn how CSS can change the layout.

THE BOX MODEL


In Chapter 6, you were briefly introduced to the box
model. The simplest way to put it is that CSS treats every
HTML element as if it’s in its own box. By default, when
a browser renders a webpage, the boxes flow onto the
page in sequence as it encounters them in the code. This
is sometimes called normal flow.
FIGURE 15.1 shows an example from the New York
Times.
Figure 15.1 Elements outlined on the New York
Times homepage, illustrating the box model

For each element, you can control a number of


parameters:

Th e w idth a n d h eig h t of its box

Bor der color a n d th ickn ess a r ou n d th e box

Wh eth er or n ot th e bor der is v isible

Wh eth er th e box itself is v isible

Wh er e th e box fits in th e flow of elem en ts on th e pa g e

How m u ch spa ce is a r ou n d th e box (m a r g in s), a n d


a r ou n d th e con ten t w ith in th e box (pa ddin g )

Y ou can also change the position of an element in the


flow of a page by choosing whether to make it an inline
element or a block element. This can have an effect on
how much space is (or can be defined) around the box.

VIDEO 15.1

Demonstrating Flow
In this v ideo, y ou’ll see the dif f erent way s an element can be arranged, and how
changing the CSS af f ects the f low of a page.

The CSS display property


Using the display property, you can change the flow
of an element. These are the most common values:

block m a kes a n elem en t sta r t on a n ew lin e a n d ta ke u p


th e fu ll w idth of th e con ta in er (for m in g a block of
con ten t, if y ou w ill).

inline lea v es a n elem en t in its position in th e flow of


con ten t. It w ill n ot sta r t on a n ew lin e, a n d it w ill ta ke
u p on ly th e h or izon ta l spa ce it n eeds. Cer ta in pr oper ties,
like height a n d width, h a v e n o effect on in lin e
elem en ts.

inline-block is a h y br id of inline a n d block. Th e


elem en t w ill displa y in lin e bu t ta ke on th e pr oper ties of
a block, like h eig h t, w idth , a n d spa cin g .

none com pletely h ides th e elem en t a n d r em ov es it fr om


th e flow . It w ill on ly be v iew a ble in sou r ce code.

Tip
There’s another property, called visibility. If it’s set to hidden, users will not
be able to see the element, but it will still take up the same amount of space
on the page. It will not be removed from the flow.

Tip
There are several other display properties that are less common. Two you’ll
learn about in depth in Chapter 16 are flex and grid.

To set a link to display as a block-level element:


1. In y ou r sty le sh eet, ty pe th e selector y ou w a n t to ch a n g e. In
th is ex a m ple, u se a.
2. If y ou w a n t th e sty le to a pply to a specific cla ss, ty pe a per iod
follow ed im m edia tely by th e cla ss n a m e, th en a dd a left
cu r ly br a ce. Her e, u se .button {.
3. Ty pe th e pr oper ty y ou w a n t to a ssig n to th e selector . In th is
ca se, u se display: block;.
4. Ty pe } to close th e sty le decla r a tion .

This moves any link (<a> tag) of the class button from
inline to its own block (FIGURE 15.2).
Figure 15.2 This <a> tag of the class button now
sits on its own line.

Height and width


Unless you specifically define a height and width, they’ll
default to a size big enough to hold the content (with the
caveat that block-level elements are the full width of
their parent container). To define a specific size, you can
use the height and width properties. They accept the
same units you would use to measure text size: px, em,
rem, and %.

Tip
Using % will cause the targeted element to take up that percentage of the
parent container. So if the container is 100px and you define, say, a width of
50%, the target element will be 50px wide.

To set a specific height and width for an element:


1. In y ou r sty le sh eet, defin e th e elem en t to w h ich y ou w a n t to
a pply th e r u le, follow ed by a left br a ce. In th is ex a m ple, u se
aside {.
2. Ty pe width: follow ed by th e desir ed w idth . In th is ca se,
400px;.
3. Ty pe height: follow ed by th e desir ed h eig h t. In th is ca se,
200px;.
4. Ty pe } to en d th e sty le decla r a tion .

This gives you a 400x200 box for all aside elements


(FIGURE 15.3).
Figure 15.3 An aside element with a set width and
height. A border has been added to show the full
container.

Tip
You can also use the value auto for either height or width. This is especially
useful when resizing images. If you want images to be 600px wide, using a
height of auto will make sure the image maintains the correct aspect ratio.

Finally, you can set minimum and maximum values for


both height and width.
The minimum properties are min-width and min-
height. They say, “Do not drop the container’s size
below this value.” If you set min-width: 300px; the
container will always be at least 300px wide but can be
wider, depending on the content.

And max-width and max-height say, “Do not let a


container go beyond this size.” So max-height: 500px
means the container can be shorter than, but will never
be taller than, 500px.
Each of these can make sense depending on the context.
But the main thing to remember is that the height and
width properties are fixed. They will always be exactly
the size you define, no matter the size of the browser
window or parent container (FIGURE 15.4).
Figure 15.4 This element’s width has been set bigger
than the browser’s width, causing the content to go
beyond the user’s viewable window.

VIDEO 15.2

Adjusting Heights and Widths in Layout


Now that y ou know all about managing height and width, it’s time to put that
knowledge to the test. In this v ideo, y ou’ll set and adjust the widths and heights of
v arious elements to make ev ery thing line up nicely.

Using overflow
You may f ind y ourself in situations where setting a specif ic height or width causes
the box to break and text to f low outside of that box.
Luckily, the overflow property is there to help y ou. The two v alues that can help y ou
out here are:

hidden: Hides any content that goes bey ond the container.

scroll: Adds scroll bars to the container.


PADDING AND MARGINS
In Chapter 14, you learned how to adjust spacing for
text to make it more readable and how to add
whitespace when necessary. Y ou can do the same thing
with entire elements and everything they contain—text,
images, and otherwise.
As stated earlier, there are two ways to add spacing to an
element: around the outside of the whole box, which is
margin, and around the content inside the box, which is
padding. That, taken with height, width, and
border, creates the complete amount of space a block-
level element takes up (FIGURE 15.5).
Figure 15.5 How padding, margin, height,
width, and border affect a block-level element

Y ou can define padding and margin values using the


same units as those for height and width. Using a
single value for either property applies the same value to
all four sides of the element.

To add padding and margin to a paragraph:


1. In y ou r sty le sh eet, ty pe th e selector y ou w ish to ta r g et,
follow ed by a left cu r ly br a ce. In th is ca se, u se p {.
2. Ty pe padding: follow ed by th e v a lu e; th is ex a m ple u ses
20px;.
3. Ty pe margin: a n d th e v a lu e; h er e, u se 20px;.
4. Ty pe } to close th e decla r a tion .

This adds a little extra spacing to your paragraphs


(FIGURE 15.6).

Figure 15.6 The first image shows two paragraph


elements with neither padding nor spacing. The
second has both.

VIDEO 15.3

Building a Completely Styled Button


Now that y ou know how to turn links into blocks and add spacing, y ou can create a
real-looking button using only CSS. You’ll learn how in this v ideo.
Finer control over values
With both padding and margin, you’re not locked into
assigning a single value to the attribute for the entire
element. Y ou can define a different value for the left,
top, right, and bottom of each box. There are a few ways
to do it.
Y ou can explicitly define each side, as shown in TABLE
15.1.

Table 15.1 Padding and Margin Side Properties

Padding Margin

padding-left margin-left

padding-top margin-top

padding-right margin-right

padding-bottom margin-bottom

Y ou can also use a shorthand version, in which you set


the values for each of the four sides individually in a
single declaration:
Click h er e to v iew code im a g e

padding: [top] [right] [bottom] [left];


margin: [top] [right] [bottom] [left];

For each property the values are applied in clockwise


order around the element, starting from the top. Slightly
shorter would be:
Click h er e to v iew code im a g e

padding: [top/bottom] [left/right];


margin: [top/bottom] [left/right];
Here, you have two values instead of four, where the
first value sets the top and bottom spacing, and the
second value sets the left and right spacing.
Finally, there’s also a three-value declaration:
Click h er e to v iew code im a g e

padding: [top left/right bottom];


margin: [top left/right bottom];

Here, the first value is for the top spacing, the middle
value is for the left and right, and the last is for the
bottom.

Shorthand Properties
Shorthand properties are properties in CSS that combine sev eral dif f erent properties
into one. You’v e seen some, like border (which combines border-width, border-
style, and border-color), and padding and margin in this chapter.
They are a conv enient and generally cleaner way to write CSS when y ou want
unif ormity (f or example, when y ou want all borders to be the same color).
On the other hand, there are f actors y ou need to keep in mind when using shorthand
properties, particularly def ault v alues of properties and issues of inheritance.

To learn more about shorthand properties, check out this page at MDN:
dev eloper.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties.

Using margin: auto

Sometimes when you set a width, you might want to


center the container on the page. That’s very easy to do
using the margin property. Y ou can set margin to the
value auto, and it will calculate the width of the parent
container, subtract the width of your target element, and
distribute the leftover value evenly on both sides.

Say you have a wrapper class that has a width of


800px:

.wrapper {
width: 800px;
}

On most tablets and desktop devices, the width of the


window (and therefore, the entire website) will be more
than 800px, and your content will look like what you see
in FIGURE 15.7, where there is a lot of space to the
right of the container.
Figure 15.7 A fixed-width container (.wrapper)
without using margin: auto aligns the content all
the way to the left of the window.

Using the keyword auto with margin allows you to


automatically center that content in the middle of the
window.
Y ou can use the auto keyword in two ways: as the only
value for margin (margin: auto) or in conjunction
with a set top and bottom (margin: 30px auto).
Both cases result in horizontal centering. The latter also
includes a 30px margin before and after the container.

To center an element automatically with margin:


auto:
1. In y ou r sty le sh eet, ty pe th e selector y ou w ish to ta r g et,
follow ed by a left cu r ly br a ce. In th is ca se, u se .wrapper {.
2. On a n ew lin e, ty pe width:, follow ed by th e v a lu e. In th is
ca se, 800px;.
Settin g a w idth for th e con ta in er isn ’t str ictly n ecessa r y , bu t
w ith ou t it y ou w ill n ot see th e r esu lts of u sin g th e auto
key w or d.
3. On a n ew lin e, ty pe margin:, th en th e v a lu es, in clu din g
v a lu es for option s like top or bottom m a r g in s. In th is ca se,
ty pe 30px auto;.
4. On a n ew lin e, ty pe }.

Y our full ruleset looks like this:

.wrapper {
width: 800px;
margin: 30px auto;
}

That results in a div with the class wrapper being


center aligned on a page (FIGURE 15.8).

Figure 15.8 Centering a container using margin:


auto

ELEMENT FLOW
By default, elements flow onto the page in the order they
appear in the HTML, depending on whether they are a
block or inline element. FIGURE 15.9 shows how the
elements on a page naturally flow, with block-level
elements outlined. Y ou can see that block-level elements
take up the entire width of the page and dictate most of
the natural flow. Links and other text formatting fall in
line with those blocks (like the links in the unordered
list).

Figure 15.9 This fantastic screenshot shows this page


from Chris Coyier: codepen.io/chriscoyier/full/JpLzjd.

However, there are a few ways to change the flow of


elements. Y ou might want to do this to pull out certain
content (like a quote or an aside), draw attention to an
image, or even reorder elements when viewing the site
on a smaller device.
The most common way to change the flow of HTML
elements is to use the float property.
CODE 15.1 The CSS used to style the page in Figure 15.10

main {
width: 800px;
margin: 0 auto;
}
aside {
border: 1px solid #333333;
padding: 30px;
width: 200px;
float: right;
}

Using floats
The float property takes an element out of its normal
flow and places it to the right or left inside the container:

aside {
float: right;
}

This moves the aside element to the right and lets


everything else flow around it (FIGURE 15.10). Y ou
can see the code in CODE 15.1.

Figure 15.10 An aside that floats to the right of the


rest of the content

Note that the floated element will be surrounded by any


elements below it, so if you want it to appear in the top
of a container, it will have to be the first element.
Y ou can even use float to create a grid of elements.
Floating all elements of a particular type takes them out
of the normal flow and lines them up next to each other.
Before the creation of the layout modules Flexbox and
CSS Grid (which you’ll learn about in Chapter 16), this is
how many web designers created column-based layouts.

VIDEO 15.4

Making a Simple Two-column Layout with Floats


While there are newer way s to create lay outs in CSS, using f loats is still pretty
popular. In this v ideo, y ou’ll learn how to do that, and all the nuances of doing it
correctly.
To create a grid layout with floats:
1. In y ou r sty le sh eet, ty pe th e selector y ou w ish to ta r g et,
follow ed by a left cu r ly br a ce. Th is ex a m ple ta r g ets
pa r a g r a ph s, so u se p {.
2. Ty pe float:.
3. Ty pe left; to for ce th e elem en t to floa t on th e left side of its
con ta in er .
To for ce th e elem en t to floa t on th e r ig h t side, y ou w ou ld u se
th e v a lu e right.
4. Ty pe margin: to set th e spa cin g betw een th e elem en ts. For
th is ex a m ple, u se 15px;.
5. Ty pe width: to set th e w idth of ea ch elem en t. Th is ex a m ple
u ses 300px;.
6. Ty pe } to close th e sty le decla r a tion .

This makes the paragraphs flow onto the page in a grid


(FIGURE 15.11).

Figure 15.11 A grid of paragraphs achieved using the


float property

Clearing floats
While this can work, it can also cause havoc for any
elements in the normal flow. Elements can end up in
unexpected places to work their way around floated
elements. And although there are better ways to achieve
a grid (as you’ll see in Chapter 16), you could always use
the clear property, which tells the element to place
itself below any floated content:
.next-section {
clear: left;
}

Other values for this property include right and both.

Tip

Using the clear property for layout is sometimes referred to as the clearfix.
You might even see a class named clearfix that’s designed for this very
purpose.

Using the position property


Another way to place elements and containers precisely
is by using the position property. It accepts several
values, which I’ll list in a moment.
This property is often accompanied by a set of properties
that position elements in specific areas of the window or
container: left, right, top, and bottom. These all
accept the normal units (px, em, rem, %), and they all
have slightly different meanings depending on the value
of position. Here are the values for position, and
positioning properties:

static: Th is is th e defa u lt v a lu e. Th er e is n o specia l


position in g .

relative: Pla ces th e con ta in er ba sed on its n or m a l


position . Th e dir ection a l pr oper ties w ill m ov e th e
con ta in er a w a y fr om its n or m a l position .
So left: 50px m ov es th e con ta in er to th e r ig h t by 5 0
pix els, sim ila r to margin.

fixed: Th e con ta in er is in a fix ed position on th e pa g e, so


n o m a tter w h a t pa r t of th e pa g e is bein g displa y ed to th e
u ser , th e con ta in er w ill be in th e sa m e spot.
Th e dir ection a l pr oper ties in th is in sta n ce a r e ex a ct
coor din a tes; left: 0; top: 0; m ea n s th e con ta in er
w ill be a t th e left edg e a t th e v er y top of th e w in dow .

absolute: Th e con ta in er is position ed in a fix ed position


in its pa r en t con ta in er .
Dir ection a l pr oper ties w or k th e sa m e w a y a s th ose for
th e fixed position .
sticky: Th e con ta in er is position ed r ela tiv ely (a s in th e
n or m a l flow ) u n til th e u ser r ea ch es a specific scr oll
position . Th en it sticks in pla ce on th e scr een .
For ex a m ple, top: 0 position s th e elem en t r ela tiv ely in
th e n or m a l flow u n til th e pa g e is scr olled a n d th er e a r e
zer o pix els betw een th e elem en t’s top edg e a n d th e
v isible a r ea of th e w ebpa g e. Bey on d th a t th r esh old, th e
elem en t beh a v es a s if it u sed fix ed position in g a n d w ill
be fix ed to zer o pix els fr om th e top.

To get a better idea of how each of these work, check out


Video 15.5.

VIDEO 15.5

Demonstrating the position Property


Visualizing how the position property works, ev en with the help of screenshots, can
be tough. This v ideo goes through all the properties and v alues and shows how they
work.

To make a sticky sidebar:


The starting markup for this task is listed below. Since
there’s no HTML5 element specifically for “wrapping”
other elements (from a semantic meaning standpoint),
it’s common practice to use the <div> element with a
wrapper class:

<div class="wrapper">
<aside>
...
</aside>
<main>
...
</main>
</div>

1. In y ou r sty le sh eet, ty pe .wrapper {.


2. Ty pe width: 800px;.
3. Ty pe margin: 30px auto;.
4. Ty pe }.
5. Ty pe main {.
6. Ty pe width: 500px;.
7. Ty pe }.
8. Ty pe aside {.
9. Ty pe width: 260px;.
10. Ty pe padding: 15px;.
11. Ty pe float: right;.
12. Ty pe position: sticky;.
13. Ty pe top: 0;.
14. Ty pe }.

This code produces a two-column layout with a sticky


sidebar. Y ou can also add a background and border to
aside to distinguish it a bit (FIGURE 15.12). Y ou can
see the code in CODE 15.2 and 15.3.

Figure 15.12 A two-column layout with a sticky


sidebar

CODE 15.2 The HTML code used in Figure 15.12


Click h er e to v iew code im a g e

<div class="wrapper">
<aside>
This is one of 56 short stories
→written about Sherlock Holmes by
→Sir Arthur Conan Doyle. It was
→published in 1891.
</aside>
<main>
<p>“My dear fellow,” said Sherlock
→Holmes as we sat on either
→side of the fire in his lodgings
→at Baker Street, “life is
→infinitely stranger than
→anything which the mind of
→man could invent. We would not
→dare to conceive the things
→which are really mere
→commonplaces of existence.
→If we could fly out of that
→window hand in hand, hover
→over this great city, gently
→remove the roofs, and peep in
→at the queer things which
→are going on, the strange
→coincidences, the plannings,
→the cross-purposes, the
→wonderful chains of events,
→working through generations,
→and leading to the most outré
→results, it would make
→all with its conventionalities
→and foreseen conclusions most
→stale and unprofitable.”</p>

<p>“And yet I am not convinced of it,” I


answered. “The cases which come to light
in the papers are, as a rule, bald enough,
and vulgar enough. We have in our police
reports realism pushed to its extreme
limits, and yet the result is, it must be
confessed, neither fascinating nor
artistic.”</p>
</main>
</div>

CODE 15.3 The CSS code used in Figure 15.12


Click h er e to v iew code im a g e

.wrapper {
width: 800px;
margin: 30px auto;
}

main {
width: 500px;
}

aside {
width: 260px;
padding: 15px;
float: right;
position: sticky;
top: 0;
background:rgba(0,0,0,0.085);
border: 1px solid #333333;
}

p:nth-of-type(1) {
line-height: 1.5em;
letter-spacing: 0.1em;
word-spacing: 0.2em;
}

CREATING LAYERS AND OVERLAPPING


ELEMENTS
Although taking elements out of the natural flow can
create interesting layouts for your content, you can run
into situations where content overlaps and becomes
unreadable. For example, if you had not set the width
property on the main div in the previous task, your
users would have run into a problem (FIGURE 15.13).
Because we’ve fixed the position of the aside, the browser
is essentially saying, “Keep the aside in this spot, no
matter what the rest of the flow looks like.” That means
when the user scrolls, the main text overlaps the aside.

Figure 15.13 Overlapping elements as a result of


positioning

CSS has a fix for that: the z-index property. Y ou can


think of z-index as a layer or stacking property, where
the value is an integer. The closer the integer is to 0, the
“lower” on the page the element is (FIGURE 15.14).
Y ou can also think of elements with a lower z-index as
being “behind” elements with a higher z-index.
Figure 15.14 A visualization of what z-index
represents on a webpage

A ruleset that uses z-index looks something like this:

aside {
position: fixed;
top: 0;
z-index: 10;
}

Tip
z-index works only if the element has a position other than static.
Tip
Choosing z-index values in multiples of 10 or 100 is a good convention to
follow. That gives you some wiggle room on bigger projects, where you
might later realize you need to add an in-between value to existing values.

CREATING AN OVERLAY USING Z - I N D E X


One practical example of using z-index is to create a
piece of content that should be shown in front of the rest
of the content. Y ou see this with popups asking you to
join mailing lists, for example.
In this task, you will learn the basics of how to do that.
In the real world, you might make the overlay
dismissible with a bit of JavaScript, but you will clearly
see how z-index works.

To create an overlay using z-index:

The markup being styled will be the following:


Click h er e to v iew code im a g e

<div class="overlay">
<h3>This is an important alert!
→</h3>
</div>
<header>
<h1>A Case of Identity</h1>
</header>
<main>
(content goes here)
</main>

1. In y ou r sty lesh eet, fir st ty pe th e elem en t y ou w a n t to a pply


th e sty les to, follow ed by a left cu r ly br a ce. In th is ca se,
.overlay {.
2. Now set th e position of th e elem en t to a bsolu te by ty pin g , on
a n ew lin e, position: absolute;.
3. Sin ce th e elem en t is a bsolu te, y ou ca n n ow u se position a l
pr oper ties to m ov e it. Mov e it dow n th e pa g e a little bit. On a
n ew lin e, ty pe top: 10%;.
4. Mov e th e elem en t in fr on t of a ll oth er elem en ts u sin g z-
index. Sin ce th e defa u lt z-index is 0, on a n ew lin e ty pe z-
index: 1000;.
Th is w ill m a ke su r e th e ov er la y is a bov e th e r est of th e
con ten t—a s lon g a s n oth in g h a s a z-index ov er 1 000.
5. Str ictly so y ou ca n m or e ea sily see th e r esu lt, a pply a
ba ckg r ou n d color to th e elem en t. On a n ew lin e, ty pe
background: #cfcfcf;.
6. You ca n a lso cen ter th e tex t. On a n ew lin e ty pe text-
align: center;.
7. Fin a lly , a ddin g som e pa ddin g so it sta n ds ou t a bit m or e. On
a n ew lin e, ty pe padding: 40px;.
8. On a n ew lin e, ty pe }.

This results in a block of text that is layered on top of the


main page (FIGURE 15.15).

Figure 15.15 An overlay created using position:


absolute and z-index.

VIDEO 15.6

Creating a Pricing Table


In this v ideo, y ou make a three-column pricing table using the methods y ou’v e
learned in this chapter.

A NOTE ABOUT CREATING LAYOUTS


In recent years, great strides have been made in creating
layouts with CSS. The practice of laying out elements on
a webpage moved from tables, in HTML, to floating
elements and clearing them using CSS. There are many
frameworks designed to help you to create beautiful grid
layouts. A framework is a set of structured files (HTML,
CSS, and maybe JavaScript) that give you a head start
on creating websites. See the sidebar “Using CSS
Frameworks” to learn more.
But now, CSS Grid and Flexbox (two suites of layout
properties you’ll see in Chapter 16) have much wider
browser support, so they should be used instead of
floating and clearing elements. They allow for code that
is semantic, much cleaner, and easier to support. The
techniques you saw in this chapter—floats, positioning,
and changing the default flow—still have their place in
web design, though.

At this point, you have enough tools in your toolbox to


create nice-looking layouts. In Video 15.6, you put most
of that to the test by creating a pricing table.

Using CSS Frameworks


CSS f rameworks—sets of pref abricated sty les that help y ou f ast-track dev elopment
—are hugely helpf ul because streamlining the web design workf low is not just about
lay out but also about using a set of common elements.
Plus, the best f rameworks continue to be updated to support new methods.
Bootstrap, a v ery popular CSS f ramework, supports Flexbox f or lay outs now.

In this article, Rachel Andrews weighs the pros and cons of using a f ramework:
www.smashingmagazine.com/2018/11/css-f rameworks-css-grid/.
Two popular f rameworks I recommend are Bootstrap (getbootstrap.com) and
Foundation (get.f oundation).

WRAPPING UP
Y ou know all about how to change the default flow of a
page and the elements/containers on it. Y ou’ve learned
about common methods like floating (and clearing those
floats), changing the position of elements, and z-index.

Y ou can probably imagine that you’ll run into a lot of


fringe cases when you try to make these properties work
for complex layouts—which is why frameworks became
popular in the first place. But CSS has solved that with
two important new systems: CSS Grid and Flexbox.
16

Layouts with CSS Grid and


Flexbox
In This Chapter

Modern Solutions for an Important Problem


Using Flexbox

Using CSS Grid Layout


Browser Support

Wrapping Up

In the last chapter, you learned the finer points of how


the box model can be styled, and some of the longer-
standing methods for manipulating layout.
But new tools have been introduced in CSS to give you
better control over your markup and to give it more
semantic meaning. Those tools are the CSS Grid Layout
Module and the CSS Flexible Box Layout Module, known
more familiarly as CSS Grid and Flexbox. In this
chapter, you’ll learn what they are, how they work, and
when to use each.

MODERN SOLUTIONS FOR AN


IMPORTANT PROBLEM
Part of the reason Flexbox and CSS Grid (or simply
Grid) have emerged is because they are a modern
solution to an important problem: creating flexible
layouts that work properly on different screen sizes.
With the advent of responsive web design (RWD),
floating elements to create column layouts revealed a
critical bug that also affected SEO: you could not control
the stacking order.
That means if you float the aside element, as in
Chapter 15, that element needs to go above the main
content. Search engines will prioritize the aside, and if
you stack the content, the aside will always be first
(Video 16.1).

VIDEO 16.1

Stacking Order
In this v ideo, y ou’ll see the stacking order of a multicolumn lay out as the screen gets
smaller, using simple f loats f or lay outs.

CSS Grid vs. Flexbox: Which should you use?


This chapter shows you both CSS Grid and Flexbox, but
it’s good to know what the difference is so that you can
keep it in mind moving forward.

The most common answer to this question is that


Flexbox organizes content in one dimension—by rows or
columns. CSS Grid organizes content in two dimensions
—rows and columns.
Both are well supported by browsers at this point, as
these tables at caniuse.com demonstrate (FIGURES
16.1 and 16.2).

Figure 16.1 Browser support for Flexbox


Figure 16.2 Browser support for CSS Grid

Responsive Web Design


With the emergence and increasing popularity of mobile dev ices, the importance f or
making websites work on small screens was a cataly st f or the responsiv e web design
(RWD) mov ement. Among other things, RWD ensures that y our website looks good
no matter what dev ice it’s being v iewed on.
With a f eature of CSS called media queries, which y ou’ll learn about in Chapter 17,
y ou can create CSS rules f or y our lay out based on the size of the screen.

RWD prov ides a bev y of benef its, chief among which are:

You don’t need a separate site f or mobile dev ices.

Your site loads f aster.

Your lay outs are optimized.

And both give you similar results quickly (FIGURES


16.3 and 16.4).

Figure 16.3 A simple Flexbox example


Figure 16.4 A simple CSS Grid example

What you’ll quickly find is that CSS Grid is a bit more


granular. Before we dig into that, let’s take a look at
Flexbox.

Resources Galore!
This chapter introduces y ou to both Flexbox and CSS Grid, but there is a lot to know,
so it is not comprehensiv e. Here are some f antastic resources and ev en some
interactiv e guides to help y ou though:

CSS-Tricks’s A Complete Guide to Flexbox: css-tricks.com/snippets/css/a-


guide-to-f lexbox

CSS Tricks’s A Complete Guide to Grid: css-


tricks.com/snippets/css/complete-guide-grid

Grid by Example: gridby example.com

Flexbox Froggy : f lexboxf roggy.com

Grid Garden: cssgridgarden.com

USING FLEXBOX
We start by setting the display property to the value
flex, which will lay out the element and its children
according to the CSS Flexible Box Layout Module,
known by its close friends as Flexbox.
It essentially enables you to use a set of properties that
also use the word flex in the parent and child elements.

All of these properties have default values, so you will see


results as soon as you use the display property to
enable Flexbox. Let’s say you have a set of paragraphs
inside a div container (FIGURE 16.5).

Figure 16.5 Paragraphs pre-Flexbox

Tip
Flexbox commonly refers to the feature in CSS. There is no property called
“flexbox.”

To enable Flexbox on an element:


1. Ty pe th e elem en t or selector y ou w a n t to ta r g et. In th is ca se,
it’s div {.
2. On th e n ex t lin e, ty pe display: flex;.
3. On th e n ex t lin e, ty pe } to close th e sty le decla r a tion .

This gives you FIGURE 16.6 (some styling has been


added so that you can better see the effects).
Figure 16.6 Paragraphs with Flexbox applied

Y ou might notice that the paragraphs are not equal


width and that they’re very cramped, with all six on the
same line/row.
That’s because display: flex takes all the child
elements and converts them into columns of content. In
fact, they don’t even need to be the same type of
element. Here’s another example, with more than just
paragraph elements (FIGURE 16.7).

Figure 16.7 Flexbox applied to all children

Luckily, this doesn’t extend to all descendants, just


children. So without much fuss, you can get a pretty
good two- or three-column layout working.

How width works in Flexbox


By default, display: flex takes all child elements
and evenly distributes them into columns. But there are
a few ways to define column widths, which Flexbox will
take into account.

The first is simply by defining the width property.


Flexbox will respect a defined width (meaning it will use
the defined width instead of overriding it). Because
Flexbox lends itself well to multiple screen sizes
(meaning the overall width of your container will
change), this book uses percentages. But you can use
any unit you want.
Later in the chapter, you will learn about an even better
way to define the width of child containers, called flex-
basis, so keep an eye out for that!

In the next task, the goal is to take the provided markup


and make a two-column layout where the <article>
element is 70 percent of the width of the <main>
container, with the <aside> occupying the other 30
percent.

To create a two-column layout with Flexbox:


Here is the starting markup:

<main>
<article>
...
</article>
<aside>
...
</aside>
</main>

1. In y ou r sty le sh eet, ta r g et th e elem en t y ou w a n t to u se


Flex box on . In th is ca se, ty pe main {.
2. On a n ew lin e, ty pe display: flex;.
3. On a n ew lin e, ty pe } to close th e sty le decla r a tion .
4. Ta r g et th e ch ildr en of th e elem en t y ou ’r e u sin g Flex box on .
Ty pe main article {.
5. On a n ew lin e, ty pe width: 68%;.
Sin ce th e width pr oper ty doesn ’t ta ke in to a ccou n t pa ddin g ,
y ou n eed to a ccou n t for it so y ou don ’t br ea k th e m a in
con ta in er w ith ov er flow in g elem en ts. Beca u se of th a t,
su btr a ct 2 per cen t fr om th e ov er a ll 7 0 per cen t w idth y ou
w a n t th e <article> elem en t to ta ke u p.
6. On a n ew lin e, ty pe padding: 2%;.
7. On a n ew lin e, ty pe }.
8. Now ta r g et th e oth er ch ild elem en t. On a n ew lin e, ty pe main
aside {.
Ju st a s w ith <article>, to pr ev en t th e con ten t fr om
ov er flow in g th e con ta in er , su btr a ct th e pa ddin g fr om th e
w idth of th e elem en t.
9. On a n ew lin e, ty pe width: 28%;.
10. On a n ew lin e, ty pe padding: 2%;.
11. On a n ew lin e, ty pe }.

This gives you a two-column layout that stacks properly


(FIGURE 16.8).

Figure 16.8 A two-column layout with flex

Wrapping elements
If you want child elements (also known as flex items) to
naturally move to a new row so they maintain their
defined widths instead of being forced onto one line, use
the flex-wrap property. It has three values:

nowrap is th e defa u lt v a lu e. It for ces a ll flex item s on to


on e lin e. If n o w idth s for flex item s a r e defin ed, ea ch
item w ill ta ke u p a w idth equ a l to th a t of its pa r en t. If
w idth s a r e defin ed, nowrap m a y ca u se ov er flow .

wrap br ea ks th e flex item s u p in to m u ltiple lin es.

wrap-reverse beh a v es like wrap bu t r ev er ses th e or der


of th e flex item s.

Here’s a simple example of the syntax:

main {
display: flex;
flex-wrap: wrap;
}

With this property, you will also need to apply a width


(or max-width) to the child elements. That’s because if
they are block elements, they’ll naturally take up the full
width of the parent container.

To create a three-column layout with flex-wrap:

The markup is six <p> tags inside a <main> element:


<main>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
</main>

VIDEO 16.2

Using flex-item Properties


Flexbox comes with a set of properties to apply to items. In this v ideo, y ou’ll learn
how to use them, instead of width, to create the two-column lay out.

1. In y ou r sty le sh eet, ty pe main {.


2. On a n ew lin e, ty pe display: flex;.
3. On a n ew lin e, ty pe flex-wrap: wrap;.
4. On a n ew lin e, ty pe }.
5. On a n ew lin e, ty pe main p {.
6. On a n ew lin e, ty pe width: 30%;.
7. On a n ew lin e, ty pe padding: 1.5%;.
Th is is so th a t th e tota l left/r ig h t pa ddin g is 3 per cen t,
g iv in g th e tota l colu m n w idth 3 3 per cen t. Th is div ides th e
<main> elem en t n ea tly in to th r ee equ a l colu m n s.
8. Ty pe }.

This gives you even columns split across two rows


(FIGURE 16.9).
Figure 16.9 Using flex-wrap to make a three-
column layout

Tip
When you create columns using the float property, you need to use the clear
property to make sure elements line up properly under the floated area. Note
that you don’t need to use clear on any of the elements that use Flexbox. The
Flexbox properties are designed to create columns and position multiple
pieces of content.

Y ou can also set a more dynamic width that will take


other parameters (like margins and spacing) into
account by using the flex-basis property, which
allows you to set the basic size of the flex item. It accepts
any unit that width accepts (px, em, %, etc.).

The flex-basis property also accepts a number of


keywords, but most don’t have browser support. To see a
list of them and how they work, view this page in
Firefox: developer.mozilla.org/en-
US/docs/Web/CSS/flex-basis.

Aligning elements
There are even more clever ways you can use Flexbox
properties to align and space columns without the need
to do mental math to figure out the amount of padding
needed. One way is for horizontal alignment, and one is
for vertical.
In the last example, you used the padding property to
get evenly spaced columns. But there is a better way: the
justify-content property. Before jumping into that,
though, there’s another property you should know
about: flex-direction.

The flex-direction property tells the browser how to


align the items. It has four values:

row (th e defa u lt) displa y s item s left to r ig h t.

row-reverse displa y s item s r ig h t to left.

column displa y s item s v er tica lly , top to bottom .

column-reverse displa y s item s v er tica lly , bottom to


top.

Tip
If the browser is set to display text from right to left (as required by some
languages, such as Hebrew and Arabic), HTML elements flow onto the page in
the same direction. Using either row or row-reverse with flex-direction will
reverse the flow. You can also set the direction with the dir attribute in HTML
or the direction property in CSS.

To convert a row of items to a column:


1. In y ou r sty le sh eet, ty pe main {.
2. Ty pe display: flex;.
3. Ty pe flex-direction: column;.
4. Ty pe }.

This gives you a single, contained column of content


(FIGURE 16.10). To better demonstrate how the
property works, I applied a 45 percent width to the child
elements.
Figure 16.10 flex-direction in action

VIDEO 16.3

Using flex-basis, flex-flow, and justify-content


Flexbox allows y ou to easily do some clev er things with y our columns. In this v ideo,
y ou’ll see three helpf ul properties in action.
Tip
You can use flex-flow as shorthand for the flex-direction and flex-wrap
properties. You would write the rule like this: flex-flow: [flex-direction-
value] [flex-wrap-value].

With the justify-content property, you are able to


distribute the content evenly or to one side. The property
has several values, some of which are listed below, and
you can see them demonstrated in Video 16.3. The
values distribute the content according to the flow
established by flex-direction:

flex-start (th e defa u lt): Item s a r e pla ced a t th e


beg in n in g of th e con ta in er (sim ila r to left a lig n m en t).

flex-end: Item s a r e pla ced a t th e en d of th e con ta in er


(sim ila r to r ig h t a lig n m en t).

center: Item s a r e cen ter ed w ith in th e pa r en t.

space-between: Item s a r e ev en ly distr ibu ted w ith in th e


pa r en t, w ith n o spa ce betw een th e item s a n d th e edg e of
th e pa r en t con ta in er .

space-around: Item s a r e ev en ly distr ibu ted w ith in th e


pa r en t, w ith equ a l spa ce betw een th em (bu t n ot ev en ly
spa ced betw een th e edg es).

space-evenly: Item s a r e distr ibu ted w ith in th e pa r en t,


w ith equ a l spa ce betw een th em a n d th e edg es.

To create evenly spaced columns without


padding:
1. In y ou r sty le sh eet, ty pe main {.
2. Ty pe display: flex;.
3. Ty pe justify-content: space-evenly;.
4. Ty pe flex-wrap: wrap;.
5. Ty pe }.
6. Ty pe main p {.
7. Ty pe flex-basis: 30%;.
We’r e u sin g flex-basis h er e in stea d of width beca u se it’s a
little sm a r ter . It ca n con tr ol w idth or h eig h t, ba sed on flex-
direction.
8. Ty pe }.
This gives you the same results seen in Figure 16.9,
without the need for the additional padding
declaration.

flex-grow, flex-shrink, and flex


flex-basis is often used with flex, which is a
shorthand property for flex-grow, flex-shrink, and
flex-basis. These are applied to the flex items.

flex-grow is how much each item should grow


relative to the remaining space in the parent container, if
necessary, and is represented as a single unit. So flex-
grow: 2 says, “This item should take up twice as much
of the remaining space as the other items if it needs to
grow.”
Conversely, flex-shrink is how much each item
should shrink relative to the space in the parent
container. So flex-shrink: 2 says, “This item should
take up half as much space as the other items if it needs
to shrink.”

These are combined into flex, which is the


recommended property for setting flex-item sizes.
Taking the example in the previous task, we might
instead write:

main {
flex: 1 1 30%;
}

where the values represent flex-grow, flex-shrink,


and flex-basis, respectively.

However, you could write the rule by omitting flex-


shrink:

main {
flex: 1 30%;
}

Using flex allows the browser to intelligently determine


the other values and is smart enough to know how to
use the values provided.

Vertical alignment
Y ou can use Flexbox to align elements vertically. While
you can use vertical-align in specific instances,
which you saw in Chapter 13, you may not always get
the results you expect. The align-items property
improves upon vertical-align.

For flex items, use the align-items property, which


can have the following values:

stretch (th e defa u lt) fills th e fu ll h eig h t of th e


con ta in er w ith th e con ten t.

flex-start sta r ts con ten t a t th e top of th e con ta in er .

flex-end sta r ts th e con ten t a t th e bottom of th e


con ta in er .

center cen ter s th e con ten t v er tica lly in th e con ta in er .

baseline a lig n s item s on th e “ ba selin e” of th e con ten t—


w h er e th e tex t sits.

The align-items property accepts many more values,


which are listed and described at
http://developer.mozilla.org/en-
US/docs/Web/CSS/align-items#Syntax.

Y ou can see these values in action in Video 16.4.

VIDEO 16.4

The align-items Property in Action


Much as with justify-content, it’s better to see the align-items property in action.
In this v ideo, y ou’ll see the ef f ects of each v alue on real content.

To create a set of bottom-aligned columns:


1. In y ou r sty le sh eet, ty pe main {.
2. Ty pe display: flex;.
3. Ty pe align-items: flex-end;.
4. }.

Y our result will look like FIGURE 16.11. I applied


additional styles to the children to highlight the changes.
Figure 16.11 Bottom-aligned columns using Flexbox

These properties and examples will give you a great start


to using Flexbox. Check out the sidebar “Resources
Galore!” to learn more and go even deeper.
But now it’s time to look at a way to do layouts that’s
even more flexible: CSS Grid.

USING CSS GRID LAYOUT


CSS Grid Layout (or Grid, as it’s more commonly
known) also requires the use of the display property,
but you’ll need to use a second property: grid-
template-columns. This tells the browser how many
columns to create and how wide they should be. If you
want three equal-width columns, the code looks like this:
Click h er e to v iew code im a g e

main {
display: grid;
grid-template-columns: 30% 30% 30%;
}

That results in FIGURE 16.12.

Figure 16.12 Paragraphs with Grid applied

Y ou can also space them out a bit using grid-gap,


which works similarly to padding, except the two
values are for row and column spacing, respectively:
Click h er e to v iew code im a g e

main {
display: grid;
grid-template-columns: 30% 30% 30%;
grid-gap: 10px 20px;
}

If there’s one value (grid-gap: 15px), it’s applied to


both rows and columns.

Tip
You can use the grid-template-rows property to set up rows in your Grid
layout, similar to the way you use grid-template-columns to create columns.

Tip
An entire book could be written about Grid—and it has been: Rachel
Andrew’s The New CSS Layout (abookapart.com/products/the-new-css-
layout).

Tip
The same rules for children and descendants that apply for Flexbox apply for
Grid.

To create a two-column layout with Grid:

Here is the starting markup:

<main>
<article>
...
</article>
<aside>
...
</aside>
</main>

1. In y ou r sty le sh eet, ty pe main {.


2. Ty pe display: grid;.
3. Ty pe grid-template-columns: 68% 28%;.
4. Ty pe grid-gap: 15px;.
5. Ty pe }.
This gives you a nice two-column layout (FIGURE
16.13).

Figure 16.13 A two-column layout with Grid

Using the fr unit


Y ou might have noticed in the last task that once again,
some weird math was required to make sure everything
fit properly in the container. But CSS Grid introduces a
much, much better way to do it: the fr (fractional) unit.
Here’s an example:
Click h er e to v iew code im a g e

grid-template-columns: 1fr 2fr 1fr;

The fr unit is a single integer measurement that


basically reads like a recipe: “This column should be 1
part of the leftover (or available) space, this column 2
parts, and the last column should be 1 part of the leftover
space.”
The fantastic thing about the fr unit is that it takes into
account all space already taken up, like padding and
grid-gap. That means no mental math! Here’s the new
ruleset for main, with a two-column layout:
Click h er e to v iew code im a g e

main {
display: grid;
grid-template-columns: 2fr 1fr;
grid-gap: 15px;
padding: 15px;
}

This gives you a clean, evenly spaced set of columns


(FIGURE 16.14).
Figure 16.14 A two-column layout using fr units

Creating Grid templates


Another truly fantastic feature of Grid is the ability to
define templates right in the CSS. Y ou’ll get a quick
explanation here, but for a more in-depth look, check
out Video 16.5.
Here’s an example (in HTML markup and CSS
statements) that you can work from. The HTML defines
three principal elements in the class wrapper (CODE
16.1).

And now the CSS for these elements (CODE 16.2).


The first set of rules (for header, main, and aside)
does something really important here: it tells the CSS
how these elements will be referenced by name in the
Grid template using a property called grid-area. This
property allows you to reference the selector by a
friendlier name in the property grid-template-
areas.

In the rule for .wrapper, the differentiator from other


code examples in this chapter is the use of grid-
template-areas, which allows you to reference the
names assigned by grid-area and define what
columns and rows each grid-area should span. Note
that grid-template-areas does not assume the
grid-area names will match the HTML elements or
selectors. Any non-numeric string can be used. For
example, note that I assigned the name sidebar to the
aside element.

Because this is a three-column grid (as we established


with the grid-template-columns property), grid-
template-areas shakes out like this:

Ea ch lin e is a r ow .

Ea ch str in g is a cell/colu m n in th e g r id.

VIDEO 16.5

Grid Templates
In this v ideo, y ou’ll get an in-depth look at def ining and using Grid templates.

CODE 16.1 The HTML

<div class="wrapper">
<header>
...
</header>
<main>
...
</main>
<aside>
...
</aside>
</div>

CODE 16.2 The CSS


Click h er e to v iew code im a g e

header {
grid-area: header;
}
main {
grid-area: main;
}
aside {
grid-area: sidebar;
}
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-areas:
"header header header"
"main main sidebar";
grid-gap: 20px;
width: 900px;
margin: 0 auto;
}
VIDEO 16.6

Aligning Grid Elements


You can align elements in Grid v ery similarly to how y ou would do so in Flexbox. This
v ideo runs through those examples.

What this says is, “On the first row, the header grid
area should take up all three columns. On the second
row, main should take up the first two columns, with
sidebar taking up the last.” The result is something like
FIGURE 16.15.

Figure 16.15 Our previous two-column example,


now using Grid templates

As you can imagine—and as you’ll see in Video 16.5 and


Chapter 17—this is a powerful way to define flexible
layouts for the content.

Tip
If you want to leave a column or cell blank, use a period (.).

BROWSER SUPPORT
The next important consideration when using CSS is
browser support. In Chapter 10, you learned about
caniuse.com and the fact that some browsers are faster
to implement new features than others. That’s even
more evident with CSS than with HTML. There is
greater disparity among browsers as to which features
are implemented and how they are implemented.
In FIGURE 16.16 you can see that with the most
recently available version of each major browser
(excluding Internet Explorer 11, as development has
shifted to Microsoft Edge), there’s a mixed bag of
support, from not supported and partial support to fully
supported.

Figure 16.16 The caniuse.com table showing


browser support of recent CSS features

Y ou might also notice the boxes with text in the upper-


right corner of some cells. Those are called vendor
prefixes.

Using Prefixing Tools


There are loads of tools to help y ou automatically add the pref ixes y ou need, so y ou
don’t need an ency clopedic knowledge of which pref ixes to use and when:

CSS-Tricks’s writeup: css-tricks.com/how-to-deal-with-v endor-pref ixes/

Autopref ixer: autopref ixer.github.io/

Should I Pref ix: shouldipref ix.com/

You can also use a CSS preprocessor like Sass, which y ou’ll learn about in Chapter
20.

VIDEO 16.7

Prefixes in Action
In this v ideo y ou’ll see how pref ixes af f ect dif f erent CSS properties, adding support
f or new and experimental f eatures.

Vendor prefixes
Vendor (or browser) prefixes are vendor-specific CSS
properties that can be used for experimental or beta
features. Prefixes are used for a few reasons:

Th ey don ’t u se a n y specific pr oper ty fr om th e CSS spec.


In stea d, th ey u se a “ w or kin g copy ” of som e pr oper ty . For
ex a m ple, th er e’s a pr oper ty ca lled transition, w h ich
m ig h t h a v e a w or kin g , bu t n ot fin a lized, defin ition .
Pr efix es a llow br ow ser s to im plem en t th eir v er sion of
transition ba sed on th e w or kin g spec.

Th ey a llow w eb desig n er s to u se fea tu r es of CSS th a t a r e


im plem en ted in som e br ow ser s w ith ou t w or r y in g th ey
w ill br ea k th e w ebsite in br ow ser s th a t don ’t su ppor t
th a t fea tu r e.

On ce th e CSS pr oper ty is fu lly im plem en ted, th e


pr efix ed pr oper ty is ig n or ed a n d its pr esen ce doesn ’t
br ea k th e site. Th a t m ea n s pr efix es keep w ebsites
ba ckw a r d a n d for w a r d com pa tible. Ev en so, y ou sh ou ld
clea n u p old pr efix es w h en th ey ’r e n ot n eeded.

Tip

At the time of this writing, vendor prefixes are still common practice, but as
noted on MDN’s web documentation, browsers are “working to stop using
vendor prefixes for experimental features.” One reason is to prevent the use
of highly experimental features on a production website. You can read more
about it at developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix.

The major browser prefixes are as follows:

-webkit- is u sed for Ch r om e, Sa fa r i, n ew er v er sion s of


Oper a , a n d a ll iOS br ow ser s.

-moz- is u sed for Fir efox .

-o- is for older v er sion s of Oper a .

-ms- is for In ter n et Ex plor er a n d Micr osoft Edg e.

Tip
Besides -ms-, Microsoft Edge supports a number of -webkit- prefixed
features to improve compatibility.
When formatting your declarations, order them so that
all the prefixes come before the non-prefixed property
(due to the cascade!).
As an example, see the following code for a CSS
transition. It creates a simple animation when any
property for a changes (for example, if the background
color changes on hover). Y ou’ll learn about CSS
animations in Chapter 18.
Click h er e to v iew code im a g e

a {
background: #880000;
-webkit-transition: all 1s linear;
-moz-transition: all 1s linear;
-ms-transition: all 1s linear;
-o-transition: all 1s linear;
transition: all 1s linear;
}

Y ou’ll learn more about testing later in the book, but as


far as prefixes go, it’s best to see what support new
features have and use them accordingly.
For the purposes of simplicity, examples in this book
exclude prefixes.

WRAPPING UP
There’s a lot to digest here, and you’ve only scratched the
surface. However, this gives you a fantastic jump-off
point for building incredible layouts in CSS.

The whole reason for this type of power is the topic


covered in Chapter 17: responsive design. Being able to
flexibly change how content is laid out without having to
modify the markup allows you to create fantastic
content no matter what screen your site is being viewed
on.
17

Responsive Design and


Media Queries
In This Chapter

Defining Media Queries


Responsive Layouts

Making a Full-width Layout Responsive


Not Just for Screen Widths

Wrapping Up

In today’s world, websites can be viewed on computers,


tablets, phones, watches, glasses, or even kitchen
appliances. It’s impossible to design for every single
scenario, and that’s where responsive web design (RWD)
comes in. RWD ensures that your website looks good no
matter what device it’s viewed on.
This is achieved through media queries—we can write
CSS that essentially asks the browser questions and then
presents styles based on the answers.

DEFINING MEDIA QUERIES


Unlike most of the CSS declarations you’ve seen so far,
media queries aren’t just sets of properties and values.
They are containers for other rulesets. Those rulesets are
then implemented based on the results of the media
query. All media queries are formatted like this:
Click h er e to v iew code im a g e

@media [media type] and ([media features]) {


[Rulesets go here]
}

As you’ll see later, there are lots of different types and


features to check for. But for now, here’s a common
media query:
Click h er e to v iew code im a g e

@media screen and (min-width: 600px) {


main {
display: flex;
}
}

This says, “If the user is viewing this site on a screen


whose viewport is at least 600px wide, display all
<main> elements as flex.”

Throughout the book you’ve seen references to screen


size, window width, and browser size. While each term
refers to how wide an area your website renders in, the
most succinct term is viewport, which refers to the exact
area of the screen that is rendering your website.
Other media types include all, print (for printing a
webpage), and speech (for use with screen readers).

Using breakpoints
A common term in RWD is breakpoint, the point at
which your layout changes to accommodate the
viewport. It allows you to make your layouts more
useable based on the size of the device your users are
viewing the site on.

For example, if you have a navigation menu that is


601px wide, it won’t look great on devices with a
viewport of less than 601px. Y ou can use a breakpoint to
say, “Once the viewport is wider than this size, change
the layout of the navigation menu.”
So if you select a media query for min-width: 600px,
your breakpoint is 600px.

RWD Best Practices


There hav e been lots of discussions ov er the y ears as to the best practices f or
responsiv e web design. Should y ou use em or px? How should y ou organize y our
media queries? Should y ou start big and get smaller or v ice v ersa?
Here is what I do in this book:

Use px because there is less ambiguity about the actual width than with em
and rem; px is more predictable (10px is alway s 10px), and that’s
especially usef ul f or learning.

Organize sty le sheets based on media query, with the base CSS bef ore
the media queries.

Take a mobile f irst approach.

Mobile first is the web design strategy that posits that y ou design f or the smallest
screen f irst and mov e up f rom there. Its main benef it is that it f orces y ou to assess
y our content and design elements. It helps y ou include only what y ou need, and then
hopef ully y ou realize that’s all y ou need!

Choosing breakpoints is an important decision because it


ensures your layout doesn’t, well, break. Many
breakpoints focus around specific devices—usually iOS
devices—but as the field of screen sizes increases, this is
not a good approach.
Instead, choose your breakpoints based on the point at
which your content starts to look bad.

If you’re starting mobile first, that means adding a


breakpoint that takes effect when the page is on devices
with larger screens. As the viewport expands past the
breakpoint, it can switch to different layout settings,
such as multicolumn layouts or layouts that are centered
in the screen.
If you’re starting by designing your pages for large
screens (a large tablet or desktop), when the page is
viewed on a smaller device you select your breakpoint by
resizing the browser window (and therefore the
viewport) down until the content becomes unreadable.

Ultimately, you’ll probably have three major breakpoints


(where there’s a major shift in content) and three to four
minor breakpoints (with smaller fixes for specific
content). But that’s a guide, and it’s completely up to
you. Do what works best for your design.

Tip
Since this book works with relatively basic layouts, it covers two or three
total breakpoints.

VIDEO 17.1

Choosing Breakpoints
In this v ideo, y ou’ll see how to choose breakpoints by resizing the browser window
until a site starts to look bad.

RESPONSIVE LAYOUTS
So how do you make responsive layouts? Where do you
start, and how do you structure your code? I
recommend setting all the base styles above any media
queries (as in, write them down in your style sheet first)
and starting with the smallest layout. Media queries
should modify your website as the viewport gets bigger.
Here’s a simple example to start.

To change the background color at 600px:


1. In y ou r sty le sh eet, ty pe body to esta blish th e defa u lt v a lu es
for th e pa g e.
2. Ty pe { to beg in th e r u le.
3. Ty pe background: follow ed by th e h ex code for th e sta r tin g
ba ckg r ou n d color . For th is ex a m ple u se #FF0000;.
4. Ty pe color: follow ed by th e h ex code for th e tex t color . In
th is ca se, u se #FFFFFF;.
5. Ty pe } to close th e r u le.
6. Ty pe @media to beg in th e m edia qu er y .
7. Ty pe th e n a m e of th e m edia ty pe y ou w a n t to ta r g et.
Beca u se y ou w a n t to im plem en t a differ en t sty le r u le w h en
th e u ser ’s br ow ser w in dow ch a n g es, u se screen.
8. Ty pe and.
9. Ty pe th e n a m e a n d v a lu e (in pa r en th eses) of th e m edia
fea tu r e th a t sh ou ld tr ig g er a ch a n g e in th e ba ckg r ou n d
color . Th is v a lu e is y ou r br ea kpoin t for th e pa g e, a n d y ou
w a n t th e br ea k to occu r w h en th e br ow ser w in dow is 6 00px
or w ider , so u se (min-width: 600px) {.
10. Ty pe th e elem en t y ou w a n t th is r u le to a ffect. In th is ca se,
body {.
11. Ty pe th e a ttr ibu te a n d v a lu e th a t y ou w a n t to ch a n g e a t th e
br ea kpoin t. In th is ex a m ple, u se background: #0000FF;.
12. Ty pe }.
13. Ty pe } to close th e m edia qu er y .

Now resize the browser window. When it is below 600px


wide, the background is red (FIGURE 17.1). When it’s
600px or wider, the background is blue (FIGURE
17.2).

Figure 17.1 The page when the browser window is


less than 600px wide
Figure 17.2 The page when the browser window is
600px or wider

Note that the font color was set outside the media query.
The goal is to avoid repetition in your code that might
bloat your style sheet. Any styles set inside media queries
will apply only when the media query is true. So if you
have multiple media queries but don’t want the color to
remain the same, you’d have to set it in every media
query.
This is another benefit of the mobile first approach. Y ou
will likely start at default displays for smaller screens and
then introduce changes as the page is displayed in larger
viewports, allowing you to set as many default styles as
possible before you start making changes.
For example, here is a simple CSS Grid layout that
shows the pitfalls encountered when defining the bigger
screen first (CODE 17.1). It tells divs to display their
children in columns as long as the viewport is wider than
599px. At 599px or smaller, it display divs as a block.
CODE 17.1 Styles for a CSS Grid layout, designing for larger screens first
Click h er e to v iew code im a g e

div {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 15px;
padding: 15px;
}
@media screen and (max-width: 599px) {
div {
display: block;
padding: 0;
}
}

CODE 17.2 Much more succinct Grid code, designing for smaller screens first
Click h er e to v iew code im a g e

@media screen and (min-width: 600px) {


div {
display: grid;
grid-template-columns: 1fr 1fr
1fr;
grid-gap: 15px;
padding: 15px;
}
}

In the media query, you’re actually resetting the div


back to its default display mode.

Y ou can avoid the dangers of designing for the large


screen first by treating the larger screen as the special
case, and allowing the smaller screen to use the
browser’s default settings.
And now, we’ll define media queries used in designing
for small screens first (CODE 17.2). Y ou don’t have to
reset div to its original state because it maintains that
state (display: block) until you change it for bigger
viewports.

This is a seemingly trivial example, but in the mobile


first layout, it wasn’t necessary to define any special
styles, because the browser defaults were adequate. The
desktop-first layout required some resetting of styles.
Y ou can imagine that using multiple breakpoints, or
more varied styles and layouts, will compound the cases
in which you find yourself redefining styles.
Tip
In a desktop-first layout, notice that max-width is 599px versus a 600px min-
width. You might run into issues like that—where you have an “off by one
pixel” declaration—if you want to get your designs pixel-perfect. If you want
the design to change at 600px, min-width makes that a little clearer, since
600px is in the actual definition.

As you create your layouts, think about how to reduce


the number of styles you override and how to make your
style sheets easier to manage.

MAKING A FULL-WIDTH LAYOUT


RESPONSIVE
So what goes into making a fully responsive layout?
Here, you’ll build it in sections. CODE 17.3 shows the
HTML markup you’ll work with. CODE 17.4 shows the
initial CSS styles, in a style.css file. Both are available
at github.com/jcasabona/html-css-vqs/Ch17/.
CODE 17.3 The HTML markup for the rest of this chapter
Click h er e to v iew code im a g e

<div class="wrapper">
<header>
<h1>A Case of Identity</h1>
<p class="byline">by Sir Arthur
Conan Doyle</p>
</header>
<main>
<p> “My dear fellow,” said Sherlock
Holmes as we sat on either side of the
fire in his
→lodgings at Baker Street, “life is
infinitely stranger than anything which
the
→mind of man could invent. We would
not dare to conceive the things which are
really
→mere commonplaces of existence. If
we could fly out of that window hand in
hand,
→hover over this great city, gently
remove the roofs, and peep in at the queer
things
→which are going on, the strange
coincidences, the plannings, the cross-
purposes,
→the wonderful chains of events,
working through generations, and leading
to the most
→outré results, it would make all
fiction with its conventionalities and
foreseen
→conclusions most stale and
unprofitable.”</p>
</main>
<aside>
This is one of 56 short stories
written about Sherlock Holmes by Sir
Arthur Conan
→Doyle. It was published in 1891.
</aside>
<footer>
<p>The <i>Sherlock Holmes</i>
series is in the public domain.</p>
</footer>
</div>

CODE 17.4 The starting CSS (or base styles) for the markup shown in Code 17.3
Click h er e to v iew code im a g e

@import
url('https://fonts.googleapis.com/css?
family=Playfair+Display:400,400i,500,500i,600,

→600i,700,700i,800,800i,900,900i&display=swap');

body {
font-family: 'Playfair Display',
serif;
background-color:#fcf6e7;
margin: 0;
padding: 0;
}
header,
footer {
background: #282009;
color: #FFFFFF;
padding: 30px;
text-align: center;
}
h1 {
font-weight: 900;
}
main,
aside {
margin: 30px;
}
aside {
background: #272727;
color: #FFFFFF;
padding: 30px;
}
.byline {
font-family: Futura, sans-serif;
font-style: italic;
}
p {
font-size: 18px;
margin: 30px 0;
}

FIGURE 17.3 shows the smallest screen and FIGURE


17.4 the largest screen.

Figure 17.3 The mobile layout


Figure 17.4 The desktop layout

Tip
To keep the source code clean, we define only the essential styles.

Starting small: mobile first styles


Most of the styles in Code 17.4 are for general look and
feel and are not related to layout. On the smallest
screens, everything will be a single column, so the
browser’s default styles for the elements will work. The
changes you see for margin, padding, fonts, and colors
were just to add some personality to the page and make
the layout changes more obvious (like giving the aside a
different background color from the body).

So now it’s time to answer the question of when to start


changing the layout—at what point can you begin to
space the content out a bit more?
As you try to figure this out, the best thing to do is resize
your browser. Since this layout lends itself very well to a
one-column format, not a whole lot needs to be done in
terms of adjusting it. Complicated layouts require more
complicated media queries.
However, there are a few things that can be done to take
advantage of more screen real estate.

The mid-sized screen layout


One way you can take advantage of more screen space
when your page is being viewed on bigger devices is to
spread out the header text a bit. One way to do this is to
set up a grid on the <header> element and use columns
to space the child elements.

Tip
The examples in this chapter use the styles shown in CODE 17.4, which you
should add to your style.css file, as the starting point. Continue to add the
new styles presented in each task to the end of the same file.

VIDEO 17.2

Making a Full Three-Column Layout Responsive


Though this book preaches mobile f irst, y ou may be in a situation where y ou hav e a
f ull site design and need to make it mobile f riendly. This v ideo shows y ou how to do
just that. Then y ou’ll see what it looks like as the browser resizes.

To create a two-column layout at a breakpoint:


1. Sta r t by defin in g y ou r m edia qu er y , ba sed on th e br ea kpoin t
a t w h ich y ou ’v e ch osen to ch a n g e y ou r la y ou t. Ty pe @media
screen and (min-width: 768px) {.
A dd th is code to th e en d of y ou r sty le sh eet (a ssu m in g y ou ’r e
u sin g th e code fr om Code 1 7 .4 ).
2. Ta r g et th e elem en t y ou ’d like to ch a n g e a t y ou r deter m in ed
br ea kpoin t. Ty pe header {.
3. A dd th e sty les for th is elem en t a t th e specific br ea kpoin t, on e
per lin e. Ty pe display: grid;.
4. Ty pe grid-template-columns: 2fr 1fr;.
5. Ty pe grid-gap: 15px;.
6. Ty pe justify-items: center;.
7. Close th e r u leset for y ou r elem en t by ty pin g }.
8. Close th e m edia qu er y by ty pin g }.

Once you extend your browser window to a width of at


least 768px, your header will move the byline out from
under the heading and to its right (FIGURE 17.5).

Figure 17.5 The header once the viewport is widened


beyond 768px

This is a good first step, but the real fun starts at the next
breakpoint: 1000px.

The large-screen layout


On a large screen, you can really take advantage of the
screen real estate. Using a multicolumn layout for large
screens is a great way to show more information to the
user, now that they have the room for it. A wrapper
div comes in handy here. This div “wraps” the
elements—header, main, aside, and footer—so that
they are all siblings. That means you can apply
display: grid to the .wrapper selector and easily
control how each child element (or grid item) is
displayed.

Since the large screen layout builds upon all the styles
added to style.css before it, add the following styles
to the end of style.css.

To set up a grid layout at a specific breakpoint:


1. You w a n t th is la y ou t to g o in to effect a t th e la r g est
br ea kpoin t y ou deter m in ed w or ks best for y ou r la y ou t. Ty pe
@media screen and (min-width: 1000px) {.
2. You w ill a lso n eed to cr ea te th e grid-areas. Ba sed on Code
1 7 .3 , ty pe header { grid-area: header; }.
Beca u se of th e ca sca de, th is w ill essen tia lly be a dded on to
pr ev iou s r u lesets ta r g etin g h ea der .
3. On a n ew lin e, ty pe main { grid-area: main; }.
4. On a n ew lin e, ty pe aside { grid-area: sidebar; }.
5. On a n ew lin e, ty pe footer { grid-area: footer; }.

Be sure to leave off the } that would close the media


query. We’re not done with it yet!
With those defined, it’s time to convert the wrapper div
into a grid with a template layout.

To convert wrapper to a grid layout:

1. It’s tim e to ta r g et y ou r en tir e la y ou t a t th is br ea kpoin t. Ty pe


.wrapper {.
2. A g r id len ds itself w ell to con tr ollin g ea ch elem en t of th e
la y ou t. On a n ew lin e, ty pe display: grid;.
3. On a n ew lin e, ty pe grid-gap: 15px;.
4. Deter m in e h ow m a n y colu m n s y ou w a n t in y ou r la y ou t. For
th is ex a m ple, ch oose fiv e to m a ke it clea r w e w on ’t h a v e a
main section a n d aside th a t a r e th e sa m e w idth s. On a n ew
lin e, ty pe grid-template-columns: 1fr 1fr 1fr 1fr
1fr;.
5. Ty pe grid-template-areas:.
6. Ty pe "header header header header header".
Rem em ber fr om th e m id-sized la y ou t ta sk, th a t header is
a lso u sin g grid. Th is con tr ols th e w idth of th e header
elem en t, w h ich w e w a n t to ex ten d a cr oss th e en tir e pa g e.
7. Ty pe "main main main main sidebar".
8. Ty pe "footer footer footer footer footer";.
9. Close th e .wrapper r u leset by ty pin g }.
10. Close th e m edia qu er y . On a n ew lin e, ty pe }.

Now the sidebar shows up to the right of the main


content, just like in Figure 17.4.

Now for the fun part: resize the browser window and
watch your layout change!
There are a few more stylistic changes you can make,
like increasing the heading font size and tightening up
some styles, but you’ve just taken your first layout and
made it responsive.

The rest of this chapter explores other functions of CSS


media queries.
VIDEO 17.3

Creating a Responsive Nav Menu


A common pattern f or responsiv e design is replacing the menu items with a single
label or icon that, when clicked or tapped, rev eals the menu. In this v ideo, y ou’ll learn
how to do that.

NOT JUST FOR SCREEN WIDTHS


The only media type you’ve seen in action so far is
screen, and the only feature you’ve seen is related to
width. While these are the most common
implementations for media queries, they aren’t the only
ones. For starters, there’s another common media type
to look at: print.

Creating a print style sheet


Because computers print websites more or less exactly as
they appear in the browser window, such printouts often
aren’t very helpful to those who want readable text
(FIGURE 17.6).
Figure 17.6 Trying to print a webpage

Luckily, you can add a media query to apply print styles


to the page. Here’s how to do it, starting with the
markup from the previous section.

To add printer styles to a website:


1. A t th e bottom of y ou r sty le sh eet, ty pe @media print { to
ta r g et pr in ter s.
2. Ty pe th e elem en ts y ou w a n t to in clu de in th e pr in tou t. For
th is ex a m ple, y ou w a n t th e w h ole pa g e, so in clu de body,
header, aside, footer {.
3. On a n ew lin e, ty pe background: #FFFFFF;.
Th is step a n d th e n ex t set th e ba ckg r ou n d color a n d tex t to
w h ite a n d bla ck, r espectiv ely , so th e tex t is m or e ea sily
r ea da ble w h en pr in ted.
4. On a n ew lin e, ty pe color: #000000;.
5. On a n ew lin e, ty pe }.
6. On a n ew lin e, ty pe .wrapper {.
Th is is th e cr u x of th e pr in t sty les.
7. On a n ew lin e, ty pe display: block;.
Sim ply settin g th e displa y to block m a kes th e br ow ser
ig n or e a ll g r id-r ela ted pr oper ties (like grid-template-
columns) a n d m ov es th e con ten t in to on e colu m n .
8. On a n ew lin e, ty pe width: 75%;.
Th is is a sty listic decision on m y pa r t, bu t it g iv es th e r ea der
plen ty of m a r g in on eith er side of th e con ten t.
9. On a n ew lin e, ty pe margin: 0 auto;.
10. On a n ew lin e, ty pe } to close th e .wrapper r u leset.
11. On a n ew lin e, ty pe } to close th e m edia qu er y .

This creates a single column of black text that looks


great when printed (FIGURE 17.7).

Figure 17.7 The printed page

On Hiding Elements
One all-too-common practice in responsiv e design is just hiding elements that don’t
“f it” on smaller screens. While the mobile f irst approach should help solv e this, it’s
still something to be mindf ul of . If y ou need to hide an element f or small screens,
y ou should question whether y ou need it at all.

One exception to this rule is print sty les. If y our goal is to make sure the main
content is readable when printed, it might be a good idea to hide certain elements (like
comments or images).
Aside from media types (all, print, screen,
speech), you can also target specific media features.

Targeting specific media features

Tip
You can get a list of media features at developer.mozilla.org/en-
US/docs/Web/CSS/@media. But keep in mind that specific devices might have
their own implementation.

Y ou might want to target a specific feature on touch


devices, check if a device is in portrait or landscape, or
much more. This is what the extended media features
are for. A great example is checking to see whether a
user has enabled dark mode.

To apply dark mode styles:


1. A t th e bottom of y ou r sty le sh eet, ty pe @media screen.
2. To specify on e or m or e m edia fea tu r es, ty pe and follow ed by
th e n a m e of th e m edia fea tu r e in pa r en th eses. To ch eck for
da r k m ode, ty pe (prefers-color-scheme: dark) {.
3. Ty pe th e selector s y ou w a n t th e sty le to a pply to; in th is
ca se, body, header, aside, footer {.
4. To m a ke su r e th e tex t h a r m on izes w ith th e ov er a ll in ky
en v ir on m en t, r ev er se th e u su a l bla ck-on -w h ite color s. Ty pe
background: #272727; to m a ke th e pa g e a da r k g r a y .
5. Ty pe color: #FFFFFF; to m a ke th e tex t w h ite.
6. Beca u se it’s lig h t tex t on a da r k ba ckg r ou n d, a bit m or e
spa cin g w ill m a ke th e tex t ea sier to r ea d. Ty pe line-
height: 2em;.
7. Ty pe }.
8. Ty pe on e m or e }.

Now, when you visit the site on a device using dark


mode, it will look like FIGURE 17.8.
Figure 17.8 Dark mode styles applied to a webpage

Experiment with more of these media features, as you


can do checks for the following:

Poin ter (cu r sor ) su ppor t (w ith any-pointer)

Hov er su ppor t (w ith any-hover)

Retin a displa y s (w ith resolution, min-resolution)

In v er ted color s (w ith prefers-color-scheme)

And much more. The possibilities for customizing a


website’s experience are growing quickly!

VIDEO 17.4

Advanced Media Queries


The examples in this book only scratch the surf ace of what y ou can do with media
queries. In this v ideo, y ou learn how to write more adv anced media queries by
combining checks and using logical operators.

WRAPPING UP
Media queries are essential to creating great user
experiences no matter what device your site is being used
on. From adjusting layout based on width to swapping
out colors in dark mode, your styles are completely
customizable based on the user’s preferences and their
browser’s capabilities.
And now that you’re familiar with everything from the
basics to layouts in CSS, it’s time to get a little more
advanced and look at CSS animations.
18

CSS Transformations and


Animations
In This Chapter

CSS Transitions
CSS Transformations

CSS Animations
Wrapping Up

It used to be that if you wanted to add a little extra


flourish to your webpages, you’d need to use JavaScript
or, if you go far back enough, Flash. The added flourish
could be a simple transition or a little animation, but
now CSS has the ability to apply transformations to
properties as well as to create frame-by-frame
animations.

While you won’t be making the next Toy Story in your


browser, you will be able to easily create interactions
that improve a user’s experience with your website. This
chapter gives you a small taste of what’s possible!

CSS TRANSITIONS
CSS transitions are some of the simplest but most
delightful effects you can apply to your elements.
Normally, when you change the value of a CSS property,
the change happens instantaneously. A CSS transition
allows you to change those values over time, which adds
nuance and visual cues to your user interface. They
generally occur due to some user interaction, like a
hover.
The main property here is transition, and it’s a
shorthand property for transition-property,
transition-duration, transition-timing-
function, and transition-delay. In transition,
they are replaced by these four values:

property: Th e CSS pr oper ty th a t y ou w a n t to a n im a te.


It ca n be a n y CSS pr oper ty th a t su ppor ts tr a n sition s—
w h ich is m ost bu t n ot a ll of th em . See a fu ll list a t
dev eloper .m ozilla .or g /en -
US/docs/Web/CSS/CSS_a n im a ted_pr oper ties.

duration: Th e a m ou n t of tim e, in secon ds, th e


tr a n sition sh ou ld ta ke.

timing-function: Th e m a th em a tica l descr iption of th e


r a te a t w h ich th e pr oper ty ch a n g es, w h ich ca n itself
ch a n g e ov er tim e. Com m on ex a m ples a r e ease (th e
defa u lt), linear, ease-in, ease-out, a n d ease-in-out.
You ca n ev en m a ke y ou r ow n tim in g fu n ction w ith
cubic-bezier.

delay: Th e a m ou n t of tim e, in secon ds, befor e th e


tr a n sition sta r ts.

When you write the transition property, it accepts


the four values in this order:
Click h er e to v iew code im a g e

transition: [property] [duration] [timing-


function] [delay]

Further, each option can have a value of 0 or 1, except


property, which should have a value of none, all, or
a specific CSS property. Listing just a property will
assume default values for duration (0s), timing-
function (ease), and delay (0s). And if you supply
two numbers (in seconds), the timing-function
defaults to ease.

Tip
Transitions can be applied in other ways, such as through adding a class in
JavaScript.
VIDEO 18.1

Demo of Transition Functions


It’s easiest to show how these transitions work in a v ideo. So here, y ou’ll see each as
a 1.5-second transition applied to the width property.

CODE 18.1 The background color of this button will change when the user hovers
their pointer over it.
Click h er e to v iew code im a g e

<!--Here's the HTML for the button. -->


<a class="button" href="#">Click Here</a>

/*Here follows the CSS that defines the


appearance of the button.*/
a.button {
background: #880000;
border-radius: 40px;
color: #ffffff;
display: block;
font-size: 1.5rem;
max-width: 150px;
padding: 15px;
text-align: center;
text-decoration: none;
}
/*And let's add a hover state to the
button.*/
a.button:hover {
background: #008800;
}

One common application of transitions is to change


background colors. CODE 18.1 shows a button defined
in CSS (FIGURE 18.1).

Figure 18.1 button produced by Code 18.1 in its


initial state.

In this example, when the user hovers their pointer over


the button, only one thing changes: the background
property changes from dark red to dark green. But it’s a
sudden, simple change. Adding a transition can make
that change smoother.

To add a background transition to an element


with CSS:
1. Usin g th e sa m ple CSS a s a sta r tin g poin t, a fter text-
decoration in th e a.button r u leset, ty pe transition:.
2. Nex t to transition:, ty pe background 1s ease-in;.
Th is sa y s, “ A dd a 1 -secon d ea se-in tr a n sition to th e
background pr oper ty .”

That’s it! Mouse over your button to watch a much


smoother transition from dark red to dark green. As an
added bonus, the browser reverses the timing function
when you un-hover, so you get a nice transition both on
hover and when you move off the element.

Tip
For a transition to work, the property you wish to target must be defined in
both states, and those properties must have different values.

Tip

The transition in this example is purposefully a little longer than usual so


you can see the effect in action. A more common duration is half a second.

As mentioned earlier, you can also use a delay value to


introduce a pause before the transition. Y ou do this by
adding a fourth value to the transition property—a
number in seconds. Here’s an image with a transition
effect on hover (FIGURE 18.2):
Figure 18.2 An image before and after the transition
to the hover state is invoked

Click h er e to v iew code im a g e

img {
padding: 20px;
width: 250px;
transition: width 2s ease 0.5s
}
img:hover {
width: 350px;
}

The last point we’ll make about transitions in this


chapter is that you can use the keyword all to target all
the properties in the style declaration.

To enlarge an input field on focus:


1. In y ou r sty le sh eet, ty pe input {.
2. Ty pe font-size: 1.5rem;.
3. Ty pe padding: 5px;.
4. Ty pe transition: all 1s ease-out;.
Th is tr a n sition a pplies th e tim in g fu n ction ease-out (sta r t
fa st a n d g et slow er ) to a ll pr oper ties w ith differ en t v a lu es
u pon sta te ch a n g e, ov er th e cou r se of 1 secon d.
5. }.
6. Ty pe input:focus {.
7. Ty pe font-size: 2rem;.
8. Ty pe padding: 10px;.
9. Ty pe }.

Y our input field will now enlarge when the user clicks it,
taps it, or activates it by pressing the Tab key.

VIDEO 18.2

Increasing the Size of an Input Field


In this v ideo, y ou create an input f ield that increases in size when the cursor is
f ocused on it.

CSS TRANSFORMATIONS
Another way to add simple effects to your webpages is
with CSS transformations. While commonly triggered by
actions by the user—like hovering, clicking, or focusing
on a form element—that’s not necessarily the case, as
you’ll see later in this chapter.

Tip

This chapter talks a lot about 2D and 3D planes. As a refresher, the x axis is
the horizontal axis, going left to right. The y axis is the vertical axis, going
down to up. The z axis is the depth axis, going front to back (where back is
away from the viewer).

VIDEO 18.3

Transformation Examples
In this v ideo, y ou’ll see the v isual ef f ect created by each transf ormation.

The transform property lets you transform an HTML


element by rotating it, scaling it, skewing it, or
repositioning it in the horizontal and/or vertical
directions. It’s even possible to combine several
transformations to achieve interesting visual effects:

scale(x,y) ch a n g es th e size of th e elem en t. It a ffects


font-size, height, width, a n d padding. Use scaleX()
a n d scaleY() to sca le on ly a sin g le a x is. Un its a r e a
m u ltiplier (0.5 to sh r in k by h a lf, 2 to dou ble th e size,
etc.).

skew(x,y) tilts a n en tir e con ta in er ba sed on th e v a lu es.


Use skewX() a n d skewY() to skew on ly a sin g le a x is.
Un its a r e deg r ees.

translate() m ov es a con ta in er fr om side to side, u p


a n d dow n , or both . Gen er a lly com bin ed w ith th e
animate pr oper ty . Un its a r e sta n da r d m ea su r em en t
u n its y ou ’v e seen th r ou g h ou t th e book (px, em, etc.), a s
w ell a s oth er a dv a n ced u n its th a t ca n r epr esen t
n u m ber s to th e br ow ser .

rotate() r ota tes th e elem en t clockw ise fr om its cu r r en t


position . Un its a r e deg r ees.

Tip

There are two more functions—matrix() and perspective()—but they are a little
more complicated to implement. To learn more, read this article: css-
tricks.com/almanac/properties/t/transform/.

Tip
It’s easy to get carried away implementing transformations because they can
do cool things to your elements, but unless you’re creating advanced
animations, use them sparingly so they stand out.

Writing transformations
The syntax for writing a transformation is a little simpler
than for transitions, but transformations can be used for
more advanced animations, as you’ll see later. Here’s a
basic declaration that incorporates a transformation:
Click h er e to v iew code im a g e

div.diamond {
background: #FF0000;
width: 200px;
height: 200px;
margin: 50px;
transform: rotate(45deg);
}

The above code results in a rotated 200 by 200 square,


which looks like a diamond (FIGURE 18.3). Note that
this is a static transformation, which can serve as a
design element. Other transformations, like scale(),
are better served when combined with a user event or an
animation.

Figure 18.3 A rotate transformation applied to a


square

Tip
You’ll notice that the transform property takes elements out of their original
flow. That’s something to keep in mind as you move forward.
To skew a div slightly on hover:

1. In y ou r sty le sh eet, ty pe div {.


2. Ty pe background: #FF0000;.
3. Ty pe width: 200px;.
4. Ty pe height: 200px;.
5. Ty pe transition: transform 1s linear;.
Th is is so th e elem en t skew s sm ooth ly w ith a w ell-tim ed
a n im a tion , in stea d of m a kin g th e elem en t ju m p to th e
skew ed sta te.
6. Ty pe }.
7. Ty pe div:hover {.
8. Ty pe transform: skewX(-20deg);.
Wh en y ou u se deg r ees a s th e u n it, y ou ca n a lso u se n eg a tiv e
v a lu es.
9. Ty pe }.

Now when the user’s mouse hovers over the square, it


skews to the right (FIGURE 18.4).

Figure 18.4 A square with a skewX()


transformation applied on hover

VIDEO 18.4

Creating an Image Gallery with Mouseover Effects


In this v ideo, y ou’ll learn how to combine transf ormations and make an attention-
grabbing ef f ect when a user hov ers ov er an image.

3D Transformations
The f ollowing f unctions hav e 3D v ersions:

scale3d(x,y,z)
rotate3d(x,y,z)

translate3d(x,y,z)

matrix3d()

They each apply their transf ormations to the z axis as well, and this is where the
perspective() f unction comes in handy —it sets the perspectiv e f or all child
elements to make sure 3D animations are all based on the same v iewpoint.
While this book doesn’t get into the nitty -gritty of 3D transf ormations, they are good
to know about if y ou want to take CSS animations to the next lev el or do some
academically cool stuf f .

CSS ANIMATIONS
The final and most robust way to add flair to your
webpages is CSS animations. These are done using two
properties: animation and @keyframes.

@keyframes is a way for you to timestamp the steps of


your animations. This essentially puts your animations
on a timeline that you can change. So you can say, “At
start (0% of the timeline), the container should do this.
At 50%, it should change to this, and at end (100%) it
should be this.” Y ou reference the timeline (or
keyframes) by assigning a name to them. See CODE
18.2 for a simple example (FIGURE 18.5).

Figure 18.5 The two states of the switch animation

CODE 18.2 A div with an animation applied to it. The animation property
references the name (switch) that is given to the @keyframes controlling
the animation.
Click h er e to v iew code im a g e
div {
width: 200px;
height: 200px;
background: red;
animation: switch 4s infinite;
}
@keyframes switch {
0% {
background: red;
}
50% {
background: blue;
}
100% {
background: red;
}
}

Tip

If two steps have the same value, use comma-separation as a form of


shorthand: @keyframes switch { 0%, 100% { background: red; } }.

This code applies an animation that switches the


background color from red to blue on a loop.
animation is a shorthand property that lets you set the
value of multiple properties. Here’s what’s used in Code
18.2:

animation-name: Th is m a tch es th e @keyframes n a m e.

animation-duration: How lon g th e a n im a tion sh ou ld


ta ke in secon ds.

animation-iteration-count: How m a n y tim es th e


a n im a tion sh ou ld r u n . Th e key w or d infinite is a
pla ceh older for n o lim it.

There are other animation properties that can be


represented in the animation shorthand property. Here’s
the full list in the order they’re expected:

animation-name

animation-duration

animation-timing-function

animation-delay

animation-iteration-count
animation-direction

animation-fill-mode

animation-play-state

Since this is an introduction to animations, this book


doesn’t cover everything. If you’d like to learn more,
check out this MDN article: developer.mozilla.org/en-
US/docs/Web/CSS/animation.

VIDEO 18.5

Rainbow Animation
In this v ideo, y ou expand on the switch animation and use key f rame stops to
change the div to ev ery color in the rainbow.

Tip

There are several other animation properties you can add as well, including
delays and timing functions. Check out all the properties here: css-
tricks.com/almanac/properties/a/animation/#article-header-id-0.

Combining animations
Y ou can add more than one animation at once. To
demonstrate, you’ll convert the switch square to a
circle. border-radius is used for this task because the
value you provide for the property lets you set how
much you want to “round off” the corners, as a
percentage. Setting it to 50 percent rounds them so
much that the square looks like a circle.

To convert a square to a circle:


1. In th e 0% key fr a m e, below background: red;, ty pe
border-radius: 0%;.
2. In th e 5 0% key fr a m e, below background: blue;, ty pe
border-radius: 50%;.
3. In th e 1 00% key fr a m e, below background: red;, ty pe
border-radius: 0%;.

This creates a red square that transforms into a blue


circle (FIGURE 18.6).
Figure 18.6 Red square transforming to blue circle

Animations using the transform property


Using transform in animations is a great way to save
performance and do neat things like actually moving
objects. This is where the translate() function from
earlier comes into play. Using the CSS code below as a
starting point, you’ll make the ball that is generated by
the following style declaration bounce up and down
(FIGURE 18.7). In your HTML, add the following:

Figure 18.7 The ball that will bounce in the next


task.

<p class="ball"></p>

And in your CSS, add the following:

p.ball {
width: 50px;
height: 50px;
border-radius: 50%;
background: #000000;
}
To bounce the ball:
1. In p.ball, a fter background: #000000;, ty pe animation:
bounce 1s infinite alternate;.
bounce is th e n a m e w e’r e g iv in g to th e a n im a tion w e’r e
a bou t to defin e.
Th e infinite v a lu e m ea n s “ Loop th is a n im a tion a n d n ev er
stop it.”
Th e alternate v a lu e m ea n s “ Ex ecu te th e a n im a tion , a n d
th en pla y th e a n im a tion in r ev er se.”
2. Ty pe animation-timing-function: linear;.
Th is tim in g fu n ction , linear, sa y s th a t th e item sh ou ld
a n im a te a t a n ev en , con sisten t speed th e w h ole tim e.
3. Ty pe } to close th e p.ball decla r a tion .
4. Ty pe @keyframes bounce {.
Th is is w h er e w e defin e ou r a n im a tion . Notice th a t th e
n a m e, bou n ce, is a lso r efer en ced in th e a n im a tion pr oper ty
in step 1 .
5. Ty pe 0% {.

On Performance
Adding too many animations to y our pages can cause perf ormance issues in
the browser. That’s because they place heav y demands on the CPU (central
processing unit), and they can potentially crash the browser.

There are a f ew animations y ou can use saf ely because the browser itself
implements them, which means the GPU (graphics processing unit) can assist.
They are the standard transf orm properties built into CSS with the addition of
opacity :

1. opacity

2. translate

3. rotate

4. scale

To learn more, check out this f antastic article:


www.html5rocks.com/en/tutorials/speed/high-perf ormance-animations/.

6. Ty pe transform: translate(0px, 0px);.


We defin e n o tr a n sla tion a t 0 per cen t (or th e fir st step of th e
a n im a tion ) so th a t th e ba ll r etu r n s to its sta r tin g sta te.
7. Ty pe }.
8. Ty pe 100% {.
Th is sets a key fr a m e a t th e v er y en d of th e a n im a tion (a t
1 00 per cen t of th e tim elin e).
9. Ty pe transform: translate(0px, 400px);.
Sin ce th e translate pr oper ty m ov es th e elem en t a lon g th e x
a n d y a x es, th is sa y s, “ Mov e th e ba ll 4 00px a lon g th e y a x is.”
Sin ce th e sta r tin g poin t is 0px , th e ba ll w ill m ov e dow n
4 00px .
10. Ty pe }.
11. Ty pe }.

CODE 18.3 The bouncing ball CSS.


Click h er e to v iew code im a g e

p.ball {
width: 50px;
height: 50px;
border-radius: 50%;
background: #000000;
animation: bounce 1s infinite
→alternate;
animation-timing-function: linear;
}

@keyframes bounce {
0% {
transform: translate(0px,0px);
}
100% {
transform: translate(0px, 400px);
}
}

For a complete listing of the final CSS see CODE 18.3.


To see the results (and expand upon them), check out
Video 18.6 (FIGURE 18.8).
Figure 18.8 The ball starts at the top of the parent,
bounces to the bottom, and then repeats.

VIDEO 18.6

Follow the Bouncing Ball


In this v ideo, y ou expand on the bounce animation and make the ball bounce f rom
one corner of the container to the other and then back.

WRAPPING UP
What a chapter! Now you know how to add effects and
animations to your elements. This will help you create
more dynamic pages, and it allows for smoother, less
jarring state changes to let the user know what’s
happening on your page.
Of course, you’ve only scratched the surface. There’s a
ton to know about CSS animations, and lots of fantastic
examples out there. To go deep with CSS animations,
check out this article on CSS-Tricks: css-
tricks.com/almanac/properties/a/animation/.
And if you want to see what you can do, the “picked
pens” on CodePen never disappoint: codepen.io/.

Y ou may have noticed a lot of repetition of CSS


properties (like font, color, and background) in this
chapter and elsewhere. The next chapter shows you how
to remove some of that repetition with CSS variables.
19

CSS Variables
In This Chapter

What Are Variables?


Simplifying Styles with Variables

Calculations with Variables


Wrapping Up

As you start to build more complex websites, your style


sheets will also grow in complexity. Luckily, there are
ways to manage complex CSS and get it under control.

In Chapter 20, you will be introduced to CSS


preprocessors, which are essentially programming
languages that are mostly CSS with added functionality.
But if you’re not yet ready to dive into something like
that, CSS natively supports variables, which will go a
long way toward taming your CSS.

Tip
The official specification name for variables is custom properties:
developer.mozilla.org/en-US/docs/Web/CSS/--*.

WHAT ARE VARIABLES?


So far, as you’ve written CSS you’ve needed to manually
type styles each time you want to use them. For
example, let’s say you have an accent color on your
website of #EB1DFE ( ). Y ou can apply that to
buttons, borders, links, and so on. But for each instance,
you’ll need to type #EB1DFE.
But what if you decide to change it to a different accent
color? Y ou’ll need to find all the references and manually
change them. More so, if you want to change only some
of them, a file-wide Find/Replace won’t work. But
there’s a better way. Y ou can use custom properties,
which are often referred to as variables.
Variables act like placeholders; they are a way to store
information in order to reference it later, and they are a
part of every programming language. With variables,
there are two components: the name and the value.
When you define (or set) a variable, you assign it a
value. Then you can use the variable name instead of the
value.

In CSS, to reference a variable, you use the function


var() and place the variable between parentheses. A
function in this instance is a way to execute a piece of
code that tells the browser, “Grab the value of the
variable and use that.”

Tip
By convention, the names of variables use camel case. That means each word
in the name except the first is capitalized, and there are no spaces between
the words: thisIsCamelCase.

The beauty of variables is you only need to change the


accent color value in one place, and it will update
everywhere.

To make a CSS variable assignment:


1. In y ou r sty le sh eet, a t th e top, ty pe :root {.
Th is defin es th e scope of th e v a r ia ble (m or e on th a t la ter ).
2. Now it’s tim e to m a ke th e a ssig n m en t. Ty pe --
accentColor: #EB1DFE;.
Ev er y v a r ia ble n eeds to sta r t w ith a dou ble h y ph en (--). Th e
n a m e sh ou ld descr ibe w h a t it’s r epr esen tin g .
Th e v a lu e ca n be a n y v a lid CSS v a lu e. In th is ca se, it’s a h ex
r epr esen ta tion of a color .
3. Ty pe }.
4. On th e n ex t lin e, ty pe a { to a ssig n th e sty le to lin ks.
5. Ty pe color: var(--accentColor);.
6. Ty pe }.

This makes all your links a nice pink (FIGURE 19.1).

Figure 19.1 A link using the color assigned by a CSS


variable

To see the full syntax, check out CODE 19.1.


CODE 19.1 The code that creates and uses the variable --accentColor
Click h er e to v iew code im a g e

:root {
--accentColor: #EB1DFE;
}

a {
color: var(--accentColor);
}

VIDEO 19.1

Changing Multiple Elements by Changing a Single Variable


Using CodePen, I show y ou how a single v ariable change updates multiple elements
on a page.

It may seem trivial here, but imagine you’ve used the


color dozens of times through multiple style sheets. It
can be a daunting task to remember where the instances
are and then update all of them, especially if a simple
find and replace won’t work—what if you want to keep
some of the values but not all of them?

Since variables are native CSS, they work just like any
other property or ruleset:

Th ey ca sca de, w h ich m ea n s th ey ca n ea sily be


ov er w r itten .

Th ey ca n be m a n ipu la ted by Ja v a Scr ipt (w h ich is


ou tside th e scope of th e book).
Th ey don ’t r equ ir e a n y a ddition a l tools to w or k.

Tip
You can also include a fallback value in the var() function. This means that if
you try to use a variable that has no value assigned to it, a default value will
be used. For example, if you write color: var(--primaryColor, #FF0000);,
the color #FF0000 will be used if the --primaryColor variable is not valid.

Variable scope
When you talk about variables, you can’t ignore a
discussion about scope. The scope of a variable
determines the context in which it’s “visible,” or can be
referenced. In the accent color task, you used the
keyword :root, which means, “The scope of this
variable is the entire document.” But you could have just
as easily used div or p, making the scope only those
elements. Y ou can also change the scope by defining the
same variable in a different ruleset (FIGURE 19.2).

Figure 19.2 Changing the scope of a variable


changes the styles.

To change the scope of a CSS variable:

Here is your HTML:


Click h er e to v iew code im a g e

<main>
<a href="https://google.com"> Visit Google</a>
</main>
<aside>
<a href="https://casabona.org">
→Learn More</a>
</aside>
1. In y ou r sty le sh eet, ty pe :root {.
2. Ty pe --accentColor: #EB1DFE;.
3. Ty pe }.
4. On a n ew lin e, ty pe th e n a m e of th e elem en t w h ose pr oper ty
y ou w a n t to ch a n g e. In th is ca se, u se aside {.
5. Ty pe th e n a m e of th e v a r ia ble for th e pr oper ty y ou w a n t to
ch a n g e. For th is ex a m ple, u se --accentColor: #008800;.
6. Ty pe }.
7. On a n ew lin e, ty pe a {.

VIDEO 19.2

Changing the Scope of Variables


When y ou change the scope of a v ariable, y ou can more succinctly update
y our rulesets. Here’s a demo on CodePen.

8. Ty pe color: var(--accentColor);.
Th is sin g le decla r a tion is a ll th a t is n eeded. If th e <a> ta g is
th e descen da n t of a n <aside> elem en t, its --accentColor
v a lu e w ill be #008800. Oth er w ise, it w ill be #EB1DFE.
9. Ty pe }.

Y ou can think of variables as phone numbers, where the


area code is the scope. Two people in the US can have
the same phone number if they aren’t in the same area
code (just ask anyone whose number is 867-5309, from
the Tommy Tutone song “Jenny”).
If you don’t dial the area code, your local area code is
assumed. If you dial the area code, you’re changing the
scope of the phone number. Variables are the same way.

Spanning Multiple Files


It hasn’t been discussed much in this book, but y ou’re not limited to one CSS f ile per
website. You can hav e multiple CSS f iles and use them to organize dif f erent aspects
of y our sty les.

While there is much debate ov er what loads f aster (one giant CSS f ile or sev eral
smaller CSS f iles), there is some benef it to using multiple CSS f iles, especially as it
pertains to v ariables. You can keep all of y our v ariables in a single f ile—say,
variables.css—and load it bef ore any other CSS f ile. You would list this as the f irst
<link> ref erence in y our HTML. The browser loads CSS f iles (and all f iles) in the
order in which it encounters them.
Then y ou can cleanly def ine v ariables and their scopes and leav e the actual rulesets
to a separate CSS f ile (of ten named main.css or style.css).
SIMPLIFYING STYLES WITH
VARIABLES
The ability to change the scope of CSS variables means
you can write more succinct CSS. In the scope task, you
saw that there were two variable definitions but only one
ruleset for the <a> tag. This doesn’t just apply to element
rulesets. Y ou can change variables through media
queries too.
This gives you the chance to define nearly all of your
styles early in your CSS, without the need to create large
sections of code dedicated to media queries. If you
change only the variable values, and not entire styles,
your media queries will be much shorter, and there’s less
work for the browser to do, making your website more
efficient.

To create a grid using variables and media


queries:

Here’s the HTML code you’re working with:


Click h er e to v iew code im a g e

<div>
<p>This is grid item 1</p>
<p>This is grid item 2</p>
<p>This is grid item 3</p>
</div>

1. A t th e top of y ou r sty le sh eet, ty pe :root {.


Th is lin e w ill defin e th e defa u lt v a lu es for ou r CSS v a r ia bles.
We sta r t m obile fir st, so th e g r id tem pla te w ill be a sin g le
colu m n .
2. On a n ew lin e, ty pe --gridTemplate: 1fr;.
Rem em ber h er e th a t w e a r e on ly defin in g th e v a r ia ble, a n d
n ot th e sty le. Th a t com es la ter .
3. On a n ew lin e, ty pe --gridGap: 0;.
4. On a n ew lin e, ty pe }.
5. On a n ew lin e, ty pe @media screen and (min-width:
600px) {.
Th is is th e on ly r efer en ce to a m edia qu er y , a n d its sole
pu r pose is to ch a n g e th e v a lu es of th e v a r ia bles, n ot to a ssig n
a ctu a l sty les. A t th e 6 00px br ea kpoin t, th e v a r ia bles w ill
ch a n g e.
6. On a n ew lin e, ty pe :root {.
Sin ce th e scope of th e v a r ia bles in step 1 is :root, w e n eed to
r efer en ce th a t sa m e scope in th e m edia qu er y .
7. On a n ew lin e, ty pe --gridTemplate: 1fr 1fr 1fr;.
A t 6 00px , w e w a n t th e g r id la y ou t to ch a n g e fr om on e
colu m n to th r ee colu m n s, so w e’r e ch a n g in g th e v a lu e of th e
v a r ia ble.
8. On a n ew lin e, ty pe --gridGap: 10px;.
Th e sa m e g oes for th e g a p betw een colu m n s. Ch a n g in g th e
v a r ia ble h er e w ill ch a n g e th e sty les a t th e 6 00px
br ea kpoin t.
9. On a n ew lin e, ty pe } to close th e :root v a r ia ble
decla r a tion s.
10. On a n ew lin e, ty pe } to close th e m edia qu er y .
11. On a n ew lin e, ty pe div {.
Th is is th e on ly div r u leset w e’ll n eed, th a n ks to CSS
v a r ia bles.
12. On a n ew lin e, ty pe display: grid;.
13. On a n ew lin e, ty pe grid-gap: var(--gridGap);.
Th e v a r ia ble --gridGap w ill ch a n g e ba sed on th e m edia
qu er y decla r a tion a bov e, m a kin g th is div r espon siv e
w ith ou t ex plicitly pu ttin g it in to its ow n m edia qu er y
r u leset.

VIDEO 19.3

Complex Layouts with Variables


Taking the grid task a step f urther, this v ideo shows y ou how to make a
complex lay out using CSS v ariables.

14. On a n ew lin e, ty pe grid-template-columns: →var(--


gridTemplate);.
Sa m e g oes for --gridTemplate. Th is v a lu e w ill ch a n g e ba sed
on th e br ea kpoin t.
15. On a n ew lin e, ty pe } to close th e div.

The resulting code stacks paragraph elements inside the


div in a single column when the viewport is narrow
(FIGURE 19.3). If the viewport is widened beyond
600px, the paragraphs are distributed into three columns
(FIGURE 19.4). See CODE 19.2 for the complete code
listing.
Figure 19.3 The CSS variables produce a single
column of grid items when the viewport is less than
600px wide.

Figure 19.4 Once the viewport is 600px or wider, the


values of the CSS variables change, creating a three-
column grid.

For comparison’s sake, CODE 19.3 shows the code


you’d have to write if you didn’t use CSS variables.
CODE 19.2 This concise code uses variables to create a responsive grid layout.
Click h er e to v iew code im a g e

:root {
--gridTemplate: 1fr;
--gridGap: 0;
}
@media screen and (min-width: 600px) {
:root {
--gridTemplate: 1fr 1fr 1fr;
--gridGap: 10px
}
}
div {
display: grid;
grid-template-columns:
→var(--gridTemplate);
grid-gap: var(--gridGap);
}
CODE 19.3 The code to create a very simple grid without CSS variables. This
quickly gets much more complicated with bigger grids or more breakpoints!
Click h er e to v iew code im a g e

div {
display: grid;
grid-gap: 0;
grid-template-columns: 1fr;
}
@media screen and (min-width: 600px) {
div {
grid-gap: 10px;
grid-template-columns: 1fr 1fr
1fr;
}
}

CALCULATIONS WITH VARIABLES


Aside from the var() function, CSS also provides the
calc() function, which allows you to perform basic
arithmetic operations in CSS. Y ou can do the following:

A ddition w ith th e plu s sig n (+)

Su btr a ction w ith th e m in u s sig n (-)

Mu ltiplica tion w ith th e a ster isk (*)

Div ision w ith th e for w a r d sla sh (/)

This allows you to include calculations either in new


variables or on the fly—that is, in the property definition.
One big benefit is that you can mathematically define
padding and properly scale font sizes, making your styles
more consistent.

In other words, we can size various properties


proportionally derived from a couple of base values.

To proportionally change a variable with calc():

This HTML is straightforward:


Click h er e to v iew code im a g e

<h1>This is a heading</h1>
<p>This is body text!</p>

1. A t th e top of y ou r sty le sh eet, ty pe :root {.


2. On a n ew lin e, ty pe --fontSize: 1.25rem;.
3. On a n ew lin e, ty pe --fontSizeHeading: calc(.
Th is open s u p th e calc() fu n ction for u s.
4. Ty pe var(--fontSize) * 3.
Th is is th e oper a tion . Rem em ber th a t w e n eed to u se th e
var() fu n ction to g et th e v a lu e of --fontSize. Th en w e
m u ltiply it by 3 . We’ll u se th is ca lcu la ted v a lu e for h1, a n d
w e w a n t it to be th r ee tim es a s la r g e a s th e body ’s fon t size.

Manipulating Variables with JavaScript


Though Jav aScript is generally outside the scope of this book, it’s worth talking
about it in the context of v ariables.

One of the most powerf ul aspects of CSS v ariables is their ability to be


manipulated by Jav aScript. This allows y ou to make changes to v ariables, and
theref ore to y our lay out and sty les, in real time and on the f ly.
Perhaps y ou want to change the background color based on how long a user
has been on y our site. You can change the CSS v ariable that controls the
background, based on a Jav aScript counter.
As y ou begin to master HTML and CSS, learning Jav aScript is the next logical
step, and this is one more reason to check it out.

CODE 19.4 The CSS that uses calc() to create a heading size proportional
to the body font size
Click h er e to v iew code im a g e

:root {
--fontSize: 1.25em;
--fontSizeHeading: calc(var(
→--fontSize) * 3 );
}

body {
font-size: var(--fontSize);
}

h1 {
font-size: var(--fontSizeHeading);
}

5. Close th e fu n ction w ith );.


6. On a n ew lin e, ty pe }.
7. On a n ew lin e, ty pe body {.
8. On a n ew lin e, ty pe font-size: var(--fontSize);.
9. On a n ew lin e, ty pe }.
10. On a n ew lin e, ty pe h1 {.
11. Ty pe font-size: var(--fontSizeHeading);.
You cou ld a lso u se font-size: calc(var(--fontSize) *
3); a n d for g o defin in g a secon d v a r ia ble.
12. On a n ew lin e, ty pe }.
Y ou can see the full CSS in CODE 19.4. The result is
that the body copy is slightly bigger than the browser
default, and the <h1> tag is three times as big as the
body copy (FIGURE 19.5).

Figure 19.5 On the left are the default sizes for


Chrome. On the right, the new sizes, including the
heading size resulting from the calc() function.

WRAPPING UP
CSS variables can change the way you write CSS,
especially as it becomes more complex. Between
overriding it easily and making calculations, you can do
some pretty powerful stuff.
And there’s something else that can take your CSS to the
next level: preprocessors.
20

CSS Preprocessors
In This Chapter

How CSS Preprocessors Work


Getting Started with Sass

Writing Sass
Wrapping Up

CSS includes functions that make writing rulesets easier,


but there are even more powerful tools that can
streamline and optimize your CSS code.

These tools are called CSS preprocessors, and they


operate at a level above CSS. That is, they take what you
write and convert it to CSS. Preprocessors add features
that otherwise wouldn’t exist in CSS, the ability to reuse
rulesets easily without copying and pasting, and loops (a
way to automatically write code based on a set of
criteria). Let’s take a closer look.

HOW CSS PREPROCESSORS WORK


A CSS preprocessor is essentially a programming
language that produces valid CSS. Y ou write in the
unique syntax of the preprocessor (which you’ll learn
about in this chapter), and the preprocessor takes what
you write and converts it into CSS.
Doing this allows the preprocessors to add new features
to CSS without changing how the browser works. Think
of it this way: if you want more storage space in your
laptop, you’re probably not going to crack it open to
replace the hard drive—you’ll buy an external hard drive.
It sits on the outside of your computer, but it still offers
more space for you.
CSS preprocessors act similarly. They add more features
you can use to write CSS without cracking open the
browser to add the support. And the beauty of most
preprocessors is that they look enough like CSS that if
you already know CSS you can quickly get started using
one.

Why use a preprocessor over native CSS?


With CSS variables, CSS Grid, Flexbox, and the
continued evolution of CSS, the gap between native CSS
and preprocessors is closing (FIGURE 20.1).

Figure 20.1 What Sass syntax looks like, and the CSS
it outputs

Still, preprocessors offer a number of benefits over native


CSS:

Ea sier n estin g a n d ca sca din g . In stea d of w r itin g ou t th e


en tir e selector (like div.wrapper main section
p.alert), y ou ca n n est a selector in side a n oth er on e to
cr ea te a v isu a l h ier a r ch y sim ila r to HTML. You ’ll lea r n
m or e a bou t th is la ter .

Repea ta ble/r eu sa ble r u lesets. You sa w th is a bit w ith


v a r ia bles, bu t pr epr ocessor s a llow y ou to
pr og r a m m a tica lly g en er a te CSS r u lesets. For ex a m ple,
in stea d of m a n u a lly w r itin g th e ca lcu la tion s for sca led
h ea din g s, a s y ou did in Ch a pter 1 9 , y ou ca n w r ite a few
lin es of code sa y in g , “ Sta r tin g w ith h1, decr ea se th e size
of ea ch h ea din g by 2 0 per cen t.”

Bu ilt-in fu n ction s. Ea sily g en er a te color sch em es,


per for m a dv a n ced m a th oper a tion s, a n d m or e w ith
bu ilt-in fu n ction s.

Or g a n iza tion . Cr ea te m u ltiple pr epr ocessor files a n d


com pile th em in to a sin g le CSS file.

A u to-pr efix in g . A u tom a tica lly pr efix y ou r CSS


pr oper ties w ith ou t h a v in g to a dd th em m a n u a lly ev er y
tim e.

Y our mileage will vary based on the preprocessor you


choose. On that note, while there are a few different
preprocessors to choose from, this book uses Sass/SCSS.

Tip
This chapter is a primer on preprocessors; it is a little less hands-on than
previous chapters because entire books have been written about specific
preprocessors. But as you continue your web design education, it’s highly
likely you’ll come across one.

Popular CSS Preprocessors


There are many CSS preprocessors to choose f rom, but there are two v ery popular
preprocessors: Sass (sass-lang.com) and Less (lesscss.org).

They dif f er in nuances of f eatures and sy ntax, but if y ou’re starting f rom zero, either
one should be f ine f or y ou.
Statistically (at the time of this writing), Sass is a lot more popular, which means
y ou’ll likely f ind more tutorials, examples, and support.

If neither appeals to y ou, there’s also Sty lus (sty lus-lang.com), which has been
praised f or its simple and clean sy ntax.

GETTING STARTED WITH SASS


When deciding whether it’s worthwhile to use Sass or
any other CSS preprocessor, keep in mind that you will
need to add a compiler to your workflow. Throughout
this book, you’ve been able to write HTML and CSS in
your text editor, save it, and immediately open the file in
your browser. With Sass there’s an extra step involved:
the Sass file needs to be compiled.
Before you get started, you should know there are
technically two versions of Sass you can write: Sass and
SCSS. The main difference is the syntax. Sass looks more
like a programming language, and SCSS looks more like
CSS. This book uses SCSS. All files written with SCSS use
the file name extension .scss.

For the purposes of this book, there are two ways you
can get started with Sass:

You ca n u se CodePen . Th is does n ot r equ ir e in sta llin g


a n y th in g a ddition a l on y ou r com pu ter . You ca n pr a ctice
w r itin g it, see th e r esu lts, a n d th en deter m in e la ter if
y ou ’d like to con tin u e w ith it. A s a n a dded bon u s, y ou
ca n copy th e com piled CSS a n d pa ste it r ig h t in to y ou r
ow n .css files.

You ca n in sta ll a n a pp th a t com piles Sa ss. Th is a llow s


y ou to w r ite Sa ss files a n d cr ea te CSS files, w h ich y ou
ca n th en u se on y ou r w ebsites.

Here’s how to do both.

To write Sass using CodePen:


1. Go to codepen .io.
2. Do on e of th e follow in g to cr ea te a Pen (a scr a tch pa d for code
sn ippets):
If y ou a lr ea dy h a v e a n a ccou n t a n d a r e log g ed in to it, click
Pen in th e left sideba r u n der th e Cr ea te h ea din g (FIGURE
20.2).
Figu r e 20.2 Tw o w a y s of cr ea tin g a n ew Pen : fir st, for
u ser s log g ed in to a n a ccou n t; secon d, for u ser s w h o a r en ’t
log g ed in .

If y ou do n ot h a v e a n a ccou n t or y ou a r e log g ed ou t, click th e


Sta r t Codin g bu tton .
3. In th e n ew Pen , fin d th e CSS box , a n d click th e Open CSS
Settin g s bu tton ; it h a s a cog icon ( ).

4. In th e dia log box th a t open s, click th e CSS Pr epr ocessor m en u


(FIGURE 20.3).
Figu r e 20.3 Th e CSS Settin g s dia log box on CodePen

5. Ch oose SCSS fr om th e CSS Pr epr ocessor m en u .


6. Click Close. Now th e CSS box sh ou ld be la beled CSS (SCSS).
You ’r e a ble to ty pe Sa ss sy n ta x in to it n ow .
7. Let’s sta r t sm a ll. You ’ll lea r n a bou t v a r ia bles la ter in th e
ch a pter , bu t for n ow , kn ow th a t th e sy n ta x is a dolla r sig n
($) a n d th e v a r ia ble n a m e. Cr ea te a v a r ia ble for ba ckg r ou n d
color by ty pin g $bgColor: #EB1DFE;.
Th is cr ea tes a v a r ia ble a ssig n m en t w h er e $bgColor h a s th e
v a lu e #EB1DFE.
8. On a n ew lin e, ty pe body {.
9. On a n ew lin e, ty pe background: $bgColor;.
Th e ba ckg r ou n d of th e pen sh ou ld im m edia tely tu r n a da r k
pin k.
10. On a n ew lin e, ty pe }.
11. To v iew th e com piled CSS, click th e a r r ow bu tton on th e
r ig h t ( ).

12. Ch oose V iew Com piled CSS (FIGURE 20.4).

Figu r e 20.4 Th e m en u th a t a llow s y ou to displa y


com piled CSS in th e pen

You r SCSS code is r epla ced w ith com piled CSS, a n d


“ Com piled” a ppea r s in th e title ba r of th e CSS box .

To write Sass using an app on your computer:


1. Go to scou t-a pp.io.
2. Un der Sa ss for Web Desig n er s, dow n loa d th e v er sion of Sa ss
for y ou r com pu ter ’s oper a tin g sy stem (FIGURE 20.5).

Figu r e 20.5 Th e Scou t-A pp w ebsite, sh ow in g th e


dow n loa d bu tton s

For m a cOS, click th e OSX bu tton ; for a PC, click Win dow s.
3. In sta ll th e a pplica tion .
Wh en th e in sta lla tion is com plete, y ou ’ll a dd a pr oject to
Scou t.
4. On y ou r desktop, cr ea te a n ew w ebsite folder . I’v e ca lled
m in e websit e. Th en cr ea te tw o n ew su bfolder s n a m ed scss
a n d css.
5. La u n ch Scou t-A pp, a n d click th e folder icon u n der Im por t
Pr ojects (FIGURE 20.6).

Figu r e 20.6 You ca n loa d a n ex istin g w ebsite in to Scou t-


A pp by dr a g g in g its folder in to th e Im por t Pr ojects a r ea or
by clickin g th e folder icon .
A file n a v ig a tion folder open s.
6. Select th e w ebsite folder y ou cr ea ted in step 4 .
7. On th e A dd Pr oject scr een (FIGURE 20.7), click in th e In pu t
Folder field a n d n a v ig a te to th e scss folder y ou ju st cr ea ted.

Figu r e 20.7 Th e Scou t-A pp Pr oject scr een is w h er e y ou


m a n a g e y ou r pr ojects.

Scou t-A pp is n ow w a tch in g th e in pu t folder for a n y ch a n g es.


8. Click in th e Ou tpu t Folder field, a n d select th e css folder y ou
ju st cr ea ted.
Scou t-A pp w ill a u tom a tica lly sa v e a n y ch a n g es fr om th e
in pu t folder in to th is ou tpu t folder .
9. Test th is ou t. In a tex t editin g pr og r a m , cr ea te a n ew file (it
doesn ’t n eed a n y con ten t) a n d sa v e it a s st y l e.scss in th e
scss folder .
10. Ch eck th e css folder . You sh ou ld n ow h a v e a n ew file n a m ed
style.css.
If y ou don ’t, y ou m a y n eed to pr ess th e pla y bu tton n ex t to
th e pr oject n a m e.

Tip

One great feature of Sass is that it can compile a minified version of your
CSS—meaning without spaces or line breaks. This reduces the file size and
lets browsers download it faster. You will learn more about the advantages of
this in Chapter 23.
VIDEO 20.1

Configuring Sass on Your Computer


If y ou want to write Sass and generate CSS f rom it, y ou’ll need a Sass compiler.
Here’s how to install one on y our machine.

WRITING SASS
At the beginning of this chapter I mentioned that there
are full books and courses created just for Sass. But there
are a few features worth highlighting:

Nestin g selector s

V a r ia bles th a t don ’t r ely on br ow ser su ppor t

Ma th oper a tor s

Ex ten din g r u lesets

Nesting CSS selectors in Sass


One of the cooler features of Sass is its ability to reformat
selectors in nested form, which saves you from having to
write out increasingly long selectors for specificity. The
benefit, besides a better visual representation of the
family tree than in normal CSS, is that you can include
declarations alongside the dependents you want. For
example, this Sass code:
Click h er e to v iew code im a g e

.wrapper {
background: #000000;
color: #FFFFFF;
main {
aside {
border: 1px solid #FFFFFF;
}
}
}

… compiles to this in CSS:

.wrapper {
background: #000000;
color: #FFFFFF;
}
.wrapper main aside {
border: 1px solid #FFFFFF;
}

Notice that the CSS targets aside elements that are


children of main and grandchildren of .wrapper. By
writing the ruleset as nested selectors, it reads, “aside is
inside main, and both of them are inside .wrapper.”
This ensures specificity and makes your CSS easier to
read. And as your CSS grows, you won’t have to worry
about specificity as much—as long as you have the
proper nesting.
An important character for nesting is the ampersand (&).
It serves as a placeholder for the parent selector. So
.wrapper main would become & main. This is
helpful, as it allows you to use the parent (or outer)
selector in more advanced ways, like for pseudo-
selectors. Here’s how to use the parent selector.

To target :first-child while nesting in Sass:

1. In y ou r style.scss file, ty pe p {.
2. Ty pe color: #880000;.
3. On a n ew lin e, in den t a n d ty pe &:first-child {.
4. Ty pe color : #008 8 00;.
5. Ty pe font-size: 1.5rem;.
6. Ty pe }.
7. Ty pe }.

The resulting Sass will look like this:

p {
color: #880000;

&:first-child {
color: #008800;
font-size: 1.5rem;
}
}

It will be compiled to this CSS:

p {
color: #880000;
}
p:first-child {
color: #008800;
font-size: 1.5rem;
}

If you’re using Scout-App, your output might look a little


different. Make sure that in your project settings,
Production is selected and Expanded is chosen from the
Output Style menu (FIGURE 20.8).

Figure 20.8 The settings in Scout-App that will give


you fully expanded CSS output

VIDEO 20.2

More Nesting Examples


I demonstrate more examples of nesting that use the & f eature, as well as some
media queries.

Variables and mathematical operators


In Chapter 19, you learned about CSS custom properties
(variables) and functions. While variables in Sass
became popular before the advent of custom properties
in CSS, the preference for web developers today is to use
CSS’s built-in variables.

Still, Sass variables are worth covering, as you’ll likely


see them if you continue to develop with Sass.
Variables and math in Sass work very similarly to native
CSS variables. The main difference is the syntax. To
define a variable in Sass, instead of using two hyphens (-
-), you use a dollar sign ($):
$bgColor: #EB1DFE;

Then you just type the variable name, as opposed to


using the var() function, like in CSS:

body {
background: $bgColor;
}

Most of the same benefits (like the ability to change


multiple values at the same time by reassigning a
variable) apply to Sass variables, with a few exceptions:

Th ey ca n n ot be ch a n g ed in r ea l tim e.

Th ey ca n n ot be m a n ipu la ted by Ja v a Scr ipt.

Th ey don ’t ca sca de.

To define and use a variable in Sass:


1. A t th e top of y ou r style.scss file, befor e a n y oth er
decla r a tion s, ty pe $fontSize: 1.25rem;.
2. On a n ew lin e, ty pe body {.
3. Ty pe font-size: $fontSize;.
4. Ty pe }.
5. Sa v e th e file.
6. Open th e style.css file a n d ex a m in e th e com piled CSS. It
sh ou ld look like th is:
body {font-size: 1.25rem;}

While this is a single declaration using a variable, you


can imagine using the $fontSize variable in several
places. If that ever needs to change, all you’d need to do
is reassign $fontSize and then recompile the Sass.

The arithmetic operations in Sass are the same as in CSS


(+, -, *, /) and there is one more: modulo or
“remainder,” and that’s represented by a percent sign
(%).

The modulo operator divides two numbers, but instead


of returning a result, it returns the remainder. For
example, 15 % 2 returns the value 1.
Using the same Sass from the previous task, you can use
a multiplier on the font size.

To increase font size with multiplication:


1. In y ou r style.scss file, on a n ew lin e a fter th e closin g } on
th e body r u leset, ty pe h1 {.
2. Ty pe font-size: $fontSize * 3;.
3. Ty pe }.

The compiled CSS will look like this:

h1 {font-size: 3.75rem; }

Notice that you don’t have to specify the unit on the


multiplier—it will use the unit provided in the variable. If
you use different units in arithmetic operators (like rem
* px), you will get an error.

Tip

Math in Sass doesn’t stop with arithmetic operators. There are also built-in
math functions for rounding, min, and max. Learn more here at sass-
lang.com/documentation/modules/math.

Repeatable rulesets with @extend


In CSS, variables make it easier to reuse repeatable
properties, as you saw in Chapter 19. But what if you
could do it with entire rulesets? With the extend rule in
Sass, you can! The extend rule allows one selector to
use (or inherit) the ruleset from another selector. It’s
written @extend [selector].

To use @extend for alerts:

1. In y ou r style.scss, file, cr ea te th e cla ss y ou w a n t to


ex ten d. For th is ta sk, it w ill be a cla ss th a t’s u sed for a ler t
box es. Ty pe .alert {.
2. Ty pe background: #880000;.
3. Ty pe color: #FFFFFF;.
4. Ty pe padding: 10px;.
5. Ty pe text-align: center;.
6. Ty pe }.
7. Now it’s tim e to cr ea te th e cla ss th a t ex ten ds .alert. Th is
cla ss w ill ch a n g e th e a ler t slig h tly , sh ow in g a differ en t
ba ckg r ou n d color to den ote a “ fr ien dly ,” less u r g en t m essa g e.
Ty pe .alert-good {.
8. Ty pe @extend .alert;.
Th is tells Sa ss th a t .alert-good sh ou ld u se a ll of th e r u les
defin ed in .alert.
9. Ty pe background: #000088;.
Th is ov er r ides th e or ig in a l r u les to sh ow th e ch a n g e in
.alert-good. In th is in sta n ce, it’s on ly th e ba ckg r ou n d
color .
10. Ty pe }.
11. Sa v e th e file a n d ex a m in e th e com piled CSS file (CODE 20.1).

With extend rules, you don’t need to copy and paste or


otherwise rewrite rulesets! Sass also neatly compiles
classes that use extend rules to prevent code bloat.
Notice how it combines the selectors into a comma-
separated list instead of repeating the rulesets for each
selector (FIGURE 20.9).

Figure 20.9 The .alert and .alert-good classes


in use

CODE 20.1 The resulting CSS a er using extend for the .alert and .alert-
good classes

.alert, .alert-good {
background: #880000;
color: #ffffff;
padding: 10px;
text-align: center;
}
.alert-good {
background: #000088;
}

Y ou can also use multiple extends in a ruleset, which


allows you to include multiple definitions without having
to write them (FIGURE 20.10). The class will simply
inherit the styles from both selectors. So if you have a
class called .big:

Figure 20.10 The .alert-good class is extending


both .alert and .big.

.big {
font-size: 3rem;
}

Y ou can do something like this, using the Sass from the


previous task:

.alert-good {
@extend .alert;
@extend .big
background: #000088;
}

The resulting CSS can be seen in CODE 20.2.


Finally, you can also write placeholder classes that exist
only to be extended. There are no references to
placeholder classes in the compiled CSS. This is strictly
for you to use in Sass. Placeholders are great if you have
a style you want to use across multiple rulesets, but you
don’t want those rulesets associated with a usable class,
which would muck up your CSS.
Y ou define a placeholder class with the percent sign (%).
The % is an indicator in Sass that you’re using a
placeholder class and that it should not be compiled as a
usable class in CSS.

To write a placeholder class:


1. In y ou r style.scss file, ty pe % follow ed by th e n a m e of th e
pla ceh older cla ss y ou w a n t to defin e. In th is ca se, u se notify
{.
2. Ty pe margin: 0 auto;.
3. Ty pe padding: 10px;.
4. Ty pe text-align: center;.
5. Ty pe }.
6. Ty pe .alert {.
7. Ty pe @extend %notify;.
8. Ty pe background: #880000;.
9. Ty pe color: #FFFFFF;.
10. Ty pe }.
11. Ty pe .error {.
12. Ty pe @extend %notify;.

13. Ty pe background: #FEB728; ( ).

14. Ty pe }.
15. Sa v e th e .scss file a n d ex a m in e th e com piled CSS (CODE
20.3).

CODE 20.2 The results of .alert-good extending two other classes. Notice
that .alert-good is referenced in both the .alert and .big declarations.

.alert, .alert-good {
background: #880000;
color: #ffffff;
padding: 10px;
text-align: center;
}
.big, .alert-good {
font-size: 3rem;
}
.alert-good {
background: #000088;
}

With placeholder classes, applying that class name to an


element (notify in this case) will do nothing.
Notice there’s no reference to %notify, and that all the
properties from %notify are grouped together, leaving
only the custom properties in their own rulesets
(FIGURE 20.11).

Figure 20.11 The .alert and .error classes


generated from the %notify placeholder class

Tip
There’s one more aspect of Sass that’s important: mixin. It is similar to
extend, but there are some important differences to understand. I chose to
include extend here because it’s more in line with what you’ve already
learned. If you want to learn about mixin, you can do so at sass-
lang.com/documentation/at-rules/mixin.

CODE 20.3 These classes were generated from a placeholder class in Sass.

.alert, .error {
margin: 0 auto;
padding: 10px;
text-align: center;
}
.alert {
background: #880000;
color: #ffffff;
}
.error {
background: #feb728;
}

WRAPPING UP
This was only a brief introduction to CSS preprocessors,
and you’ve only scratched the surface with Sass. But it’s
important to know about as you continue to build
websites, and you’re very likely to come across it.

With that, the CSS section of this book is complete. From


here, you’ll learn important concepts and tools to help
you build better websites. But there’s one important step
to take first: we need to get your website online!
21

Getting Your Website Online


In This Chapter

Choosing Hosting and a Domain


Pre-Launch Check

Making Y our Site Live


Testing Y our Site

Wrapping Up

Y ou have the HTML down. Y ou have the CSS down.


Y our files are nice and organized. How do you show it to
people?
Getting your website online requires two components
you saw all the way back in Chapter 2: a domain and a
server. Once you have those, there’s a clear process you’ll
walk through to get your website online. Then you can
send it to everyone you know!

CHOOSING HOSTING AND A DOMAIN


The time has come for you to make some decisions. Y ou
need to purchase both a domain and web hosting for
your website. When you purchase a plan from a hosting
company, the company provides you with the
technologies and services that you need for your website
to be seen on the internet.
At the most basic level, your hosting provides you with a
publicly accessible space on a server that stores and
manages connections to your website. People will
connect to your website via the domain.
There are lots of different hosting companies. Many
specialize in specific types of websites, but any hosting
you get will be able to serve up HTML and CSS. So how
do you choose?

Evaluating hosting
When choosing the right hosting for your needs, there
are a few ways to evaluate them. While there isn’t a
“one-size-fits-all” hosting company, drawing up a list of
your needs will help you narrow down the requirements
a bit. So what do you look for?

Ca n y ou ta lk to a per son ? If y ou ’r e g oin g to be settin g u p


a n d su ppor tin g y ou r ow n w ebsite, y ou sh ou ld m a ke su r e
th e h ostin g com pa n y y ou g o w ith pr ov ides g ood
tech n ica l su ppor t! Gr ea t docu m en ta tion a n d v ideos a r e
fin e, bu t ch a t a n d ph on e su ppor t a r e in cr edibly
im por ta n t a s w ell.

Will th er e be a u tom a tic ba cku ps? Th is isn ’t a dea l


br ea ker a s fa r a s ch oosin g th e pla n , bu t it’s im por ta n t to
kn ow w h eth er y ou w ill n eed to m a ke y ou r ow n ba cku ps
or if th ey h a n dle th a t for y ou .

Will th ey h elp m a ke y ou r site secu r e? Th is ca n com e in


m a n y for m s, in clu din g site m on itor in g , fr ee SSL (see th e
“ Secu r e Dom a in s” sideba r ), pr otection fr om cy ber
a tta cks, a n d r epa ir in g y ou r w ebsite if it’s h a cked.

Tip
Many people use the term SSL when speaking of website security in general,
even though SSL technically refers only to the Secure Sockets Layer
cryptographic protocol. That technology itself has been deprecated in favor
of the newer Transport Layer Security (TLS) protocol.

Pricing can also be a factor. Y ou generally get what you


pay for, and at this stage of the game, you probably don’t
need anything too crazy, especially if you’re still honing
your skills. There are two hosts I’d recommend:

Web Hostin g for Stu den ts: If y ou n eed som eth in g r ea lly
ch ea p to $2 5 /y ea r (FIGURE 21.1):
w ebh ostin g for stu den ts.com /.
Figu r e 21.1 Web Hostin g for Stu den ts

SiteGr ou n d: On ce y ou ’r e r ea dy to pu blish y ou r site to


th e w or ld (a lso kn ow n a s “ g oin g liv e” ), y ou ’ll n eed to
m ov e on fr om a ba sic ser v ice like Web Hostin g for
Stu den ts. SiteGr ou n d is v er sa tile a n d w or ks w ell for lots
of ty pes of sites (FIGURE 21.2). If y ou u se th e lin k fr om
th is book, y ou ’ll g et a specia l offer for y ou r fir st y ea r :
ca sa bon a .or g /g o/siteg r ou n d/.

Figu r e 21.2 SiteGr ou n d

Choosing a domain
Usually, you can purchase domains from the same place
you get your hosting, but it’s not always recommended
in case one day you decide you want to change hosts.
Certain companies offer one free domain with an
account, but if you’d like to purchase a domain
separately, which I recommended, hover.com is a great
service. They offer a number of different top-level
domains (TLDs) from .com and .org to .io, .me, and
.xyz.

Tips on choosing a domain name:

Ma ke it u n iqu e a n d ea sy to r em em ber . You w a n t y ou r


dom a in to sta n d ou t, bu t n ot so m u ch th a t it’s difficu lt to
r em em ber w h en som eon e tr ies to v isit.

Ma ke it ea sy to ty pe a n d spea k. A dom a in w ith a tr icky


n a m e w ill sen d people to th e w r on g pla ce or dissu a de
th em fr om v isitin g a t a ll. On th a t sa m e token , tr y to
a v oid n u m ber s a n d h y ph en s. Th ey a r e v er y h a r d to
spea k (is th e n u m ber ty ped ou t or is it th e dig it?), a n d
h y ph en s a r e often for g otten a bou t.

Tr y to a cqu ir e a n a m e in th e .com dom a in fir st. A bou t


7 0 per cen t of dom a in s u se th e TLD .com , ev en a s th e
n u m ber of TLDs g r ow s. Th a t m ea n s th a t m ost people w ill
h a v e a n ea sier tim e r em em ber in g a .com dom a in a n d
w ill likely tr y th a t fir st.

Ma ke it a s sh or t a s possible. Th is g oes ba ck to m a kin g it


ea sy to r em em ber , spea k, a n d ty pe—joesba ker y .com is
ea sier to r em em ber (a n d spell) th a n
joesdow n in g tow n ba ker y .com .

A v oid copy r ig h ted n a m es. Ma ke su r e y ou ’r e n ot u sin g a


copy r ig h ted ter m in y ou r dom a in . Th e la st th in g y ou
w a n t to do is ch a n g e it beca u se y ou ’v e in fr in g ed
som eon e’s copy r ig h t. A n ex a m ple is w ordpres s .
A ccor din g to th e Wor dPr ess Fou n da tion , w h o h olds th e
copy r ig h t for Wor dPr ess, y ou ca n n ot u se w ordpres s in a
dom a in n a m e.

Be a w a r e of w or d com bin a tion s. Th is sou n ds silly a n d


som ew h a t ju v en ile, bu t y ou don ’t w a n t to a cciden ta lly
cr ea te a v u lg a r dom a in .

Secure Domains
You might notice that some domains use the http:// pref ix and others use
https://. The dif f erence is that https:// indicates that the site accepts
connections using the Hy pertext Transf er Protocol Secure, which in turn
employ s Transport Lay er Security, or TLS. In general conv ersation, TLS
is of ten lumped in together with its predecessor, SSL. A domain using
HTTPS will be of f ered a TLS certif icate.

This means any data sent to and f rom y our website will be transmitted
securely ; y ou will want this if y ou’re processing pay ments, taking user
inf ormation, or logging in with a username and password.
There are also search engine optimization (SEO) benef its. Google uses
https as a “ranking signal”—something it uses to ev aluate how high to
rank y our website in search results. In Chrome, it warns users when https
is not in use.
This is conf igured by the serv er, and SiteGround of f ers f ree TLS/SSL
certif icates through Let’s Encry pt.
Sn a g th e m a tch in g socia l m edia if y ou ca n . Ma tch in g
dom a in n a m es w ith socia l m edia a ccou n ts ta kes a w a y
th e g u essw or k for u ser s.

Keep in mind that this is not a checklist. If you have the


perfect domain but it uses a number, use the number.
Since you can point two domains to the same website,
grab it spelled out and with a digit. If a .com isn’t
available, buy the .org instead.

The goal is to do the best you can, and most of all make
it relevant to your website’s topic.

One Note on Email


“Do I get an email address?” is a common question when purchasing a domain and
hosting. Email is a separate serv ice and theref ore not alway s included.
You will usually f ind email of f ered as an add-on to hosting, but there are alternativ e
solutions av ailable. Hov er.com of f ers email f orwarding, f or example.
You can also sign up f or something like Google Apps f or Business, though this
requires extra setup.

To register your domain:


1. V isit h ov er .com .
2. Use th e sea r ch box to ty pe in y ou r dom a in idea (FIGURE
21.3).

Figu r e 21.3 Th e sea r ch box on h ov er .com

You ca n in clu de or ex clu de a TLD. Hov er w ill still sh ow y ou a


fu ll list of a v a ila ble dom a in s.
3. Pr ess En ter or click th e sea r ch icon .
4. You ’ll be ta ken to a scr een of a v a ila ble dom a in s. Click th e
plu s sig n n ex t to th e on e y ou w a n t.
5. Click th e Sh oppin g Ca r t bu tton in th e top r ig h t (FIGURE
21.4).
Figu r e 21.4 Th e Sh oppin g Ca r t bu tton on h ov er .com

6. Go th r ou g h th e ch eckou t pr ocess a n d cr ea te y ou r a ccou n t!

VIDEO 21.1

Registering a Domain
Here’s the entire process, start to f inish, of registering a domain with hov er.com.

Connecting your domain


Once you’ve purchased your domain, if you haven’t
done it through your hosting company, you’ll need to
point it to your host. This will vary based on both your
host and your domain registrar.

Y our host should provide instructions for changing


what’s called the DNS, Domain Name System. Y ou can
think of it as a big lookup table (or address book),
associating servers with domains.

Tip
Once you purchase your domain and point it to a server, it may take 24 to 48
hours to work. This is a process known as propagation.

In Video 21.2, you’ll see how to do it with Hover and


SiteGround.

VIDEO 21.2

Pointing Your Domain to SiteGround


Here’s how y ou’ll point y our domain, registered through Hov er, to SiteGround hosting.

PRE-LAUNCH CHECK
Before taking your site online, you’ll want to run
through a quick checklist:
1. Is y ou r w ebsite folder or g a n ized th e w a y y ou ’d like it to be?
You w ill u ploa d it ju st th a t w a y , so dou ble-ch eck.
2. A r e a ll of y ou r lin ks, em beds, a n d r efer en ces pr oper ly
for m a tted? Ma ke su r e th a t if y ou ’r e lin kin g to som eth in g in a
ch ild folder , it’s in th e r ig h t pla ce, a n d th a t a ll im a g es a n d
oth er m edia displa y pr oper ly .
3. A r e th er e a n y r efer en ces to files th a t sta r t w ith file: or C:?
Th ese a r e a bsolu te lin ks to th e files on y ou r com pu ter , a n d
th ey w ill n ot w or k for a n y on e oth er th a n y ou on ce th ey a r e
u ploa ded, so m a ke su r e to ch a n g e th em to r ela tiv e lin ks.

It’s best to click through each page and make sure


everything looks and works as you expect. Once you do
that, you’re ready to upload your files to your server.

MAKING YOUR SITE LIVE


With your hosting and domain purchased, it’s time to get
your site online—sometimes referred to as deploying
your site. To do that, you’ll need to use something called
File Transfer Protocol, or FTP.

FTP is how you send files from your computer to the


server. To do this, you’ll need an FTP program. A free
(and widely used) one is FileZilla (FIGURE 21.5). Y ou
can download it at filezilla-project.org.

Figure 21.5 FileZilla, a popular FTP program

Finding FTP Information


Finding the FTP inf ormation f or y our serv er will v ary f rom host to host. For
SiteGround, it’s best to use their documentation, just in case it changes af ter the
time of this writing: www.siteground.com/tutorials/f tp/accounts/.

Once you download that, you’ll see you need some


information:

Host
Th is m ig h t a lso be listed a s h ost a ddr ess, IP a ddr ess,
dom a in , or ser v er a ddr ess.

User n a m e

Pa ssw or d

Por t
A por t is a com m u n ica tion g a tew a y in a com pu ter (or
oth er dev ice) defin ed in softw a r e. Usu a lly , in div idu a l
por ts a llow for a specific n etw or k ser v ice to pa ss
th r ou g h . You ca n th in k of it a s a dockin g ba y or a s a
locker th a t y ou h a v e th e key to.

This information can be found through your hosting


account. Look for a section of the documentation that
includes “FTP” in the title.
Once you find that information, you’ll fill it into the
appropriate fields in FileZilla. Then you’ll connect to your
server. Once you connect, you’ll see two panels: on the
left-hand side will be your computer; on the right, your
server.

To send files to your server with FileZilla:


1. Usin g th e in for m a tion fr om y ou r h ostin g pr ov ider , fill in th e
h ost, u ser n a m e, pa ssw or d, a n d por t.
2. Click Qu ickcon n ect.
3. On ce th e r ig h t pa n el popu la tes, y ou ’ll w a n t to loca te th e
public_html or www folder . Th is is w h er e a ll w eb-a ccessible
files w ill liv e.
You m ig h t a lr ea dy be in th a t folder . You ca n u se th e Rem ote
Site ba r a bov e th e r ig h t pa n el to see w h er e y ou a r e (FIGURE
21.6).
Figu r e 21.6 Th e Rem ote Site box in FileZilla w ill sh ow
y ou w h er e y ou ’r e u ploa din g files to on y ou r ser v er .

VIDEO 21.3

Uploading Your Files


You’ll get a quick tour of FileZilla, f ind y our FTP inf ormation (if y ou use
SiteGround), and then upload y our f iles.

4. In th e pa n el on th e left, m a ke su r e y ou ’r e displa y in g th e
con ten ts of y ou r w ebsite folder .
5. Dr a g ea ch file a n d folder in y ou r w ebsite folder fr om th e left
pa n el to th e r ig h t pa n el (FIGURE 21.7).

Figu r e 21.7 Th e sta te of FileZilla on ce y ou u ploa d y ou r


site

Rem em ber n ot to ju st dr a g th e w ebsite folder ov er . Th is w ill


r esu lt in y ou r w ebsite files bein g loca ted in a ch ild folder .
6. On ce th e files u ploa d, v isit y ou r dom a in w ith a br ow ser . Th e
files on y ou r w ebsite sh ou ld r en der pr oper ly a n d displa y a s
y ou desig n ed th em !

TESTING YOUR SITE


Now that your website is uploaded to the server, it’s time
to give it a test. Use your browser to visit your site at the
domain you purchased, click through all of the links, and
make sure your images and other media are showing up
properly.
Check each file
If you can, check the site on a computer other than your
own to double-check that you didn’t leave any absolute
links to files on your computer in the HTML documents.
Those will still work for you (because they’re located on
your computer), but they won’t work for anyone else.

The same goes for all links. Y ou’ll want to make sure
internal links are still going to your site, and that
external links are reaching the intended destination.

Test in common browsers


Y ou’ll learn more about testing in the next chapter, but
for the purposes of making sure your freshly uploaded
site is working properly, you’ll want to check in at least a
few browsers, like Safari, Edge, Chrome, and Firefox.

As you’ve seen, browsers handle things differently, and


checking your site in multiple browsers will increase the
changes that you’ll find something that’s broken before
your users do.

WRAPPING UP
Congratulations! Y ou did it! Y ou’ve uploaded your site to
a server and it’s now live. But your job is not done.
With all of the basics down, it’s time to dive into some
advanced but important topics. And the first is testing
your site for a multitude of issues, from broken HTML
and CSS to device support.

404 Errors
Something y ou hav en’t seen y et, f or y our own site at least, is a 404 error. This is a
common error f or websites that means “f ile not f ound.”
If someone tries to v isit a f ile on y our website that doesn’t exist, the serv er will send
a 404 error, alerting the user that what they ’re try ing to access isn’t there.

404 errors can happen because of a ty po in a f ile, because of a f ile that was nev er
uploaded to the serv er, or when a link to an external site lacks the https:// pref ix,
among other reasons.
22

Testing Your Website


In This Chapter

Why Test Y our Website?


Validating Markup

Browser Testing
Device Testing

Troubleshooting with Chrome Developer Tools


Wrapping Up

Now that you know how to build and launch a website,


it’s time to look at some other areas of web design that
you should become familiar with. The first is testing.

Up until now you’ve been writing some code and


checking it in whatever browser you use. Perhaps you’ve
been resizing the browser to see how it looks at different
sizes. But there’s a bit more you can and should do.

WHY TEST YOUR WEBSITE?


Y ou might be wondering why you have to test your
website beyond just checking it in your browser to make
sure it doesn’t look broken. Because websites need to run
properly everywhere that a web browser can run (which
is basically everywhere), we need to test everywhere.
That means testing in major browsers, on different
platforms, and at different device screen sizes.

There are also a lot of unknowns in web development.


Y ou don’t know what users are going to do. Y ou don’t
know if they have an ad-blocker that’s somehow
affecting your website. Y ou don’t know the speed of their
internet connection.
Finally, since HTML is very forgiving—you can write
HTML in several different ways and the code will still
work for you—you could run into situations where
devices other than your own interpret your markup
differently. This is especially true if your HTML is not
valid—that is, written properly to specification, as defined
by the DOCTYPE.

When you test your website, you should follow a three-


pronged plan:

V a lida te y ou r HTML a n d CSS.

Test in br ow ser s.

Test on dev ices.

As you do those things, you can troubleshoot the


problems you encounter using some very helpful tools.

VALIDATING MARKUP
Y ou want to validate your markup first because it will
find any glaring errors in your HTML—absent closing
tags, improper usage, or syntax errors.
Syntax errors are found in code that’s incorrectly typed
(FIGURE 22.1). Perhaps the closing bracket (>) is
missing from a tag or you left a quotation mark out of
your HTML. These lapses can cause big errors on your
page that could go unnoticed if your browser of choice
doesn’t flag them.
Figure 22.1 Invalid code alerts generated by a syntax
error in HTML. These are two of the many issues the
error causes.

Luckily, there’s a single validator that will check your


HTML and CSS and even look for broken links.

The W3C markup validator


The World Wide Web Consortium (W3C) is the
international organization that creates the standards and
specifications for HTML and CSS.
They also happen to have a markup validator that you
can use to make sure your HTML and CSS code meets
their standards (FIGURE 22.2).

Figure 22.2 The W3C Markup Validation Service


home page (validator.w3.org/)
There are three ways to send your markup to the
validator:

Pr ov ide th e URI (or th e dom a in ) of th e file.

Uploa d th e file.

Copy a n d pa ste th e m a r ku p in to a tex tbox (ca lled direct


input).

Since the CSS for your site is in a separate file, file upload
and direct input will be a little tricky (though not
impossible). In general, you should choose the URI
option.

To validate your markup:


1. V isit v a lida tor .w 3 .or g .
2. Click th e V a lida te by URI ta b.
3. Ty pe y ou r w ebsite’s dom a in in to th e A ddr ess field.
4. Click th e Ch eck bu tton .
5. Rev iew y ou r r esu lts a n d fix th e er r or s. Th ese ca n br ea k y ou r
site in cer ta in br ow ser s.
You m a y a lso see w a r n in g s th a t in dica te im pr oper or
u n n ecessa r y u se. You ca n (a n d sh ou ld) fix th ese, bu t th ey do
n ot r isk br ea kin g y ou r w ebsite.

Though validating your code will likely save you a lot of


time by helping you eliminate errors on your website,
that doesn’t mean it will solve all of your issues. For that,
you’ll need to do your own testing, starting with different
browsers.

VIDEO 22.1

Using the W3C Markup Validator to Find and Fix Errors


Now that y ou know how to use the v alidator, it’s time to see how to use the
inf ormation it prov ides to make f ixes.

BROWSER TESTING
The low-hanging fruit for testing is browser testing.
That’s when you view your website in the major
browsers to make sure everything looks good.
Remember that browsers may not implement new
HTML features at the same time, and each browser
interprets CSS differently. So you’ll want to check your
website in the following desktop browsers. Y ou can get
three of the four depending on your operating system:

Ch r om e (dow n loa d for m a cOS/Win dow s)

Fir efox (dow n loa d for m a cOS/Win dow s)

Sa fa r i (m a cOS on ly ; com es on m a cOS)

Edg e (com es on Win dow s; dow n loa d for m a cOS)

For each browser, check each page of your website to


make sure things don’t look completely broken. That
means broken or misaligned layouts, unreadable text, or
other things that look completely off.

Websites do not need to look the same in every browser,


though! So if there are some minor differences due to
padding, that’s okay. The CSS reset method mentioned in
Chapter 12 should take care of most of those issues, but
don’t sweat the minor differences too much (FIGURE
22.3).
Figure 22.3 Comparing a website in Chrome and
Safari. The site looks exactly the same in both
browsers—huzzah!

Browser and device testing tools


Y ou won’t always have access to every browser or to a
wealth of devices to test your websites on. Luckily, there
are several tools that will help you with your testing
when you need it.
The longtime favorite for many pros is BrowserStack
(browserstack.com), which will provide real-time testing
on actual devices, giving you a more robust and accurate
testing environment (FIGURE 22.4).

Figure 22.4 Testing a website with BrowserStack


They offer a free tier if you’re starting out, but it can get
expensive pretty quickly, especially if you need to test for
more than 30 minutes. Another option is LambdaTest
(lambdatest.com). There is a free tier here that will let
you perform a limited amount of real-time browser
testing. It should be enough for the types of sites created
in this book.

DEVICE TESTING
In the world of mobile browsers and the Internet of
Things (a system that connects almost any kind of object
to the internet), it’s important to make sure your
websites work on mobile devices and on networks with
different internet speeds.
While BrowserStack is a great option for doing browser
testing to test on browsers and devices you don’t natively
have access to, it’s important for you to test on devices
you’re physically using as well (even if it’s not all of
them). Y ou’ll want to make sure that your site:

Resizes cor r ectly on a r ea l scr een

Loa ds qu ickly

Is u sin g su ppor ted fea tu r es or a ppr opr ia te fa llba cks

It’s important to use real devices for this because


although you can check actual devices through your
computer on BrowserStack or by emulating devices
(using a computer-generated version of the device),
there’s nothing like the real thing.

What you should test


There is a seemingly infinite number of combinations of
devices, operating systems, and connection speeds, and
it’s impossible to test all of them. So what do you do?
For devices, you should check a resource like Device
Atlas, which will tell you the most popular mobile
devices by country (deviceatlas.com/device-
data/explorer/).
On the actual devices, you should test the built-in
browser. Y ou should look up what the most popular
browsers are to make sure you’re covering the bases.
Statcounter has good data for this: gs.statcounter.com/
(FIGURE 22.5).

Figure 22.5 Browser stats from Statcounter

Y ou’ll want to test the most popular browsers and


devices at least, to make sure everything is working.
Internet connection speeds are a little easier to simulate.
There are a few testing tools you’ll learn about later in
this chapter, and in Chapter 23 when you learn about
improving performance. But for now, here’s a short list
of connections you should check:

Hig h -speed in ter n et (if y ou r site loa ds slow ly h er e, y ou ’ll


n eed to m a ke som e a dju stm en ts).

Cu r r en t cellu la r in ter n et con n ection s—5 G a t th e tim e of


th is w r itin g .

Tw o pr ev iou s g en er a tion s of cellu la r n etw or ks (4 G a n d


3 G a t th e tim e of th is w r itin g ).

Ex tr em ely slow in ter n et.


For th is y ou m ig h t tr y a cr ow ded coffee sh op or libr a r y .
The goal here is to make sure your site doesn’t load too
slowly. It creates a poor user experience.

Finding test devices


Whereas checking browsers and simulating slow internet
connections can be done in software, testing on actual
devices requires access to hardware.

Y ou’re probably not buying a ton of hardware to test


your websites, but you can send the site to a few friends
who have different devices and different-sized devices.
Y ou can also leverage social media here. Send out a
message asking people to visit your site and send a
screenshot or report what’s going on. Y ou can even ask
them to use yourbrowser.is (yourbrowser.is/generate) to
generate a report about their device so you don’t need to
guess (or have them guess) (FIGURE 22.6).

Figure 22.6 My browser information, as reported by


yourbrowser.is

As a last-ditch effort, you could always go to a cellphone


carrier’s store and test devices there! I’ve done it when in
a pinch (though just be aware that they might not like
it).

If you’re really stuck, an emulator is better than nothing.


By using Xcode on macOS (FIGURE 22.7) and
Android Studio on macOS or PC, you can emulate
devices to test on.
Figure 22.7 The iPhone 11 Pro Max, displayed in
XCode’s Simulator

To emulate an iPhone with Xcode for macOS:


1. In y ou r A pplica tion s folder , dou ble-click th e Xcode icon .
If it’s n ot pr e-in sta lled, y ou ca n dow n loa d it fr om th e A pp
Stor e. You m a y n eed to u pda te it. If y ou do, r u n th ose
u pda tes.
If th e Welcom e To Xcode w in dow open s, click th e X in th e
u pper -left cor n er to dism iss it.
2. A fter Xcode open s, in th e m a in m en u ba r , ch oose Xcode >
Open Dev eloper Tool > Sim u la tor .
Sim u la tor m ig h t ta ke a few m in u tes to open , depen din g on
th e speed of y ou r m a ch in e.
3. On ce Sim u la tor loa ds th e iOS or iPa dOS dev ice, click th e
Sa fa r i icon .
4. In th e a ddr ess ba r , ty pe th e URL of y ou r w ebsite.
5. If y ou w a n t to test oth er dev ices, y ou ca n ch oose Ha r dw a r e >
Dev ice, th en ch oose th e oper a tin g sy stem a n d dev ice y ou
w a n t to test.

Even if you already have an iPhone, this is an easy way


to test your site on other iPhone versions or on various
iPad models.

VIDEO 22.2

Using the Xcode Simulator


Once y ou access the Simulator in Xcode, there are sev eral f eatures worth exploring.
Here’s a quick tour of them.

VIDEO 22.3

Emulating Android Devices


If y ou already hav e an iPhone but want to test y our site on Android dev ices, y ou can
do so with Android Studio. Here’s how.

TROUBLESHOOTING WITH CHROME


DEVELOPER TOOLS
One staple of web development troubleshooting has been
to use the development tools built into web browsers. All
of the major browsers offer these, but we’ll use the
developer tools provided in Chrome, officially named
Chrome DevTools. This is a set of tools you can use to
check markup, CSS, webpage load speed, and
downloads. Y ou can also test responsive web designs as
well as perform a whole host of other tasks that will
make your job as a web designer easier.

To access Chrome DevTools:


1. In Ch r om e, click th e m en u bu tton in th e u pper -r ig h t cor n er
of th e w in dow ( ) to open a m en u .

2. Ch oose Mor e Tools > Dev eloper Tools fr om th e m en u .

A new screen will pop up on the right, showing the


source code of your website (FIGURE 22.8).

Figure 22.8 The Chrome DevTools panel is to the


right of the browser window by default.

VIDEO 22.4

Chrome DevTools Overview


In order to quickly f amiliarize y ou with Chrome Dev Tools, y ou’ll get an ov erv iew of
what each tab does and how to nav igate the panel.

A common use case for Chrome DevTools (and for the


developer tools in any browser) is to change part of the
CSS on the site to get a preview of how it looks before
committing those changes to code.
For example, if your intended three-column layout is
displaying as two columns, you can adjust the CSS in
developer tools, note the required changes, and then
make them to the actual source file.
This is a bit faster than making the changes in code,
saving, uploading, and testing.

Y ou can also test color schemes, fonts, and other styles


much more quickly.

To modify CSS with Chrome DevTools:


1. V isit y ou r w ebsite.
2. Open Ch r om e Dev Tools.
3. Select on e of th e elem en ts fr om y ou r m a r ku p by clickin g it
in Dev Tools (FIGURE 22.9).

Figu r e 22.9 Selectin g a n HTML elem en t in Ch r om e


Dev Tools

4. In th e Sty les ta b (w h ich displa y s th e CSS for th e pa g e), a t th e


bottom of th e Elem en ts pa n el below th e HTML listin g , click
n ex t to th e open in g cu r ly br a ce for th a t elem en t’s r u leset
(FIGURE 22.10). Th is w ill cr ea te a n ew lin e in th e r u leset.
Figu r e 22.10 Modify in g CSS in Ch r om e Dev Tools

5. Pla ce y ou r cu r sor on th a t n ew lin e, a n d ty pe color:.


6. Pr ess Retu r n /En ter to m ov e to th e n ex t field.
7. Ty pe #FF0000;.
Now , a ll of th e n ex t in th a t elem en t sh ou ld tu r n r ed.

Mobile device testing with Chrome DevTools


Another common use case for Chrome DevTools is to
test different screen widths and even connection speeds.
While this isn’t a substitute for actual device testing, this
will help you find media query and performance issues.

To test in different screen sizes:


1. V isit y ou r w ebsite.
2. Open Dev Tools.

3. Click th e Tog g le Dev ice Toolba r bu tton ( ).

4. Notice th a t y ou r w ebsite’s w idth h a s n ow ch a n g ed (FIGURE


22.11), a n d th er e’s a n ew toolba r w ith a n item la beled
Respon siv e. Click th a t la bel a n d ch oose on e of th e oth er
dev ices fr om th e list.

Figu r e 22.11 Th e Respon siv e dev ice test section of


Ch r om e Dev Tools

5. Now click th e m en u a g a in a n d ch oose Respon siv e. In th is


m ode, y ou ca n m a n u a lly ch a n g e th e w idth . Ch a n g e it to on e
of y ou r br ea kpoin ts.
6. In th a t sa m e toolba r , th er e’s a m en u la beled On lin e. Th a t
lets y ou con tr ol th e loa d tim e of th e w ebsite. Ch oose Low -En d
Mobile a n d r efr esh th e pa g e. You sh ou ld n otice it ta kes m u ch
lon g er for y ou r w ebsite to loa d.
You ca n see ex a ctly h ow lon g by con su ltin g th e Netw or k ta b
of th e Elem en ts pa n el. See m or e in V IDEO 22.5.

VIDEO 22.5

Responsive Testing in Chrome


Chrome of f ers a robust set of tools f or testing y our website on a v ariety of mobile
dev ices and networks. Here’s a walkthrough of those f eatures and the inf ormation
y ou can get f rom them.

WRAPPING UP
Testing is an important part of web design because it
ensures your website works for as many people as
possible. By checking for valid markup and viewing your
website in as many browsers and on as many devices as
feasible, you’re helping your website visitors.
Another way you can help your visitors is by making
sure your website loads quickly. Let’s look at how to do
that in the next chapter.
23

Improving Website
Performance
In This Chapter

What Do We Mean by Performance?


Know How Y our Website Performs

Performance Testing Tools


Minify HTML and CSS Files

Optimize Y our Images


Load Y our Critical CSS First

Wrapping Up

Depending on the study cited, from 40 to 80 percent of


users will abandon a website if it takes more than four
seconds to load. According to one study, Amazon loses
$1.6 billion per year for every second of load time
(medium.com/@vikigreen).
While your losses won’t be quite that great (at least
when you’re starting out), you should always look to
improve the performance of your website because a slow
website will cost you users. Aside from that, better
performance will improve your site’s user experience
(UX), increase user engagement with your content, and
even help boost your site’s page rank in Google.

WHAT DO WE MEAN BY
PERFORMANCE?
Before getting too far into the weeds, you need to know
what web professionals mean by performance. Getting
to the heart of it, performance is measured by two
criteria:

Loa d tim e: How lon g it ta kes for a w ebsite to be deliv er ed


to th e u ser fr om th e tim e th ey r equ est it.

In ter fa ce efficien cy : How lon g it ta kes for som eth in g to


h a ppen on ce a u ser in ter r ea cts w ith y ou r w ebsite—
clickin g a lin k, fillin g ou t a for m , a n d so on .

Tip

Load time is sometimes also measured as “perceived” load time. This


essentially means that if you show the user something, even if it isn’t the
entire website, they’ll feel like the website is loading faster.

Tip
Interface efficiency is also referred to as “responsiveness.” So as not to
confuse this with the practice of designing websites for all screen sizes, I use
the term efficiency.

The goals in making your site perform as well as possible


in terms of page load speed and how quickly it reacts to
user interactions (referred to as being more performant)
are a fast load time (under three seconds for any
network speed) and to provide the user with feedback as
soon as they do something on your website. This can be
as simple as hover states on links.

Now that you know what performance means and why


your website should be performant, let’s take a look at
the how.

KNOW HOW YOUR WEBSITE


PERFORMS
Before you start optimizing for performance, you need to
know how well your website performs in the first place.
Often this has to do with the amount of data you’re
sending from the server to the user’s browser. The more
data, the slower a website loads.
Common performance factors
Y ou’ll learn about some tools to help you pinpoint
specific performance issues, but there are a few common
culprits:

Im a g es: Hu g e im a g e files r epr esen t a lot of da ta th a t


n eeds to be tr a n sm itted. A n d often , th ey don ’t n eed to be
a s big a s th ey a r e.

Oth er m edia : You m ig h t con sider im a g es fir st beca u se


th ey a r e m or e in y ou r con tr ol. With oth er m edia , like
a u dio a n d v ideo files, y ou ’r e pr oba bly u ploa din g th em to
a ser v ice like Sou n dClou d or You Tu be, a n d th ose ser v ices
w or k h a r d on im pr ov in g per for m a n ce. Ev en so,
em beddin g too m a n y v ideos or pieces of a u dio on a pa g e
ca n still slow dow n y ou r w ebsite.

Bloa ted HTML a n d CSS: Usin g too m u ch m a r ku p or too


m a n y sty les ca n lea d to big g er HTML a n d CSS files,
w h ich lea ds to slow er loa d tim es. La ter in th is ch a pter
I’ll ta lk a bou t w a y s to dia g n ose th ose pr oblem s a n d fin d
solu tion s to th em . On top of th a t, a s y ou in clu de m or e
files (like Ja v a Scr ipt libr a r ies), dow n loa din g ea ch on e
r equ ir es a sepa r a te r equ est to th e ser v er . Mor e r equ ests
a lso lea d to lon g er loa d tim es.

Hostin g : It’s ea sy to bla m e h ostin g for per for m a n ce


issu es, bu t th e tr u th is a ba d h ost w ill r esu lt in a slow er
site. If y ou ’r e u sin g a h ostin g com pa n y th a t ov er w or ks
its ser v er s or u n der in v ests in r esou r ces for th ose ser v er s,
y ou ca n h a v e a sin g le lin e of tex t in a file loa d slow ly .
Wh ile y ou ’r e lea r n in g , it’s oka y to skim p in th is a r ea
beca u se it’s th e big g est cost to y ou , bu t on ce y ou ’r e
r ea dy to do th is pr ofession a lly , a g ood h ost is a m u st.

Tip

I recommend SiteGround to most people when they need web hosting.

PERFORMANCE TESTING TOOLS


While media, bloated code, and hosting are all areas you
can keep an eye on when developing your website, it’s
worth using third-party tools to help you pinpoint
performance issues on your website.

There are several web-based tests that will load your


website and then give you a list of areas to fix. Popular
ones include PageSpeed Insights from Google (FIGURE
23.1), GTmetrix (FIGURE 23.2), and Pingdom
(FIGURE 23.3).

Figure 23.1 Google’s PageSpeed Insights for


Casabona.org
(developers.google.com/speed/pagespeed/insights/)

Figure 23.2 GTmetrix ratings for Casabona.org


(gtmetrix.com/)
Figure 23.3 Pingdom’s rating for Casabona.org
(tools.pingdom.com/)

They each use slightly different methods for measuring


performance, but they’ll all help by pointing out what
you can improve.

Tip
Some might argue that the best tool to pay attention to is Google’s
PageSpeed Insights because it will give your site a rank based on
performance. However, the Google search algorithm may also affect your
PageSpeed rank, so getting multiple opinions is a good idea.

VIDEO 23.1

Doing a Live GTmetrix Test


GTmetrix is an in-depth perf ormance testing tool that pulls scores f rom multiple
sources and giv es y ou suggestions based on each. This v ideo takes y ou on a quick
tour of the interf ace, and giv es y ou adv ice on what to do with the inf ormation the
serv ice prov ides.

To use PageSpeed Insights:


1. In y ou r br ow ser , v isit
dev eloper s.g oog le.com /speed/pa g espeed/in sig h ts/.
2. In th e tex t box la beled En ter A Web Pa g e URL, ty pe y ou r
w ebsite’s a ddr ess (FIGURE 23.4).

Figu r e 23.4 Pa g eSpeed In sig h ts URL box

3. Click th e A n a ly ze bu tton .
On ce th e tool com pletes a n a ly sis, y ou ’r e g iv en tw o scor es:
on e for m obile a n d on e for desktop.
4. Click Desktop, on th e left tow a r d th e top of th e pa g e (FIGURE
23.5).

Figu r e 23.5 Th e Mobile a n d Desktop bu tton s th a t r ev ea l,


a n d let y ou sw itch betw een , th e scor es on Pa g eSpeed
In sig h ts

Pa g eSpeed In sig h ts g iv es y ou da ta ba sed on h ow w ell y ou r


w ebsite h a s per for m ed for oth er people. It th en g iv es y ou
deta iled descr iption s of ea ch m etr ic.
5. Click th e th r ee-lin e icon n ex t to La b Da ta to v iew th ose
descr iption s ( ).

6. Un der both Oppor tu n ities a n d Dia g n ostics, y ou see scor es a n d


r ecom m en da tion s. Click th e dow n a r r ow ( ) to v iew th e
r ecom m en ded fix es y ou ca n m a ke.

The Chrome DevTools Network tab


Chrome DevTools, which you learned about in Chapter
22, has more than just tools for reviewing HTML, CSS,
and responsive design.
Y ou learned how to test in Chrome on low-speed
internet connections, but the Network tab will give you a
more detailed breakdown of your website’s performance
(FIGURE 23.6).
Figure 23.6 The Network tab in Chrome DevTools
with results loaded from Casabona.org

To view results in the Network tab in Chrome


DevTools:
1. V isit y ou r w ebsite in Ch r om e.
2. Open Ch r om e Dev Tools by clickin g th e m en u bu tton a n d
ch oosin g Mor e Tools > Dev eloper Tools.
3. Click th e Netw or k ta b.
4. On m a cOS, pr ess Com m a n d-R to r eloa d th e pa g e a n d see th e
n etw or k a ctiv ity r esu lts. On Win dow s, pr ess Ctr l-R.
You r w ebsite r eloa ds, a n d th e Netw or k ta b is popu la ted w ith
da ta or g a n ized in to tw o section s: a tim elin e a n d a list of a ll
th e files (HTML, CSS, im a g es, etc.) th a t y ou r w ebsite loa ds,
w ith loa d tim es.

Using the information from the Network tab, you can


look at slow-loading files and determine how you can
optimize your site.

Speaking of which, let’s look at a few techniques for


optimizing your website, starting with some low-
hanging fruit: making your HTML and CSS files smaller.

VIDEO 23.2

A Closer Look at the Network Tab


Knowing how the Network tab works can help y ou f ast-track perf ormance testing
based on internet speeds and other f actors. Let’s take a closer look at this f antastic
tool.

MINIFY HTML AND CSS FILES


Minifying HTML and CSS files is the act of removing
unnecessary characters in order to make the files as
small as possible.

When you write HTML, every character counts towards


the total file size, even spaces and line breaks—the
computer still needs to represent them as data.
Generally, one character = one byte (though some
characters use more). So “Hello World” has a size of 11
bytes. Since you generally see sizes in kilobytes (KB),
megabytes (MB), or gigabytes (GB), TABLE 23.1
shows how many bytes are in each unit of
measurement. Y ou may see people use a simple power
of 10 conversion (1000 bytes in a KB; 1,000,000 bytes in
a MB, etc). However, when converting values to
computer storage, you should use the exact values
provided in the table.

Table 23.1 Byte Conversion Chart


Unit Size in Bytes

Kiloby te (KB) 1 02 4

Meg a by te (MB) 1 ,04 8 ,5 7 6

Gig a by te (GB) 1 ,07 3 ,7 4 1 ,8 2 4

In both HTML and CSS, spaces and line breaks are


unnecessary; they are only there because it’s easier for us
to read the files with proper spacing included. The same
goes for comments. While they give cues to developers as
to what’s going on in the code, they do not affect how
the browser renders a site, so they aren’t needed.
Removing spaces, line breaks, and comments can lead to
considerable space savings (FIGURE 23.7).

Figure 23.7 On the left you see the CSS from


Casabona.org, which is nearly 6400 lines of code and
129KB in size. On the right, you see the minified
version, one (very long) line and 97KB. That’s 40
percent smaller!

There are lots of online tools for minifying both HTML


and CSS. Some give you options for degrees of
minification (just remove line breaks, remove all spaces,
etc.). Make sure that whatever minification is done, it
doesn’t end up breaking your code. I’ve gotten consistent
(and good) results from Minify Code (FIGURE 23.8).

Figure 23.8 Minifycode.com allows you to minify


HTML, CSS, and JavaScript.

To minify HTML using Minify Code:


1. V isit m in ify code.com .
2. Click th e HTML Min ifier bu tton .
If y ou r br ow ser w in dow is a sm a ller size, y ou m a y see a blu e
icon in th e top r ig h t. Click it to r ev ea l th e n a v ig a tion m en u .
3. Open th e index.html file for y ou r w ebsite in a tex t editor .
4. Copy a ll th e tex t fr om y ou r index.html file.
5. Pa ste th e tex t in to th e tex tbox on th e Min ify Code pa g e.
6. Click th e Min ify HTML bu tton .
You r HTML is r epla ced w ith th e m in ified v er sion .
7. Copy th a t code.
8. Cr ea te a n ew folder ca lled m in ified.
9. In th a t folder , cr ea te a n ew file ca lled index.html.
10. Pa ste th e m in ified HTML in to th e n ew in dex file a n d sa v e th e
file.
11. Uploa d th e n ew , m in ified v er sion of index.html to y ou r w eb
ser v er .

Y our mileage will vary depending on how much markup


you have in your file. The bigger savings are often seen
with minifying CSS. That process looks exactly the same
as the previous task, but you’ll use the CSS minifier on
minifycode.com instead of the HTML minifier.
Tip
As you delve deeper into web development, you will likely use tools that help
you automate some of your work. Minifying is a great candidate for
automation.

Tip

Because minified code is not useful when you’re actually writing HTML or
CSS, you should keep an unminified copy of your code (the “development”
version) and minify only what you plan to upload to your server (the
“production” version).

Tip
If you ever want to “unminify” something, a process called beautifying,
minifycode.com can do that too!

OPTIMIZE YOUR IMAGES


Another quick win for improving performance is
optimizing your images. There are three ways you can
do this.
First, when you can, use SVG for simple graphics, since
they are inherently smaller than pixel-based images like
JPEGs.

Tip

If you have a very complex SVG, you might save in load time, but the browser
will take a lot longer to render the image.

Second, if you are using pixel-based images, make sure


your images are the appropriate size for the space they’re
in. For example, if you have an image sized to 500x250,
you shouldn’t be shrinking a 2000x1000 image by 75
percent; use a 500x250 image sized at 100 percent. Y ou
can do this easily in HTML using the techniques you
learned in Chapter 7.
Another image format that has gained popularity is
WebP. Developed by Google, the format makes images
about 26 percent smaller than their PNG counterparts.
It uses the .webp extension, and it’s supported by all
major browsers except Safari at the time of this writing.
Y ou can learn more about how to use WebP at css-
tricks.com/using-webp-images/.
Finally, you can compress your images. Compression is
a way of shrinking a file size at the code level without
altering what the file represents. In fact, minifying is a
form of compression. We get a much smaller file size,
but your website still looks the same. Another example is
shorthand in text messaging or chat. Instead of “laugh
out loud,” most people write “LOL.” It’s much shorter
but means the same thing.

Why compress images?


Images often contain extra information that bloats the
file size, like metadata about the image. This can be
where the photo was taken, what camera was used, date
and time, and more.
None of this matters to people visiting your website,
especially when it’s loading slowly. So you can use
compression and optimizing tools to remove that
metadata and reduce image file sizes without losing
quality (FIGURE 23.9).
Figure 23.9 On the left is the original image, and the
compressed version is on the right. Notice that there’s
no difference in quality.

There are several free image-optimizing tools for macOS


and Windows, as well as web-based services. For
macOS, I recommend ImageOptim
(imageoptim.com/). It’s been around for a long time, it
works well, and it can integrate with other services
through its API (for a price).
For Windows, RIOT (riot-optimizer.com/) is a free tool
that works well.
ImageOptim also has a web interface with limited
functionality (FIGURE 23.10).

Figure 23.10 The interface for


imageoptim.com/online has several options for
optimizing your images.

To use ImageOptim to compress an image:


1. Go to im a g eoptim .com /on lin e.
2. Keep a ll th e settin g s a t th eir defa u lt v a lu es for n ow .
You ca n a lw a y s ex per im en t w ith th ese settin g s!
3. Click Ch oose Files a n d select on e of th e im a g es fr om y ou r
w ebsite folder .
Th is w ebsite su ppor ts selectin g m u ltiple im a g es if y ou w a n t
to pr ocess m or e th a n on e a t a tim e.
4. On ce y ou ’v e selected y ou r im a g e, click Su bm it.
5. A fter Im a g eOptim fin ish es com pr essin g th e im a g e, y ou ’ll be
pr om pted to dow n loa d th e n ew v er sion . Sa v e it to th e
m in ified folder y ou cr ea ted in a sepa r a te ta sk.
6. Uploa d th e im a g e to y ou r w ebsite, r epla cin g th e old on e.

Again, your mileage will vary depending on the image


you use. But for the image used in Figure 23.9, the
original was 4.3MB and the reduced version was 3.9MB.
Between using something like ImageOptim and sizing
your images properly, your website should load a lot
faster. But there’s something else you can do that will
make a huge difference, which I cover in the next
section.

Getting Creative with Images


Aside f rom sizing and compressing, y ou can get creativ e with the way y ou process
and display images.

For example, the less complex the image, the less space it takes up. Consider using
black and white or duotone images instead of f ull color—that can go a long way
toward reducing f ile size.

Advanced Hosting Techniques


There are two terms y ou’ll likely hear as y ou learn more about webpage loading speed
and perf ormance.

The f irst is cache. Caching copies some of y our website f iles to be stored on the
v isitor’s computer f or f aster access. Much like the local storage y ou learned about
earlier, a cache is where a browser stores certain f iles that are unlikely to change
of ten (like images and y our CSS). This reduces the number of requests y our browser
has to make to the serv er, because the f iles are already technically on the user’s
computer.
The second is content delivery network (CDN). This is a set of serv ers y our website
f iles are distributed to. When a user makes a request to y our website, the serv er
closest to the user serv es up the needed f iles.
You can think of cache and a CDN this way : imagine that y our f av orite ice cream
place is 20 minutes away f rom y our home. The “request” f or ice cream would take 20
minutes.

With cache, it would be as if y ou bought a gallon of the ice cream to keep in y our
f reezer.
With a CDN, it would be as if the ice cream shop worked out a deal with y our grocery
store, which is only 10 minutes away, to sell the ice cream there.

LOAD YOUR CRITICAL CSS FIRST


Another term you’ll probably see, especially if you review
your PageSpeed Insights results, is the term render-
blocking resources. These are any files that need to be
downloaded before the page can be displayed at all. The
fewer render-blocking resources, the faster your page is
perceived to load.
Imagine you’re going on a trip but you didn’t pre-pack a
bag. Each time you get into your car, you realize you
forgot something, so you run back inside to get it. It
takes you much longer to get on the road. Each
forgotten item is like a render-blocking resource. If you
had packed a bag earlier, you would have been able to
leave faster.
This is also known as time to first paint. The first paint is
the very first render of your website. When users see a
blank screen, they know the website is taking time to
load. Y our goal is to eliminate this blank screen as soon
as possible, even if it’s not the full site (FIGURE 23.11).
Figure 23.11 Filament Group’s site employs several
performance boosters, including critical CSS. Y ou can
see its first paint, where you can start reading the
content, versus the last paint, which includes all the
images, bells, and whistles.

Part of the reason I left this until last in the chapter is


that it’s more complicated than the other techniques
we’ve covered. It’s not just shrinking a file or some other
basic task.
The lazy loading technique from Chapter 10 is one way
to remove certain render-blocking resources and get
your website loaded faster. However, everything you
include in the <head> element of your website is also,
by default, render-blocking.
For the purposes of this book, render-blocking resources
means your CSS file. If it’s absolutely massive, it will
take your website longer to load. So you can employ the
following technique:

Move the most important CSS—that is, the CSS required


to style the first part of the website—to an internal style
sheet (see Chapter 11). Load the rest of the CSS later in
the document, like right before the </body> tag.

Tip
There are lots of tools to help load only the critical CSS, and many are
automatic. Unfortunately, they rely on tools we haven’t learned about in this
book. If you’re curious, Smashing Magazine offers a good overview:
www.smashingmagazine.com/2015/08/understanding-critical-css/.

Determine your critical CSS


If you’re not using automated tools, your first job is to
determine which CSS is critical and which is not. Many
times, the determining factor is the fold (FIGURE
23.12). This is any content that shows up in the user’s
browser before they scroll.
Figure 23.12 The fold is what loads in the browser
without scrolling. Critical CSS should style for above
the fold.

Tip
The term the fold comes from the newspaper industry! Newspapers were
always stacked folded. So of course only the part of the front page above the
fold was visible, and thus it got by far the most attention.

When working with many different devices, determining


the fold is impossible, but for the purposes of this book,
let’s work with your desktop browser window. Take a
look at your website and see what renders in the browser
before you do any scrolling. This is the stuff that you
should target for your critical CSS.
Y ou can also use a tool like the Critical Path CSS
Generator by Sitelocity (FIGURE 23.13).
Figure 23.13 Sitelocity’s Critical Path CSS Generator
will help you determine what your website’s critical
CSS is (sitelocity.com/critical-path-css-generator).

Tip
In critical CSS, you can also leave out certain special effects, like text
shadows or box shadows. The goal is a fast first paint. You can add bells and
whistles later.

CODE 23.1 shows a simple HTML example with a


single comment denoting where I’ve determined the fold
to be.
In this instance, you’ll want to include some body styles
and the header and .primary-content styles in your
critical CSS. Everything else can be put in the
style.css file. For simplicity’s sake, CODE 23.2
includes the critical CSS.
CODE 23.1 Critical CSS markup example
Click h er e to v iew code im a g e

<html>
<head>...</head>
<body>
<header>...</header>
<main>
<section class="primary-
→ content"> ...</section>
<!--Here is "the fold"-->
<section class="secondary">...
→</section>
</main>
<footer>...</footer>
</body>
</html>

To add critical CSS inline:


1. Open y ou r HTML file (or cr ea te a n ew on e u sin g Code 2 3 .1 ).
2. On th e lin e a fter th e open in g <head> ta g , ty pe <style>.
3. A dd y ou r cr itica l CSS. If y ou ’r e u sin g th e dem o code, u se
Code 2 3 .2 for th is pa r t.
4. On th e n ex t lin e, ty pe </style>.
CODE 23.2 The critical CSS
Click h er e to v iew code im a g e

body {
max-width: 700px;
padding: 30px;
margin: 0 auto;
font-family: 'Playfair Display',
serif;
background-color:#fcf6e7;
}

h1 {
color: #282009;
font-size: 4em;
font-weight: 900;
letter-spacing: 0.08em;
}

.byline {
font-family: Futura, sans-serif;
font-style: italic;
font-weight: bold;
text-decoration: underline;
}

header img {
width: 50px;
height: auto;
vertical-align: middle;
}

.primary-content {
background: #FFFFFF;
padding: 30px;
}

p {
font-size: 24px;
}

5. On a n ew lin e r ig h t befor e </body>, a dd a r efer en ce to y ou r


CSS file by ty pin g <link href="style.css"
rel="stylesheet" type="text/css" />.
6. Sa v e y ou r files a n d u ploa d th em to y ou r ser v er .
7. V isit th e n ew ly cr ea ted HTML file. You sh ou ld n otice th a t
som e of th e sty les loa d in itia lly , a n d th en th e r est of th e
sty les fin ish loa din g on ce th e br ow ser g ets to th e style.css
r efer en ce a t th e en d of th e docu m en t.
VIDEO 23.3

Testing Critical CSS


Once y ou add the critical CSS to y our website, it’s important to test y our f iles to
make sure that the f irst paint looks usable and that the rest of the sty les f ully load
later. Let’s create new HTML and CSS pages to see how quickly a page loads bef ore
and af ter adding the critical CSS.

WRAPPING UP
In this chapter you’ve learned some important principles
and techniques for speeding up your website. A fast
website is important because it keeps users from
abandoning it, and we want as many people to use our
site as possible.
In that same vein, another way to ensure anyone who
wanted to view your website can is to make it accessible.
Let’s take a look at how in Chapter 24.

Conditionally Load Style Sheets


Aside f rom loading y our critical CSS and then all the rest of y our CSS in a single f ile,
y ou can separate it out f urther by loading it conditionally based on media queries.

For example, let’s say y ou hav e three separate sty le sheets:

One f or general (noncritical) sty les

One f or big dev ice sty les

One f or print sty les

You can load them using media queries right in the HTML tag:
Click here to v iew code image

<link href="style.css" rel="stylesheet"


type="text/css" />
<link href="large-screen-styles.css"
rel="stylesheet" type="text/css"
→media="screen and (min-width: 1301px)"/>
<link href="print-styles.css"
rel="stylesheet" type="text/css"
media="print" />

This ensures that the last two sty le sheets are only loaded when they are needed.
24

Web Accessibility
In This Chapter

Including as Many People as Possible


What Y ou’ve Done so Far

Additional Tags and Attributes


Accessibility Tests and Validation

Finding Y our WCAG Rating


Wrapping Up

Throughout this book, you’ve learned how to make


websites. Y ou’ve learned how to support devices of all
shapes and sizes. And you’ve learned how to make your
website load as quickly as it can on internet connections
fast and slow. But there’s one more way you can make
sure your website works for whoever wants to view it:
make it accessible.

Web accessibility means designing your website in such


a way that people with disabilities can use it. This can be
making sure your images have alt tags for screen
readers, choosing color schemes that are readable for
those who are color-blind, or even adding keyboard
shortcuts to help those who can’t use a mouse to
navigate.

INCLUDING AS MANY PEOPLE AS


POSSIBLE
An important point to make at the outset is one that’s
often stated by accessibility advocates: web accessibility
doesn’t just help the disabled—it makes your website
more usable for everyone.
Usability is a big reason this book has focused on
semantics, using the right tags, and making your website
work across multiple devices, screen sizes, and
connection speed. Y ou want to reach as many people as
possible with your website. Another step in that process
is realizing that you’re not designing your website just
for yourself.

Tip
This chapter scratches the surface of accessibility and describes a few things
you can do. If you want to learn more, there’s a fantastic book called
Accessibility for Everyone, by Laura Kalbag:
abookapart.com/products/accessibility-for-everyone.

A Note on the Legal Side of Things


There are also certain legal ramif ications in certain countries f or not making y our
website accessible. In the United States, the retailer Target and the pizza deliv ery
company Domino’s both f aced legal action f or not hav ing websites that were
accessible enough.

While that shouldn’t be the main reason y ou make y our website accessible, it is
important to keep in mind that hav ing a website that isn’t accessible is v iewed as
discriminatory.

Designing for a diverse set of users


When thinking about web accessibility, it’s important to
remember that not everyone uses a computer with a
keyboard and mouse.

About 12 percent of the United States population has


some disability. That could range from color blindness to
motor impairments, and everything in between. Here’s a
short list of disabilities to think about, and how they can
affect how people use your website:

Pa r tia l ey esig h t loss ca n m a ke sm a ll tex t h a r d to r ea d


a n d im a g es h a r d to see clea r ly . User s m a y r ely on a
scr een r ea der for h elp.

Color blin dn ess m a kes it h a r d to see or distin g u ish


cer ta in color s (FIGURE 24.1). If y ou ’r e u sin g a color
sch em e th a t doesn ’t h a v e en ou g h con tr a st, tex t m a y be
com pletely in v isible to som e u ser s (FIGURE 24.2).
Figu r e 24.1 Th e sa m e im a g e a s v iew ed by people w ith
v a r y in g deg r ees of color blin dn ess, fr om n on e to
com pletely m on och r om e.

Figu r e 24.2 Gr een tex t on a bla ck ba ckg r ou n d is


r ea da ble for th ose w ith ou t color blin dn ess. Bu t for
th ose w h o a r e g r een -blin d, th e tex t looks da r k pu r ple
a n d becom es u n r ea da ble.

Fu ll or pa r tia l h ea r in g loss m ea n s u ser s w ill n ot be a ble


to listen to v ideos or a u dio on y ou r w ebsite. Th e best fix
for th is is to in clu de tr a n scr ipts a n d ca ption s or su btitles
for v ideos.

Motor im pa ir m en ts m a y ca u se u ser s to h a v e difficu lty


u sin g tr a dition a l poin tin g dev ices like a m ou se. A scr een
r ea der ca n h elp w ith in pu t, a n d m a kin g y ou r w ebsite
n a v ig a ble by key boa r d w ill h elp a s w ell.

Cog n itiv e im pa ir m en ts like dy slex ia or m em or y deficits


ca n a ffect h ow people u se y ou r w ebsite. Usin g g ood, clea r
fon ts a n d keepin g y ou r w ebsite clea r of distr a ction s isn ’t
ju st g ood UX, it ca n m a ke it m or e a ccessible.
Making your website accessible, combined with tools
available in browsers and other software, can make it so
anyone can use your website without trouble.

Tip
Two good tools for figuring out workable color schemes are paletton.com/
and coolors.co/.

WHAT YOU’VE DONE SO FAR


Luckily, a lot of what you’ve done so far goes a long way
toward making your website accessible. Using the
appropriate HTML elements for sections of your website
clues screen readers into what kind of content you’re
building.
Using heading tags (and the right heading tags) breaks
up long blocks of text and makes them easier to
consume and understand.

With forms, using different fields for different types of


input helps users better understand the type of data
they’re inserting. Similarly, labels provide meaning to
those fields.
Using the alt attribute on images allows images to be
described when they can’t be downloaded or viewed.

Tip
For alt attributes, the more descriptive, the better. For Figure 24.1, an alt tag
of “girl in yard” is better than nothing. But it’s not as good as “A girl toddler
wearing a backwards hat and holding a pink bucket in a fenced-in yard.”

The testing you’ve learned about also helps with


accessibility. By improving performance and testing on
different browsers and devices, you’re ensuring your
website can work anywhere and everywhere.

Y ou can see how well you’ve done by turning off the


styles on your website and viewing just the HTML
(FIGURE 24.3). This is what both search engines and
screen readers will see. In Chrome, you can do this using
the Web Developer extension you downloaded in
Chapter 6.

Figure 24.3 Casabona.org with all styles disabled. It’s


not pretty, but it’s usable!

To turn off CSS in Chrome:


1. V isit y ou r w ebsite in Ch r om e.

2. Click th e Web Dev eloper cog icon ( ).

3. Click th e CSS Ta b.
4. Click Disa ble A ll Sty les.

With no styles, does your website make sense? Does the


information flow the way you expect it to? Is the
information that should be at the top actually at the top?

Great! Y our website is well on its way to being


accessible. But there is more you can do. In the rest of
this chapter, you’ll learn important tests and techniques
that will help you make sure your website is accessible.

ADDITIONAL TAGS AND ATTRIBUTES


Accessibility is something you should plan for from the
beginning of your project. Before you start using
evaluation tools, do as much as you can during
development to make your website accessible.
Using well-structured HTML is the best thing you can do
to support accessibility, so make sure to use the skills
you’ve learned throughout the book to make a website
accessible at its core.
However, sometimes in the course of building your site
you do need to use HTML elements that don’t necessarily
have any meaning, like div or span. Y ou might also
create an area of your site that does not have an HTML
tag that would give it meaning. Luckily, that’s where
ARIA tags come in.

ARIA is the shorthand way of writing WAI-ARIA, or


Web Accessibility Initiative–Accessible Rich Internet
Applications. Most people just refer to it as ARIA.
ARIA is a way of providing to the browser more
information about an element when the proper meaning
isn’t built into HTML. Y ou can do that by using two
different types of attributes:

role defin es a ty pe of u ser in ter fa ce com pon en t ba sed on


its fu n ction (ex a m ples in clu de button, alert, a n d
search). Th is does n ot ch a n g e h ow th e elem en t is
displa y ed; it ju st g iv es th e elem en t m or e m ea n in g
(FIGURE 24.4).

Figu r e 24.4 A n alert w ith ba sic sty les a pplied. It a lso


con ta in s th e m or e m ea n in g fu l role="alert"
a ttr ibu te.

Sta tes a n d pr oper ties pr ov ide fu r th er in for m a tion a bou t


a pa r ticu la r elem en t. For ex a m ple, in a da te selector ,
th e v a lu e of th e m on th m a y be a n u m ber (10, for
ex a m ple). Th e pr oper ty aria-valuetext ca n h a v e th e
v a lu e October so th a t scr een r ea der s ca n g iv e th e u ser
m or e m ea n in g for th a t pa r ticu la r elem en t.

To add role to a div:

1. In a n HTML file, r ig h t a fter th e open in g <body> ta g , ty pe


<div class="sale-alert".
2. Ty pe role="alert">.
Usin g th e A RIA role a ttr ibu te, w e’r e tellin g br ow ser s a n d
scr een r ea der s th a t th is div is a n alert a n d sh ou ld be
tr ea ted a s su ch .
3. Ty pe Now though Sunday, get 25% off!.
4. Ty pe </div>.

Now your browser knows that this particular div is an


alert on your site. This is particularly useful for screen
readers, which can now tell users more than just “This is
a container on a page.”

Tip
Get a full list of roles, states, and properties at developer.mozilla.org/en-
US/docs/Web/Accessibility/ARIA/ARIA_Techniques.

States and properties


States and properties can be used to provide further
descriptions of elements or to connect elements in a
meaningful way. One way is by connecting a password
hint to the password field with aria-describedby
(CODE 24.1 and FIGURE 24.5).
CODE 24.1 A password field with the aria-describedby attribute applied
Click h er e to v iew code im a g e

<label for="password">Enter a Password:


</label>
<input type="password" id="password"
name="password" aria-describedby="hint" />
<div id="hint">Must be at least 10
characters, and include a Capital letter,
number, and special character.</div>

Figure 24.5 A password field with a hint box. Thanks


to the use of the aria-describedby attribute, the
browser knows the two elements are related.
VIDEO 24.1

Changing ARIA States and Properties


ARIA states and properties are of ten updated in real time through Jav aScript. This
v ideo shows an example of dif f erent sections of an accordion list expanding, causing
the ARIA state to change.

However, these can sometimes be a little tricky to apply


for beginning users of HTML and CSS, since many are
manipulated by JavaScript.

For example, you might design a menu that is shown


and hidden by JavaScript based on a click event (like in
Video 24.1). Y ou can add aria-expanded="true" to
the event when the menu is open, and aria-
expanded="false" when it’s closed.

Tip
A property of an element is relatively static (for example, aria-labelledby
identifies the label of an element), but a state is a dynamic property (for
example, whether a checkbox is selected or unselected). In practice, though,
it’s not important to be aware of the distinction, and most people use
attribute to refer to both of them.

Tip

One interesting example of how ARIA properties are used is the aria-live
property. It allows you to define live regions, or regions that get updated in
real time. Setting its value to polite will announce a live change when the
user isn’t actively scrolling or typing. Setting the value to assertive will
interrupt what the user is doing to make the announcement. You might use
polite for something like Twitter, when there are new tweets. Use the
assertive value for something truly important, like an error or warning.

ACCESSIBILITY TESTS AND


VALIDATION
Once you’ve got your website created, there are a few
ways to test and validate your work to ensure it is
accessible.

The Web Content Accessibility Guidelines (WCAG) are


maintained by the Web Accessibility Initiative
(www.w3.org/WAI/standards-guidelines/wcag/). They
are part of the World Wide Web Consortium (W3C),
which develops and maintains web standards. Y ou can
test your website against WCAG to learn how to make
your website more accessible.
The guidelines are currently in their second version
(WCAG 2.1), and there are three levels of accessibility,
ranging from Level A to Level AAA:

Lev el A is th e low est lev el of con for m a n ce. Th is is a g r ea t


pla ce to sta r t to m a ke su r e y ou r w ebsite is m in im a lly
com plia n t.

Lev el A A is th e n ex t lev el u p, w h er e y ou r w ebsite m eets


m or e cr iter ia in th e g u idelin es. Th is is th e g oa l m ost
or g a n iza tion s a im for beca u se it’s r ea son a bly a ch iev a ble
w ith ou t m u ch a dded cost.

Lev el A A A is th e h ig h est lev el a n d v er y difficu lt (a n d


costly ) to a ch iev e. For th e m ost pa r t, on ly a ccessibility -
focu sed or g a n iza tion s a im for th is r a tin g .

Testing tools
There are three testing tools you’ll learn how to use to
evaluate your website:

Ou r old fr ien d Goog le Ch r om e Dev Tools (FIGURE 24.6).

Figu r e 24.6 Th e a ccessibility a u dit bu ilt in to Ch r om e

WA V E by WebA IM g iv es deta iled test r esu lts a n d


feedba ck. It is h ig h ly r ecom m en ded by w eb a ccessibility
ex per ts (FIGURE 24.7).
Figu r e 24.7 WA V E by WebA IM (w a v e.w eba im .or g /) is
a tool for a ccessibility testin g .

A Ch r om e ex ten sion n a m ed Color blin dly tests for color


blin dn ess (FIGURE 24.8).

Figu r e 24.8 Color blin dly is a fr ee Ch r om e ex ten sion


th a t a pplies color filter s to a n y w ebsite to sim u la te
differ en t ty pes of color blin dn ess.

VIDEO 24.2

Digging into the Accessibility Test in Chrome


The accessibility test built into Chrome is a f antastic starting point f or checking y our
website. It prov ides a score and some helpf ul tips. Here’s how it works.
To test accessibility with Google Chrome:
1. V isit y ou r w ebsite in Ch r om e.
2. Open th e Dev Tools by clickin g th e m en u a n d ch oosin g Mor e
Tools > Dev eloper Tools.
3. Click th e A u dits ta b.

You m a y n eed to click th e dou ble a r r ow ( ) to r ev ea l

th e A u dits ta b.
4. Deselect a ll ca teg or ies ex cept A ccessibility (FIGURE 24.9).

Figu r e 24.9 Th e r epor t settin g s for th e A u dits tool in


Ch r om e

5. Un der Dev ice, select Desktop.


6. Click th e Gen er a te Repor t bu tton .
Th e r epor t g iv es y ou a scor e a n d a list of a r ea s y ou ca n fix , a s
y ou sa w in Fig u r e 2 4 .6 .

To use WAVE for detailed testing:


1. V isit w a v e.w eba im .or g .
2. In th e Web Pa g e A ddr ess field a t th e top of th e pa g e, en ter
y ou r w ebsite’s URL.
Th e test r en der s, a n d it g iv es y ou a deta iled r epor t of
a ccessibility fea tu r es, w a r n in g s, a n d er r or s (FIGURE 24.10).
Figu r e 24.10 Th e r esu lts of th e WA V E test for
Ca sa bon a .or g

It a lso g iv es y ou a r epor t on y ou r color con tr a st (FIGURE


24.11).
Figu r e 24.11 Th e con tr a st test r esu lts in WA V E

This test is much more interactive and provides tons of


detailed analysis to make sure your website is not only
accessible but also web structured and free of markup
errors.
VIDEO 24.3

Using WAVE
There are a lot of f eatures in WAVE, so we walk through the interf ace to show y ou
what the icons mean and how y ou can use the data prov ided by the test.

To test for color blindness with Colorblindly:


1. In Ch r om e, v isit th e Goog le Ch r om e Web Stor e
(ch r om e.g oog le.com /w ebstor e) a n d sea r ch for colorblindly.
2. On th e Color blin dly ex ten sion pa g e, click th e A dd To Ch r om e
bu tton to in sta ll th e ex ten sion . A n ew icon ( ) w ill
a ppea r in y ou r br ow ser ba r .
3. V isit y ou r w ebsite.
4. Click th e Color blin dly icon .
5. Select th e Gr een -Wea k/Deu ter a n om a ly option in th e m en u
(FIGURE 24.12).

Figu r e 24.12 Th e for m s of color blin dn ess Color blin dly


ca n sim u la te

Th is is th e m ost com m on for m of color blin dn ess.


6. Rev iew y ou r w ebsite to m a ke su r e y ou ca n still r ea d
ev er y th in g !
7. Repea t steps 5 a n d 6 for ea ch for m of color blin dn ess.

FINDING YOUR WCAG RATING


Y ou may have noticed in all those tests that you weren’t
given a specific WCAG level rating. There’s one more test
you can conduct for that, using AChecker (FIGURE
24.13).

Figure 24.13 AChecker (achecker.ca/checker/)


compares your website against the WCAG guidelines
and shows you what you need to fix.

To check your site against WCAG level guidelines:


1. V isit a ch ecker .ca /ch ecker /.
2. Select th e Web Pa g e URL ta b.
3. In th e A ddr ess field, ty pe y ou r w ebsite’s URL.
4. Click Option s.
5. Un der Gu idelin es To Ch eck A g a in st, m a ke su r e th e m ost
r ecen t WCA G Lev el A option is selected.
A t th e tim e of th is w r itin g , it’s WCA G 2 .0 (Lev el A ).
We’r e sta r tin g sim ple w ith WCA G Lev el A so th a t y ou ca n
g et th e ba selin e issu es fix ed.
6. Un der Repor t For m a t, select V iew By Lin e Nu m ber .
7. Click th e Ch eck It bu tton .
On th e Repor t pa g e, y ou a r e g iv en a list of issu es y ou n eed to
fix , br oken dow n by lin e n u m ber , in or der to becom e Lev el A
com plia n t (FIGURE 24.14).

Figu r e 24.14 A Ch ecker WCA G Lev el A r esu lts for


Ca sa bon a .or g

WRAPPING UP
With that, you have enough tools to keep you busy!
Over the last few chapters you’ve learned how to test
your website, make it more performant, and make it
more accessible. Y ou’re well on your way to becoming a
fantastic web developer!

But in this chapter and throughout the book, you’ve seen


references to another important aspect of web
development: JavaScript. While that topic is too much to
cover in this book, in Chapter 25 you will get a quick
introduction to it as well as to some other technologies
you might want to check out.
25

Going Beyond HTML & CSS


In This Chapter

JavaScript
Common JavaScript Libraries

Version Control
Build Tools

Wrapping Up

HTML and CSS form the bedrock of any website. And


now you know how to structure and style webpages, as
well as how to make them fast and accessible.
But they are only the beginning of your web
development journey. Now that you know the
foundation, it’s time to show you a few tools worth
looking at while you master HTML and CSS, starting
with JavaScript.

JAVASCRIPT
Y ou’ve seen the term JavaScript more than once in this
book. Y ou even got to write a tiny bit in Chapter 10
when you learned about local storage. But it hasn’t yet
been properly defined for you.
JavaScript is a programming language that is often used
in web development. In the browser, it’s a client-side
language (like HTML and CSS). It usually adds dynamic
features to a webpage in the form of manipulating
elements, changing styles on the fly, advanced form
validation, and more.
As you learn JavaScript, you’ll want to strike a balance
when using it. Loading too many different JavaScript
files can make your page take longer to load. Using too
much JavaScript can also affect your browser’s
performance, since it’s executing code in real time.
If you’ve ever had a browser crash on you, there’s a
decent chance JavaScript was at least partially to blame.

The <script> tag


JavaScript is included on a webpage using the
<script> tag, which you saw in Chapter 10. There are
two ways to use the <script> tag:

You ca n w r ite th e code in lin e—betw een th e <script>


a n d </script> ta g s—like y ou did w ith loca l stor a g e.

You ca n in clu de th e src a ttr ibu te, like y ou did w ith th e


picturefill.js ex a m ple: <script
src="picturefill.js"></script>.

And as with the <style> tag, you can include the


<script> tag anywhere within the <head> or <body>
tags.

Although you won’t learn how to write proper


JavaScript here, you’ll likely come across common
JavaScript libraries (or applications) that you can use on
your website without actually writing any (or writing
very little) yourself.

COMMON JAVASCRIPT LIBRARIES


There are tons of JavaScript libraries out there, and it
seems new ones come out every week. Y ou’ll likely want
to try your hand at a bunch once you get your legs
under you, but I’d caution you to be judicious in what
you decide to learn. In particular, when evaluating a
library, make sure of the following:

It h a s been a r ou n d for a t lea st on e a n d a h a lf to tw o


y ea r s. Th a t sh ow s th a t th e dev eloper s a r e in v ested in it.
It is w ell su ppor ted by th e dev eloper s a n d th e u ser s. Mor e
people u sin g it m ea n s it’s m or e likely to stick a r ou n d.

You a ctu a lly n eed it! Th er e’s a Ja v a Scr ipt libr a r y for
ev er y th in g u n der th e su n . Bu t r em em ber th a t th e m or e
r esou r ces y ou u se, th e h ea v ier y ou r pa g e becom es. On ly
loa d th e th in g s y ou n eed to loa d.

Start with jQuery


jQuery (jquery.com) has been around for a very long
time (especially in web years) (FIGURE 25.1). Even
though its usage is on the decline, it’s still a great way to
dip your toe in the waters of JavaScript because it
simplifies a lot of common actions without weighing
down your site with excess code.

Figure 25.1 The homepage for jQuery (jquery.com),


a longstanding and popular JavaScript library

Here’s how it works: you include jQuery on your


webpage, and then you can use it instead of vanilla
JavaScript (that is, regular JavaScript) to perform tasks
like showing or hiding elements, fading elements in or
out, and more.

Tip
jQuery (and JavaScript in general) allows you to change areas of your
website based on user interaction. Be mindful about using JavaScript when
you should be using CSS.

Other popular JavaScript technologies to


consider
I recommend jQuery because its barrier to entry is a lot
lower than that of other JavaScript libraries. But several
have gained popularity and are worth considering
because you’ll likely see them come up a lot:

Rea ct.js: Cr ea ted by Fa cebook a n d m a de open sou r ce,


Rea ct h a s fou n d its w a y in to lots of m a jor pr ojects, so th is
on e is defin itely w or th lookin g in to (FIGURE 25.2)

Figu r e 25.2 Rea ct.js (r ea ctjs.or g /) is a n open sou r ce


libr a r y th a t h a s g a in ed a lot of popu la r ity in r ecen t
y ea r s.

A n g u la r : Th is on e w a s cr ea ted by a n oth er h ea v y h itter ,


Goog le. It’s been a r ou n d a bit lon g er th a n Rea ct a n d is
u sed to h elp w ith bu ildin g sin g le-pa g e a pplica tion s a n d
w ebsites (FIGURE 25.3)
Figu r e 25.3 A n g u la r by Goog le (a n g u la r .io/) m a kes it
pa r ticu la r ly ea sy to cr ea te in ter a ctiv e ex per ien ces on
both desktop a n d m obile.

Node.js: Th is is a n open sou r ce libr a r y th a t’s a little


differ en t fr om th e oth er s—it ex ecu tes Ja v a Scr ipt outs ide
y ou r br ow ser on a ser v er , a n d is often u sed for tools th a t
h elp y ou bu ild w ebsites r a th er th a n on th e w ebsites
th em selv es. Node is v er y popu la r , so y ou ’ll defin itely
com e a cr oss it (FIGURE 25.4).

Figu r e 25.4 Node.js (n odejs.or g /) is a bit differ en t


beca u se it’s n ot u su a lly r u n in th e br ow ser .

V u e.js: Fin a lly , V u e is a r ela tiv e n ew com er in th e spa ce,


bu t it h a s been a dopted by m a n y for its ea se of u se,
especia lly w h en cr ea tin g u ser in ter fa ces (FIGURE 25.5).
Figu r e 25.5 V u e.js (v u ejs.or g /) is y ou n g er th a n th e
r est, bu t it’s g a in ed popu la r ity beca u se it h a s a low
lea r n in g cu r v e a n d is fa st.

Use JavaScript Only When You Need To


Once y ou learn Jav aScript, y ou might be tempted to make changes to y our CSS, or
ev en to y our content, using only Jav aScript because it’s easier. I strongly
recommend y ou don’t.
HTML, CSS, and Jav aScript all hav e their place, and y ou shouldn’t use Jav aScript to
change sty les when CSS would be a better f it. Remember that adding Jav aScript can
impact perf ormance in more way s than one.

As y ou ev aluate whether or not to use Jav aScript, ask y ourself if it’s something
HTML or CSS can (and should) handle. If not, f igure out how to add the script to y our
page while burdening it the least.

VERSION CONTROL
Throughout this book, you’ve likely been making edits to
your files, changing styles, adding and removing
content, and then saving over the old changes.
While that’s okay as you learn, in a more professional
environment (especially working with teams), you’ll
want a way to be able to undo changes if you need to.
That’s where version control comes in.

Version control is the systematic management of


changes to the pieces of a project. In the case of a
website, you use version control to track and organize
multiple copies of its files as they continue to be
developed. Y ou keep a single copy of your live site (called
the master) and you create a development copy to work
on (FIGURE 25.6). Each copy of the code is referred to
as a branch.
Figure 25.6 A visualization of master, development,
and feature branches. Each circle represents a
commit, and each dotted line is the creation of a
branch. Each solid line is a merge.

Version Control Workflows


There are lots of opinions on what the proper v ersion control flow should be. This
book outlines the basic idea of v ersion control, but indiv idual teams implement their
own processes.
In f act, the process outlined abov e is a popular one based on GitFlow
(nv ie.com/posts/a-successf ul-git-branching-model/). But there are many out there
y ou can try based on project and team needs.

For smaller projects where it’s just me, I’v e used a master/f eature branch f low, where
I create a branch f or each f eature, no matter how small, and then merge it back with
the master when I’m done.
As y ou start to experiment with v ersion control, the master/f eature f low is a good
way to f amiliarize y ourself with the process.

How version control works:

You r liv e site, th e code th a t’s cu r r en tly u ploa ded to y ou r


ser v er , is th e m a ster br a n ch . Th is ch a n g es on ly w h en
y ou ’r e r ea dy to la u n ch a n ew v er sion of y ou r w ebsite.

Th er e is a secon d copy of th e liv e site, often kn ow n a s th e


dev elopm en t br a n ch . Th is a llow s y ou to m a ke ch a n g es
to y ou r w ebsite w ith ou t ir r ev oca bly br ea kin g y ou r liv e
site.

Ea ch n ew fea tu r e (desig n ch a n g es a n d n ew section s,


im a g es, or con ten t) g oes in its ow n feature br a n ch . Th is
lets y ou com pa r tm en ta lize y ou r ch a n g es, w or kin g on
on e a t a tim e. A g a in , th is m a kes it so y ou ca n w or k on
on e section of y ou r w ebsite w ith th e con fiden ce th a t y ou
w on ’t br ea k th e en tir e site.
Wh en ev er y ou a dd a ch a n g e a n d sa v e it, it’s ca lled a
commit.

On ce y ou ’r e r ea dy to a dd th e n ew fea tu r es to y ou r
w ebsite, y ou a dd th em to th e dev elopm en t br a n ch . Th is
pr ocess is kn ow n a s merging a n d pus hing. A m er g e ta kes
y ou r code a n d com bin es it w ith th e dev elopm en t
br a n ch . A pu sh sen ds y ou r n ew ly u pda ted br a n ch to th e
r epositor y . Th e r epositor y is w h er e a ll th e files a n d
ch a n g es a r e tr a cked, a n d it ca n be a folder on y ou r
com pu ter or it ca n be u ploa ded to a ser v er th a t h a s Git
en a bled (m or e on Git in a m om en t).
If y ou ’r e w or kin g w ith oth er people, it en su r es th a t y ou
don ’t h a v e a n y con flicts w ith a n oth er fea tu r e br a n ch
som eon e else is w or kin g on .

Fin a lly , on ce th e dev elopm en t br a n ch is in a sta te w h er e


y ou ’r e r ea dy to m a ke th e n ew site liv e, y ou m er g e th e
en tir e dev elopm en t br a n ch in to th e m a ster br a n ch .

Use Git for version control


There are several version control tools out there (much
like there are many JavaScript libraries), but Git is the
clear winner (unlike with JavaScript technologies).

The great thing about Git is that it’s free, and you can
install it right on your computer—no additional tools
needed.
However, the easiest way to get started is to sign up for a
GitHub account (FIGURE 25.7). GitHub is a free tool
that adds a nice interface and social interactions on top
of Git.

Figure 25.7 A typical GitHub profile. Y ou can see


information about the developer and the available
repositories.

Y ou can then get the GitHub desktop client, which


allows you to easily interact with GitHub. Create
codebases (called repositories, or repos) and start playing
around. Y ou can even make copies of pre-existing
codebases (like the one for this book). That process is
called forking. Downloading the code that you want to
make edits to is called cloning.

VIDEO 25.1

Using GitHub
GitHub is a f antastic and f ree tool f or use with Git. It’s one of the easiest way s to get
started with Git.
Here y ou’ll learn how to interact with GitHub using the desktop app.

To create a GitHub account:


1. V isit g ith u b.com .
2. Fill ou t th e sig n u p for m (FIGURE 25.8).

Figu r e 25.8 Th e GitHu b sig n u p pa g e

3. V er ify th a t y ou ’r e a h u m a n bein g .
4. A n sw er a few sh or t qu estion s a bou t h ow y ou ’r e g oin g to u se
GitHu b.
5. V er ify y ou r em a il a ddr ess.

Now you’re ready to start using GitHub!

To add a repository to your account:


1. Ma ke su r e y ou ’r e log g ed in to y ou r GitHu b a ccou n t.
2. V isit th e GitHu b r epositor y y ou w a n t to m a ke a copy of. Tr y
ou t g ith u b.com /jca sa bon a /h tm l-css-v qs.
3. Click th e For k bu tton on th e top r ig h t of th e pa g e (FIGURE
25.9).

Figu r e 25.9 Th e For k bu tton lets y ou a dd a copy of th e


codeba se to y ou r a ccou n t.

The repo is now part of your account! Y ou can make


changes to it without getting permission from the owner
of the original codebase.

BUILD TOOLS
The final big concept in this chapter is build tools. We
touched on this a little bit in Chapter 20 with CSS
preprocessors, but there are a whole set of tools to help
you build websites. They are called build tools, and they
can do everything from setting up your folder structures
and compiling Sass to checking your code for errors
before you upload it to your server.
Developers like build tools because they automate a lot of
complex processes for them, but they also complicate the
overall web development process. Instead of opening up
your text editor and writing HTML and CSS, you first
need to learn to use the command line, install a set of
tools, and configure everything properly. I personally try
to avoid build tools unless I’m working on a big, complex
project, or with a large team where consistency across
work environments is important.

This is definitely the most complicated topic in this


chapter, so we aren’t going to dive deep into it, but I do
want to share with you some popular build tools you
might hear mentioned:

Gu lp a n d Gr u n t: I’m lu m pin g th ese tw o tog eth er


beca u se th ey a r e so sim ila r th a t distin g u ish in g th em on
fea tu r es w on ’t y ield m u ch . Gu lp (FIGURE 25.10) is a
little n ew er a n d a little clea n er , w h ich m ea n s it’s a little
m or e r ea da ble. Gr u n t (FIGURE 25.11) h a s been a r ou n d
a little lon g er a n d h a s m or e fea tu r es a n d in teg r a tion s.

Figu r e 25.10 Gu lp (g u lpjs.com ) is a lig h tw eig h t a n d


popu la r bu ild tool.
Figu r e 25.11 Gr u n t (g r u n tjs.com ) is a n oth er w idely
popu la r , fea tu r e-pa cked bu ild.

CodeKit: If y ou ’r e a Ma c u ser , CodeKit (FIGURE 25.12) is


defin itely th e w a y to g o w h en y ou ’r e sta r tin g ou t. It h a s
a GUI, w h ich m ea n s y ou ’r e n ot r ely in g on th e com m a n d
lin e. It a lso m ea n s it’s m u ch ea sier for beg in n er s to
u n der sta n d. Th a t sa id, it m ig h t n ot (em ph a sis on
m ig h t) be a s flex ible a tool a s Gr u n t or Gu lp, a n d its code
m a y n ot be a s por ta ble a s th a t pr odu ced by th ose tools.

Figure 25.12 CodeKit (codekitapp.com) is a fantastic


Mac app that puts a GUI on top of the command-line
build tools. This is a great way get started with build
tools.

CSS Frameworks
A framework is a codebase that y ou can tap into and use in y our own projects. It will
do a lot of the f oundational work so y ou can f ocus on building new aspects of y our
website.
They work by prov iding y ou with a core set of CSS classes and base sty les to giv e
y ou a head start on y our projects.

Another way to lev el up y our skillset, especially with CSS, is to learn a popular CSS
f ramework:
Bootstrap: This super-popular CSS f ramework was started by Twitter and is
used by thousands of web dev elopers. It’s great f or making sure y our
CSS is rock solid and properly responsiv e. Get it at getbootstrap.com.

Zurb Foundation: Foundation is a widely popular f amily of f rameworks that


prov ides not only CSS but also HTML and Jav aScript. Dev eloped by Zurb
(get.f oundation), it’s f ast and customizable, and it’s used by brands like
Mozilla, Disney, and Amazon.

Tailwind CSS: Tailwind (tailwindcss.com) is a relativ e newcomer in the


space. It touts itself as less “opinionated” than other f rameworks because
it prov ides y ou only the utilities y ou need without all the bloat of extra
sty les f or things like buttons and cards.

WRAPPING UP
As we conclude our journey together, I want to state
that this chapter wasn’t meant to overwhelm you. I
wanted you to see what else is out there, and the likely
candidates for what to learn next.
Learning a CSS framework can make you a better CSS
developer. And JavaScript goes hand in hand with
HTML and CSS. Checking out jQuery and familiarizing
yourself with the complex world of web programming
languages are good next steps, especially if you want to
create websites professionally.

We’re at the end of the book and what’s next is a quick


recap of what you learned, together with a few helpful
resources.
Final Wrap-up
WHAT’S NEXT?
Congratulations! Y ou’ve now completed HTML and
CSS: Visual QuickStart Guide. We’ve covered a lot of
ground, from basic HTML formatting and layouts to
advanced techniques for styling text with CSS. We even
took a look at important testing procedures, like those for
rendering on mobile devices, performance, and
accessibility. So what should your next steps be?
I recommend you continue honing your HTML and CSS
skills. Here are a few useful resources:

If y ou h a v en ’t ch ecked ou t th e v ideos th a t a ccom pa n y


th is book, defin itely do th a t!

You ca n g et ex er cises a n d com m on pa tter n s for HTML


a n d CSS a t ca sa bon a .or g /v qs/.

CodePen h a s fa n ta stic ex a m ples of clev er HTML, CSS,


a n d Ja v a Scr ipt a t codepen .io.

Tr y ou t th e fr ee tu tor ia ls a t Codeca dem y :


w w w .codeca dem y .com /lea r n /lea r n -h tm l for HTML a n d
w w w .codeca dem y .com /lea r n /lea r n -css for CSS.

In Chapter 25, I threw a lot of different tools at you. It


can seem daunting. But the next language you should
learn is JavaScript. As it turns out, Peachpit has a Visual
QuickStart Guide for that too:
www.peachpit.com/store/javascript-visual-quickstart-
guide-9780133846089.

Finally, I want to hear from you! Let me know what


you thought of the book and show me what you’re
working on. Find me on Twitter at @jcasabona.
Thanks for reading. I’m excited to see what you build!
Index
NUMBERS
3D transformations, 235
404 errors, 272

SYMBOLS
/* and */, commenting CSS code, 128

+ (plus sign), adjacent sibling element selector, 138

* (asterisk), attribute values, 141

* (universal/wildcard selector), 144

< (less than sign, or left angle bracket), using with


HTML tags, 18
> (greater than sign, or right angle bracket), using with
HTML tags, 18
child element selector, 137
{} (curly braces), using with CSS style declaration
blocks, 122
$ (dollar sign), attribute selector, 141

= (equals sign), attribute values, 141

/ (forward slash), using with tags, 18

# (hash symbol), using with links, 52

./ parent folder, using in relative links, 40

% (percentage), font-size, 154, 177

~ (tilde), general sibling selector, 138

A
<a> tag, 43
<abbr> tag, 31

absolute vs. relative linking, 39–41, 268


accessibility, 303–311
action attribute, forms, 91

:active state, 142

<address> tag, 83

adjacent sibling selector (+), 138

Adobe Fonts, 148


alert elements, creating, 133
alignment and justification, 158–159
alt attribute, 61, 304

anchor tag, 43

<and>, using in <code> element, 32

Angular JavaScript technology, 316


animations, CSS (Cascading Style Sheets), 236–239
Apache web server, 14
APIs (application programming interfaces), 116
Arabic, RTL (right-to-left) script, 33
ARIA (Accessible Rich Internet Applications), 305–307
aria-describedby attribute, 306

Article page section, 50


<article> tag, 52, 83. See also blog article layout

Aside page section, 50


<aside> tag, 52–53, 173, 185

asterisk (*), attribute values, 141

asterisk (*), universal/wildcard selector, 144

at-rules, CSS, 150


attributes
accessibility, 305–306
action, 91
alt, 61, 304

aria-describedby, 306

border, 77

colspan, 79–80

itemscope, 84

looking up, 111


max, 102

method, 90

min, 102

name, 90, 92

placeholder, 93

required, 106–107

role (ARIA), 305

rowspan, 79–80

searching values, 141


srcset, 63–64

step, 104

style, 125

targeting elements with, 140–141


title, 61

type, 92, 124

using, 19
value, 93

audio, 68–69, 71
author value, name attribute, 23

autocompletion, 11

B
<b> tag, 30
background colors, 143, 167, 170, 217–219. See also
colors
background images, 172. See also images
background transition, adding, 231–232
background-image property, 172

<bdi> and <bdo> elements, 33

blank value, target attribute, 43

block and inline elements, outlining, 49


<blockquote> element, 29

blog article layout, building, 54–56. See also <article>


tag
<body> tags, 22, 147

boilerplate file, creating, 23. See also files


bold
font-weight, 156
text, 30
border attribute/property, 77, 172–173
box model, 46, 176–178
<br> tag, 31

browsers
comparison, 8
CSS (Cascading Style Sheets) support, 212–214
Flexbox, 197
Grid, 197
support, 110
testing, 276–277
testing sites in, 272
using, 13
build tools, 322–323
bulleted lists, 28
buttons, styling, 180
byline class, styling, 157–158
byte conversion chart, 291

C
caching files, 295
calculations with variables, 248–249
CanIUse.com, 111–112, 116, 212
Canva graphics, 68. See also graphics
<canvas> element, 113

capitalization of text, changing, 160


<caption> element, 76–77

cascade in CSS
explained, 121
and family relationships, 134
specificity and precedence, 139–140
CDN (content delivery network), 295
centering elements, 183
checkboxes, creating, 94, 100
child
family tree, 134
indenting, 82
relative link, 40
selecting, 137
Chrome
browser, 276, 304
DevTools, 281–284, 290, 308–309
extensions, 46–47
circle
converting square to, 237
element, 67
cite attribute, <blockquote> element, 29
classes. See also pseudo-selectors and -classes
attribute, 53
vs. IDs, 140
naming, 133
targeting elements by, 131–134
clear property, floats, 187

code
indenting, 82
marking up, 32
tag, 32
codecs, 68–69
CodeKit build tool, 323
CodePen
using with Sass, 253–255
using for tests, 15
using with tables, 78
color contrast, 166
color picker, Google Chrome, 103
color stops, 169
color wheel, 168
Colorblindly testing tool, 308, 311
colors. See also background colors
in CSS, 164–168
representing on computer monitors, 164
RGB and RGBA, 167
setting for styles, 165
color-scheme value, name attribute, 23

colspan attribute, 79–80

columns and rows


extending, 79–80
floats, 186
Grid, 196–199
comma-separated list, 133
comments, adding, 20–21
compiling, 11
compressing images, 293–295
computer monitors, representing colors, 164
conic-gradient(), 169

content generators, 53
critical CSS, loading first, 296–300
CSS (Cascading Style Sheets). See also style sheets; styles
animations, 236–239
browser support, 212–214
commenting code, 128
display property, 177
file sizes, 245
frameworks, 193, 323
Grid layout, 208–211
inline styles, 125
preprocessors, 252–253
representing colors, 164–168
resets, 144, 155
syntax, 122–123
transformations, 233–235
transitions, 230–232
turning off in Chrome, 304
using, 4–5, 124–126
CSS files, minifying, 291–293
CSS Tricks, 171, 199
CSS Zen Garden website, 4–5, 123
CSS3, 5
curly braces ({}), using with CSS style declaration
blocks, 122

D
dates on forms, 102–103
<dd> tag, 81

declaration block, CSS, 122–123


default files, 14
<del> tag, 31

descendent, targeting, 136


description lists, 81–82
description value, name attribute, 23
desktop vs. mobile layout, 222
devices, testing, 276–280
directories, structure, 12
display property, CSS, 177
div, skewing on hover, 235

<div> tag, 53

<dl> tag, 81

DOCTYPE declaration, 22, 274

dollar sign ($), attribute selector, 141

domain name in URL, 37


domains, choosing and hosting, 13, 264–268
<dt> tag, 81

E
elements. See tags
em, font-size, 30, 154, 177
email and domains, 267
email format, forms, 94, 101
email links, specifying, 43
embedding content, 43, 58, 70–71
entities, 32
equals sign (=), attribute values, 141

error checking, 11
events list, creating, 82
@extend, alerts in Sass, 260

extensions in URL, 37
external style sheets, 124, 127
external vs. internal linking, 38

F
fallbacks and polyfills, 111
fields in forms, 90, 96–97, 102, 104
<fieldset> element, 104

<figure> tag, 62

file containers, 68
file extensions, 12
file format, forms, 95
“file not found” errors, 272
file system, reviewing, 128
file types, 68
files. See also boilerplate file
accessing, 13–14
caching, 295
default, 14
minifying, 291–293
FileZilla FTP program, 269–271
Firefox browser, 276
Flexbox, 196, 199–207
float property, 185–187
:focus state, 142

fold, explained, 298


folders
creating, 12
relative links, 40
font sizes, Sass CSS preprocessor, 259
Font Squirrel, 151
@font-face, 150–154

font-family property, 150–151

fonts, 146–148, 151, 155–156


Footer page section, 50–51
<footer> tag, 56

formats for media, 68–69


formatting text, 30–31, 158–160
forms
building and processing, 89
checkboxes, 100
components, 90
email, 101
fields, 92–96, 102
hidden fields, 96
input types, 94
interacting with, 88
labeling fields, 97
processing, 91
process.php file, 91

radio buttons, 99
select boxes, 98–99
<select> element, 96

setting up, 97
<textarea> field, 96

validating, 106–107
forward slash (/), using with tags, 18

framename link target, 43

frameworks, CSS, 193, 323


FTP information, finding for servers, 43, 269–271

G
GB (gigabyte), 291
general sibling selector (~), 138

GET value, forms, 90–91

GIF (Graphics Interchange Format) images, 59


Git, version control, 320
GitFlow, 319
GitHub, using, 320–321
Github repo, process.php file, 91

Google Chrome DevTools, 281–284 308–309


Google Fonts, 148–150
Google’s PageSpeed Insights, 288–289, 296
gradients, 169–171
grandchild, 40, 82, 134
grandparent, relative link, 40
graphics, pixel vs. vector, 59. See also Canva graphics
great-grandchild, family tree, 134
greater than sign (>), 18, 137 Grid, 196, 208–211

grid layout, 186, 224, 246–247

H
<h1> tag, 19

H.264 video codec, 69


hash (#) symbol, using with links, 52

<head> tags, 22

Header page section, 50–51


<header> tag, opening, 54

headings, 2–3, 19, 26–27, 147, 155


height property, 177–178

hex values, representing colors, 164–165


hidden fields, forms, 96
hidden format, forms, 95
hiding
elements, 226
text, 160
home page, 14, 40, 44, 46, 52
hosting
domains, 264–268
techniques, 295
:hover state, 142

hover.com, 267
href attribute, 43

HSL (hue, saturation, lightness), 164, 168


HTML (HyperText Markup Language)
without CSS, 5
without elements, 27
hierarchy, 3–4
minifying files, 291–293
overview, 2
shapes, 67
HTML elements. See tags
<html> and </html> tags, 22

HTML5 and CSS3, 4, 6–7, 116


HTTP vs. HTTPS, 37

I
<i> tag, 30

id attribute, 41–42, 53, 140. See also role vs. id

<iframe> link target, 43

image format, forms, 95


image gallery, creating, 235
images. See also background images; responsive images
adding to pages, 60–62, 64
compressing, 293–295
finding and making, 68
optimizing, 293–295
resizing, 63
types, 59–60
<img> tag, 60–61, 63

!important value, CSS, 139

index.html file, 10, 14

inheritance, 134–135
inline and block elements, outlining, 49
inline styles, CSS, 125
input fields, 92–93, 232
input types, forms, 94
<input> tag, forms, 90

<ins> tag, 31

Internet of Things, 277


iPhone, emulation with Xcode for macOS, 280
italic, font-style, 156
itemscope attribute, 84

J
JavaScript, 106, 248, 314–317
JPG/JPEG (Joint Photographic Experts Group) images,
59
jQuery library, 315
justification and alignment, 158–159

K
KB (kilobyte), 291
@keyframes, animations, 236

L
layers, creating, 190–191
layouts, 46–48, 193, 222, 224
lazy loading, 116–117, 297
left angle bracket (<), 18

<legend> element, 104

less than sign (<), 18

letter-spacing property, 159

<li> tag, 28

line breaks, inserting, 160


line element, 67
line height, figuring out, 159
linear-gradient(), 169–170

lines, text-decorating properties, 157

line-through, text-decoration, 156

:link state, 142

<link> tag, 127

links
# (hash) symbol, 52

absolute vs. relative, 268


creating, 36
displaying as block-level elements, 177
internal vs. external, 38
locations on pages, 42
markup, 43
opening in windows, 43–44
relative vs. absolute, 39–41
sections of pages, 41–42
targets, 43–44
URIs (Uniform Resource Identifiers), 43
lists, 28, 143
localStorage, 115

M
mailto: links, specifying, 43

main article section, creating, 54

Main page section, 50


MAMP (Mac, Apache, MySQL, PHP), setting up, 14
margins and padding, 179–183
marking up code, 31–32
markup, 2, 5, 274–276. See also semantic markup
matrix(), transform, 233

max attribute, forms, 102

max-width and max-height properties, 178

MB (megabyte), 291
media formats, 58–59, 68–69
media queries, 64, 196, 216–217, 246–247
<meta> tag, 23

<meter> element, 105

method attribute, forms, 90


Microsoft Word document, 3
min attribute, forms, 102

minifying files, 291–293


min-width and min-height properties, 178

mobile vs. desktop layout, 222


monitors, representing colors, 164
monospace fonts, 146–147
month input type, 103

.MOV file extension, 68–69

-moz- browser prefix, 214

MP3 format, 71
.MP4 file extension, 68–69
-ms- browser prefix, 214

multimedia files, storing, 72–73


multiselect boxes, creating, 98–99
MySQL web server, 14

N
name attribute, 23, 90, 92

name in URL, 37
naming
classes, 133
directories, 12
nav menu, making responsive, 225

Nav page section, 50–52


nesting items, 121, 257–258
New York Times home page, 46, 48, 176
Node.js library, 317

O
-o- browser prefix, 214

offline storage, 114–115


order-based selectors, 143
ordered lists, 28
outlining
block and inline elements, 49
elements with Wed Developer extension, 48
overflow property, 179

overflow-wrap property, 160

overlay, creating using z-index, 192–193


overline, text-decoration, 156

P
<p> tag, 18

padding and margins, 179–183


page header, creating, 54
pages. See webpages
PageSpeed Insights, Google, 288–289, 296
paragraph text, 18
paragraphs
enlarging, 132
and headings, 26–27
internal spacing, 160
quoting with citations, 29
parameter value, adjusting, 104
parent, 40, 43, 82, 134
password field, aria-describedby attribute, 306

password format, forms, 94


paths, determining for files, 13, 67
percentage (%), font-size, 154, 177
performance, 286–290, 296
perspective(), transform, 233

PHP web server, 14


<picture> element, 64–65

p.intro class, 143

pixel density, 63
pixel vs. vector graphics, 59
pixels (px), font-size, 154

pixels, computer monitors, 164


placeholder attribute, forms, 93

plus sign (+), adjacent sibling element selector, 138

PNG (Portable Network Graphic) images, 59


polyfills and fallbacks, 111–112
polygon element, 67

polyline element, 67

position property, 187

POST value, forms, 90–91

<pre> tag, 32

prefixing tools, using, 213


preprocessors, CSS, 252–253
print style sheet, creating, 225
printer styles, adding to websites, 225–226
process.php file, downloading, 91

property, CSS, 122. See also shorthand properties


protocol in URL, 37
pseudo-selectors and -classes, 141–142. See also classes;
selectors
public_html folder, 14

px (pixels), font-size, 154, 177


R
radial-gradient(), 169–171

radio buttons, creating, 99


radio format, forms, 94
range input type, 104

React.js technology, 316


readability, formatting for, 158–160
rect element, 67

regex (regular expressions), 107


relationships, selecting elements by, 136–138
relative vs. absolute linking, 39–41, 268
rem (root em), font-size, 155, 177

render-blocking resources, 296–297


required attribute, forms, 106–107

resets, CSS, 144, 155


resizing images, 63
responsive images, 63–64, 70, 217–224. See also
background images; images
RGB (red, green, blue), 164, 167
right angle bracket (>), 18
robots value, name attribute, 23

role attribute, ARIA, 305–306

role vs. id, 54. See also id attribute

root em (rem), font-size, 155

root folder, 14
rotate(), transform, 233–234

rows and columns


extending, 79–80
Flexbox, 201
Grid, 196–199
rowspan attribute, 79–80

RTL (right-to-left) script languages, 33


rulesets, 4, 122–123, 191, 260
RWD (responsive web design), 196, 216

S
<s> tag, 30

sans serif fonts, 146–148


Sass CSS preprocessor, 253–262
saturation, 168
scale(x,y), transform, 233

Schema.org vocabulary, 84–85


screen layouts, 223–224
screen reader, 24
<script> tag, JavaScript, 314

SCSS, 253
search form, 93
<section> tag, 52

<select> element, forms, 96, 98–99

selectors, 122, 143. See also pseudo-selectors and -classes


_self link target, 43

semantic markup, 2, 24. See also markup


SEO (search engine optimization), 84, 266
serif fonts, 146–148
server-side script, validating forms, 106
sessionStorage, 115

shapes, elements for, 67


shorthand properties, 181. See also property
siblings, selecting, 138
sidebar
creating, 56
making sticky, 188–189
site footer, creating, 56
SiteGround, 264–265, 268–269, 287
sites. See websites
sizing text, 154–155
skew(x,y), transform, 233, 235

<small> tag, 31

space.jpg image, 60

spam, defending against, 96


<span> element, 76–77

square, converting to circle, 237


src property, font-family, 151

srcset attribute, 63–64

stacking order, 196


Statcounter tool, 278
step attribute, 104
<strike> tag, 30

<strong> tag, 30

structure of webpages, 46–48


structured data, 83–85
style attribute, 125
style sheets, 5, 124–127, 300. See also CSS (Cascading
Style Sheets); print style sheet
<style> tag, 124, 127

styles. See also CSS (Cascading Style Sheets)


heading and body elements, 147
and markup, 5
setting colors for, 165
setting on elements, 131
simplifying with variables, 246–247
and style sheets, 120–121
<sub> tag, 31

subdomain in URL, 37
subfolders, 13
submit format, forms, 95
<sup> tag, 31

SVG (Scalable Vector Graphic) images, 59, 65–67, 293


switch animation, states, 236
syntax
errors, 274
highlighting, 11

T
<table> element, 76–77

tables, 76–80
tags
<a>, 43

<abbr>, 31

accessibility, 305–306
<address>, 83

<article>, 52, 83

<aside>, 52–53, 173

<b>, 30

<blockquote>, 29

<body>, 22

<br>, 31

<canvas>, 113

centering with margin: auto, 183


changing, 19
creating, 18
<code>, 32

<dd>, 81

<del>, 31

<div>, 53

<dl>, 81

<dt>, 81

<em>, 30

<fieldset>, 104

<figure>, 62

flow, 184–189
<footer>, 56

<h1>, 19

<head>, 22

<header>, 54

<html> and </html>, 22

<i>, 30

<img>, 60–61, 63

<input>, 90

<ins>, 31

<legend>, 104

<li>, 28

<link>, 127

looking up, 111


<mark>, 31

<meta>, 23

<meter>, 105

overlapping, 190–191
<p>, 18
<pre>, 32

vs. rulesets, 4
<s>, 30

<script> in JavaScript, 314

<section>, 52

<select>, 96

selecting by relationships, 136–138


and semantics, 2
setting styles, 131
<small>, 31

<strike>, 30

<strong>, 30

<style>, 124, 127

<sub>, 31

<sup>, 31

targeting, 122, 140–141


targeting by class, 131–134
targeting by tags, 130–131
<time>, 31

<title>, 22

<u>, 30

<ul>, 28

using, 18–19
viewing in browser, 19
Tallwind CS framework, 323
targeting
elements, 122, 130–134, 140–141
media features, 227
targets, 43
<tbody> element, 76–77

tel: links, specifying, 43

templates, Grid, 210


testing
accessibility, 307–311
browsers, 276–277
CodePen, 15
critical CSS, 300
devices, 276–280
webpages, 107
websites, 272, 274
text
formatting, 156–158
hiding, 160
sizing, 154–155
spacing, 159
styles, 161
transparency, 167
text editor, using, 10–11
text formatting
forms, 94
inline, 30–31
overview, 26–27
<textarea> field, forms, 96

text-decoration property, 156–157, 173

TextEdit, 10
text-indent property, 159–160

text-shadow property, 160

text-transform property, 160

<tfoot> element, 76–77


<th> element, 76–77

<thead> element, 76–78

tilde (~), general sibling selector, 138

time input type, 103

<time> tag, 31

title attribute, 61

<title> element, 22

TLD (top-level domain) in URL, 37, 266


TLS (Transport Layer Security), 266
_top link target, 43

<tr> element, 76–77

transform property, animations, 238

transformations, CSS (Cascading Style Sheets), 233–235


transitions, CSS (Cascading Style Sheets), 230–232
translate(), transform, 233, 238

TTF (True Type Font), 152


Twitter, offline storage, 115
two-column layout, at breakpoint, 223
type attribute, 92, 124

type selector, 130–131


typefaces. See fonts

U
<u> tag, 30

<ul> tag, 28

underline, text-decoration, 156


universal/wildcard selector (*), 144
unordered lists, 28
URL (Uniform Resource Locator), 13–14, 37–38
V
validating
accessibility, 307–311
forms, 106–107
markup, 274–276
value, CSS, 122
value attribute, forms, 93
variables
calculations, 248–249
and media queries, 246–247
overview, 242–245
in Sass, 259
simplifying styles, 246–247
vector vs. pixel graphics, 59
vendor prefixes, 212, 213
version control, 11, 318–321
vertical-align property, 159
video and audio files, 68–69
videos. See also multimedia files
alert elements, 133
align-items property, 207
Android devices, 280
ARIA states and properties, 306
attributes, 19
background images, 172
blog article layout, 56
boilerplate file, 23
borders, 173
bouncing ball, 239
box model, 46
breakpoints, 217
browser comparison, 8
browsers, 110
Canva graphics, 68
<canvas> element, 113

cascade in CSS, 121


checkboxes and radio buttons, 100
child and sibling selectors, 138
Chrome accessibility test, 309
Chrome DevTools, 281–284, 290
Chrome responsive testing, 284
VS Code, 11
CodePen demo, 15
color picker, 103, 165
colspan and rowspan, 80

converting and embedding audio, 71


converting fonts with Transfonter, 152
converting Word docs to HTML, 31
CSS Zen Garden, 5
dates on forms, 103
default files, 14
description lists, 82
directory structure, 12
embedding content, 70–71, 73
errors in external links, 38
figures for code samples, 62
file system, 128
FileZilla FTP program, 271
flex-basis property, 205

flex-flow property, 205


flex-item properties, 202

flow of pages, 176


font sizes, 155
forms, 88
GET and POST form submission, 91

GitHub, 320
Google Fonts, 148, 150
gradients, 171
Grid elements, 210–211
GTmetrix performance testing tool, 289
headers with navigation, 52
heading and body styles, 147
heading hierarchy with font sizes, 155
headings, 27
heights and widths in layout, 178
HSL values, 168
HTML with no elements, 27
HTTP vs. HTTPS, 37
image download test, 63
Image Gallery with Mouseover Effects, 235
images, 61
input fields, 232
internal CSS to external file, 127
internal style sheets, 124
justify-content property, 205

lazy loading, 116, 117, 297


Libsyn for hosting audio, 72–73
link markup, 43
links to page locations, 42
lists, 28
mailto links, 43

MAMP (Mac, Apache, MySQL, PHP), 14


media queries, 228
nesting items, 258
offline storage, 115
opening links, 43
ordered lists, 28
outlining block and inline elements, 49
overriding IDs in CSS, 140
paragraphs, 27
p.intro class and selectors, 143

position property, 187


prefixing tools, 213
pricing table, 193
rainbow animation, 237
range input type, 104
registering domains, 267
relative links, 41
rental application, 102
resizing images, 63
responsive nav menu, 225
responsive three-column layout, 223
Sass CSS preprocessor, 257
schemas, 85
screen reader, 24
select and multiselect boxes, 98
setting styles on elements, 131
srcset attribute, 64
stacking order, 196
styles and markup, 5
styles and precedence, 139
styles vs. no styles, 5
SVG (Scalable Vector Graphic) images, 60, 67
tables, 78
tags, 19
targeting classes, 132
text transparency, 167
text-indent to hide text, 160
transformations, 233
transition functions, 230
two-column layout with floats, 186
typographic parameters, 161
unordered lists, 28
URLs (Uniform Resource Locators), 37
validating forms, 107
variables, 243, 245, 247
visual hierarchy, 4
W3C markup validator, 276
WAVE testing tool, 310
Web Developer extension, 48
Xcode Simulator, 280
viewport value, name attribute, 23
:visited state, 142

VS Code, 11
Vue.js technology, 317

W
W3C markup validator, 274–276
w3.org website, direction of text, 33
WAI-ARIA (Web Accessibility Initiative—Accessible
Rich Internet Applications), 305–307
WAV format, 69, 71
WAVE testing tool, 308, 310
WCAG (Web Content Accessibility Guidelines), 307,
311–312
Web Developer extension, 46–48
web forms. See forms
Web Hosting for Students, 264–265
web server, mimicking, 14
-webkit- browser prefix, 214

WebM vs. Ogg, 69


WebP image format, 293
webpages
basic areas, 50
creating, 10
embedding content, 43
layout, 46–48
linking, 36, 41–42
outlining elements, 47–48
sections, 50–53
structuring, 22
testing, 107
URL (Uniform Resource Locator), 13
websites
making live, 269–271
pre-launch check, 268
reaching, 38
testing, 272, 274
week input type, 103

white-space property, 160

width property, 177–178

wildcard/universal selector (*), 144


wireframe, using, 50–53
Word document
converting to HTML, 31
example, 3
word-break property, 160

word-spacing property, 159

wrapper
class, 182, 188
converting to grid layout, 224

X
Xcode for macOS, iPhone emulation, 280

Y
Y oast SEO (search engine optimization), 84
yourbrowser.is tool, 279
Y ouTube.com, 73
YYYY-MM-DD type, forms, 102

Z
z-index, 191–192

Zurb Foundation framework, 193, 323


Code Snippets
Many titles include programming code or configuration
examples. To optimize the presentation of these
elements, view the eBook in single-column, landscape
mode and adjust the font size to the smallest setting. In
addition to presenting code and configurations in the
reflowable text format, we have included images of the
code that mimic the presentation found in the print
book; therefore, where the reflowable format may
compromise the presentation of the code listing, you will
see a “Click here to view code image” link. Click the link
to view the print-fidelity code image. To return to the
previous page viewed, click the Back button on your
device or app.

You might also like