1808 HTML and CSS Visual QuickStart Guide 9th Edition
1808 HTML and CSS Visual QuickStart Guide 9th Edition
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
San Francisco, CA
Notice of Rights
Notice of Liability
Trademarks
Visual QuickStart Guide is a registered trademark of
Peachpit Press, a division of Pearson Education.
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.
Chapter 5 Links
Chapter 7 Media
Final Wrap-up
Index
Table of Contents
Introduction
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
Final Wrap-up
What’s Next?
Index
Introduction
In This Introduction
Errata
But there’s good news: at the heart of it all are still just
plain and simple HTML and CSS.
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?
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.
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 {.
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
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
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:
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 Is HTML?
What Is CSS?
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.
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
VIDEO 1.1
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;
}
VIDEO 1.2
VIDEO 1.3
VIDEO 1.4
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.
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.
Browser Comparison
See how one website can look dif f erent when v iewed in Chrome, Saf ari, and Microsof t
Edge.
2
Wrapping Up
A tex t editor
VIDEO 2.2
Installing VS Code
Download, install, and customize Visual Studio Code.
Er r or ch eckin g
V er sion con t r ol
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).
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
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!
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.
VIDEO 2.4
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.
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.
HTML Syntax
In This Chapter
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
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).
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).
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
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.
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>
Tip
Older versions of HTML required that “DOCTYPE” be set in all uppercase
letters, but in HTML5 the term is case-insensitive.
Aside from the DOCTY PE, three different tags define the
overall structure of a webpage:
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
VIDEO 3.3
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
Lists
Quoting a Block of Text
Wrapping Up
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.
VIDEO 4.1
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
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.
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
<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>
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.
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
MARKING UP CODE
There are also two HTML tags specifically used for
marking up code:
Tip
When using < and > in the <code> element, you should use the HTML entities:
< and >, respectively. To learn about HTML entities visit
developer.mozilla.org/en-US/docs/Glossary/Entity.
<pre><code>
<table border="1">
<thead>
<th colspan="4">Aaron
Judge</th>
<th>RF</th>
</thead>
<tbody>
<tr role="header">
<td>Year</td>
</code></pre>
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
Wrapping Up
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.
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).
VIDEO 5.1
VIDEO 5.2
VIDEO 5.3
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.
Th e name of th e w ebsite.
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.
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
VIDEO 5.5
Lin k to th a t id in th e a n ch or ta g :
VIDEO 5.6
<a href="mailto:[email protected]">
→Email Joe</a>
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
VIDEO 5.8
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>.
_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.
WRAPPING UP
With your knowledge of formatting, organization, and
now linking, you’re ready to move into the structure and
layout side of HTML.
Webpage Layout
Block vs. Inline Elements
Page Sections
Building a Blog Article Layout
Wrapping Up
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
VIDEO 6.1
VIDEO 6.2
VIDEO 6.3
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).
6. Do th e sa m e for th e a bou t pa g e; ty pe
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.”
VIDEO 6.5
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.
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.
<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.
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
Media
In This Chapter
Using SVG
Other Media
Embedding Video
Embedding Audio
Storing Multimedia Files
Wrapping Up
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).
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.
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.
<figure>
<img src="space.jpg" alt="A view
→of the Andromeda Galaxy" />
<figcaption>A view of the
→Andromeda Galaxy</figcaption>
</figure>
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.
VIDEO 7.4
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.
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" />
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/.
VIDEO 7.6
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>.
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.
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.
<svg>
<circle cx="100" cy="100" r="50"
→fill="red" />
</svg>
VIDEO 7.7
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 7.8
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.
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).
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).
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/.
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>.
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
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.
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.
VIDEO 7.11
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.
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
Description Lists
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.
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>
Tip
You can use CSS to move the caption to the bottom of the 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>
<th colspan="2">
<th rowspan="3">
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.
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>.
VIDEO 8.2
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>
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.
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).
Tip
You can even use other HTML elements, like <p> or <ul>, inside description
lists!
VIDEO 8.3
<parent>
<child>
<grandchild>
This makes the code easier to f ollow, and y ou can quickly locate opening and closing
tags.
<address>
Yankee Stadium<br/>
1 E 161 St.<br/>
The Bronx, NY 10451
</address>
Tip
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
<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>
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
Form Fields
Labeling Fields
Validating Forms
Wrapping Up
Con ta ct for m s
Com m en ts
For u m s
Log in box es
Sea r ch box es
Ch a tbots
VIDEO 9.1
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.
<form name="search-form"
→ method="GET" action="process.php">
Figure 9.5 Using the GET method, you can see the
results of a form in the URL.
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.
VIDEO 9.2
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.
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="" />
Tip
For a complete (and regularly updated) list, check out
developer.mozilla.org/en-US/docs/Web/HTML/Element/input.
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):
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
<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>
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.
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>
Tip
Even when labels are applied to inputs throughout a webpage, it’s common
to omit them for submit buttons.
<form name="example-form"
→ method="GET">
VIDEO 9.3
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 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).
Tip
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.
<input type="date"
→ name="release-date" />
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
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.
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.
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
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
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.
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).
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="donations">Donations:</label>
<meter id="donations" min="0" max="100000"
→ value="60000">
at $60,000
</meter>
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.
<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
Tip
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.
Experimental Features
Wrapping Up
VIDEO 10.1
Tip
You’ll find caniuse.com especially handy when you start to use CSS.
<head>
<script src="picturefill.js">
→</script>
</head>
VIDEO 10.2
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.
VIDEO 10.3
VIDEO 10.4
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.
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
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
CSS Syntax
Using CSS on Y our Webpage
Wrapping Up
VIDEO 11.1
Tip
“CSS” and “style sheets” are often used interchangeably.
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;
}
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.
<style>
p {
font-size: 20px;
color: red;
}
</style>
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
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.
<link rel="stylesheet"
→ href="style.css" />
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
/* This is
a comment that spans
multiple lines. */
VIDEO 11.4
WRAPPING UP
CSS opens up a whole world of opportunity for you to
take a website and make it your own through design.
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
Tip
This is also referred to as a type selector.
p, ul, ol {
color: green;
}
This would change the page to look like FIGURE 12.2.
VIDEO 12.1
<p class="standout">
p.standout {
color: green;
}
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
VIDEO 12.3
And you can target elements if, and only if, they have
multiple classes by “daisy-chaining” them, like this:
.class-one.class-two {...}
.alert {
background: red;
color: white;
font-weight: bold;
padding: 5px;
}
.alert.blue-background {
background: blue;
}
.blue-background {
background: blue;
}
<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.
p a {
background: lightgrey;
color: darkblue;
}
Fon t sizes
<footer>
<p>This is the footer with a
→<a href="#">link in it</a></p>
<a href="#">Click here to learn
more</a>
</footer>
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.
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
Specificity of th e selector
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.
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.
<p id="intro">
#intro {
font-size: 24px;
}
VIDEO 12.6
img[alt] {
background: blue;
}
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.
a[href="https://google.com"] {
color: green;
}
img[alt*="dog"] {
background: red;
}
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.
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.
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:
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
* { ... }
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!
Styling Text
In This Chapter
Choosing Fonts
Google Fonts
Sizing Text
Formatting Text
Formatting for Readability
Wrapping Up
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
Geor g ia
V er da n a
Tr ebu ch et MS
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.
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.
VIDEO 13.1
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:
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.
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
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
@font-face {
font-family: 'Best Font';
src: url('bestfont.woff')
format('woff'),
url('bestfont.ttf')
format('ttf) ;
}
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.
VIDEO 13.4
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.
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;
}
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.
VIDEO 13.6
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
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:
But as CSS has evolved, there are now some other values
to consider:
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.
font-style
Next up is the font-style property, which italicizes
text (FIGURE 13.13). There are three values:
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.
.byline {
text-decoration: underline;
}
.byline {
text-decoration: underline
→overline;
}
.byline {
text-decoration: underline
→wavy blue;
}
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.
Along with the above, you can use the following values
for table cells:
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):
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).
VIDEO 13.8
overflow-wrap specif ies whether the browser should insert line breaks into
otherwise unbreakable text (like long words).
word-break specif ies whether to insert a line break when a word would f low
outside an element.
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
VIDEO 13.9
Color in CSS
In This Chapter
Gradients
The border Property
Wrapping Up
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.
VIDEO 14.1
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).
VIDEO 14.2
VIDEO 14.3
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.
Mor e th a n on e color
Dir ection
Size
Linear gradients
The linear-gradient() function accepts two types of
values: those for direction and those for a color list.
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 .
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():
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
Tip
CSS Tricks has a very comprehensive writeup on gradients: css-
tricks.com/css3 -gradients/.
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
border-[side]
border-[side]-[property]
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.
VIDEO 14.6
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
Element Flow
Creating Layers and Overlapping Elements
Wrapping Up
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.
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.
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.
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.
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.
VIDEO 15.2
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.
VIDEO 15.3
Padding Margin
padding-left margin-left
padding-top margin-top
padding-right margin-right
padding-bottom margin-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.
.wrapper {
width: 800px;
}
.wrapper {
width: 800px;
margin: 30px 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).
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;
}
VIDEO 15.4
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;
}
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.
VIDEO 15.5
<div class="wrapper">
<aside>
...
</aside>
<main>
...
</main>
</div>
<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>
.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;
}
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.
<div class="overlay">
<h3>This is an important alert!
→</h3>
</div>
<header>
<h1>A Case of Identity</h1>
</header>
<main>
(content goes here)
</main>
VIDEO 15.6
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.
Wrapping Up
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.
RWD prov ides a bev y of benef its, chief among which are:
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:
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.
Tip
Flexbox commonly refers to the feature in CSS. There is no property called
“flexbox.”
<main>
<article>
...
</article>
<aside>
...
</aside>
</main>
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:
main {
display: flex;
flex-wrap: wrap;
}
VIDEO 16.2
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.
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.
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.
VIDEO 16.3
main {
flex: 1 1 30%;
}
main {
flex: 1 30%;
}
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.
VIDEO 16.4
main {
display: grid;
grid-template-columns: 30% 30% 30%;
}
main {
display: grid;
grid-template-columns: 30% 30% 30%;
grid-gap: 10px 20px;
}
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.
<main>
<article>
...
</article>
<aside>
...
</aside>
</main>
main {
display: grid;
grid-template-columns: 2fr 1fr;
grid-gap: 15px;
padding: 15px;
}
Ea ch lin e is a r ow .
VIDEO 16.5
Grid Templates
In this v ideo, y ou’ll get an in-depth look at def ining and using Grid templates.
<div class="wrapper">
<header>
...
</header>
<main>
...
</main>
<aside>
...
</aside>
</div>
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
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.
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.
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:
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.
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;
}
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.
Wrapping Up
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.
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.
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!
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.
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
<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;
}
Tip
To keep the source code clean, we define only the essential styles.
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
This is a good first step, but the real fun starts at the next
breakpoint: 1000px.
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.
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.
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.
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.
VIDEO 17.4
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 Transitions
CSS Transformations
CSS Animations
Wrapping Up
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:
Tip
Transitions can be applied in other ways, such as through adding a class in
JavaScript.
VIDEO 18.1
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
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
img {
padding: 20px;
width: 250px;
transition: width 2s ease 0.5s
}
img:hover {
width: 350px;
}
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
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.
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);
}
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:
VIDEO 18.4
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.
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
animation-name
animation-duration
animation-timing-function
animation-delay
animation-iteration-count
animation-direction
animation-fill-mode
animation-play-state
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.
<p class="ball"></p>
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
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);
}
}
VIDEO 18.6
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/.
CSS Variables
In This Chapter
Tip
The official specification name for variables is custom properties:
developer.mozilla.org/en-US/docs/Web/CSS/--*.
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.
:root {
--accentColor: #EB1DFE;
}
a {
color: var(--accentColor);
}
VIDEO 19.1
Since variables are native CSS, they work just like any
other property or ruleset:
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).
<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
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 }.
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.
<div>
<p>This is grid item 1</p>
<p>This is grid item 2</p>
<p>This is grid item 3</p>
</div>
VIDEO 19.3
: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;
}
}
<h1>This is a heading</h1>
<p>This is body text!</p>
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);
}
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
Writing Sass
Wrapping Up
Figure 20.1 What Sass syntax looks like, and the CSS
it outputs
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.
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.
For the purposes of this book, there are two ways you
can get started with Sass:
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).
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
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
Ma th oper a tor s
.wrapper {
background: #000000;
color: #FFFFFF;
main {
aside {
border: 1px solid #FFFFFF;
}
}
}
.wrapper {
background: #000000;
color: #FFFFFF;
}
.wrapper main aside {
border: 1px solid #FFFFFF;
}
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 }.
p {
color: #880000;
&:first-child {
color: #008800;
font-size: 1.5rem;
}
}
p {
color: #880000;
}
p:first-child {
color: #008800;
font-size: 1.5rem;
}
VIDEO 20.2
body {
background: $bgColor;
}
Th ey ca n n ot be ch a n g ed in r ea l tim e.
h1 {font-size: 3.75rem; }
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.
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;
}
.big {
font-size: 3rem;
}
.alert-good {
@extend .alert;
@extend .big
background: #000088;
}
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;
}
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.
Wrapping Up
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?
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.
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
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.
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.
The goal is to do the best you can, and most of all make
it relevant to your website’s topic.
VIDEO 21.1
Registering a Domain
Here’s the entire process, start to f inish, of registering a domain with hov er.com.
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.
VIDEO 21.2
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.
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.
VIDEO 21.3
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).
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.
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
Browser Testing
Device Testing
Test in br ow ser s.
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.
Uploa d th e file.
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.
VIDEO 22.1
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:
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:
Loa ds qu ickly
VIDEO 22.2
VIDEO 22.3
VIDEO 22.4
VIDEO 22.5
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
Wrapping Up
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:
Tip
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.
Tip
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
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).
VIDEO 23.2
Kiloby te (KB) 1 02 4
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!
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.
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.
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.
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/.
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.
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.
<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>
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;
}
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.
You can load them using media queries right in the HTML tag:
Click here to v iew code image
This ensures that the last two sty le sheets are only loaded when they are needed.
24
Web Accessibility
In This Chapter
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.
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.
Tip
Two good tools for figuring out workable color schemes are paletton.com/
and coolors.co/.
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.”
3. Click th e CSS Ta b.
4. Click Disa ble A ll Sty les.
Tip
Get a full list of roles, states, and properties at developer.mozilla.org/en-
US/docs/Web/Accessibility/ARIA/ARIA_Techniques.
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.
Testing tools
There are three testing tools you’ll learn how to use to
evaluate your website:
VIDEO 24.2
th e A u dits ta b.
4. Deselect a ll ca teg or ies ex cept A ccessibility (FIGURE 24.9).
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.
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!
JavaScript
Common JavaScript Libraries
Version Control
Build Tools
Wrapping Up
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.
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.
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.
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.
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.
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 .
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.
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.
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.
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.
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.
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.
SYMBOLS
/* and */, commenting CSS code, 128
A
<a> tag, 43
<abbr> tag, 31
<address> tag, 83
anchor tag, 43
aria-describedby, 306
border, 77
colspan, 79–80
itemscope, 84
method, 90
min, 102
name, 90, 92
placeholder, 93
required, 106–107
rowspan, 79–80
step, 104
style, 125
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
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
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
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
<div> tag, 53
<dl> 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
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
G
GB (gigabyte), 291
general sibling selector (~), 138
H
<h1> tag, 19
<head> tags, 22
hover.com, 267
href attribute, 43
I
<i> tag, 30
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
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
<li> tag, 28
links
# (hash) symbol, 52
M
mailto: links, specifying, 43
MB (megabyte), 291
media formats, 58–59, 68–69
media queries, 64, 196, 216–217, 246–247
<meta> tag, 23
MP3 format, 71
.MP4 file extension, 68–69
-ms- browser prefix, 214
N
name attribute, 23, 90, 92
name in URL, 37
naming
classes, 133
directories, 12
nav menu, making responsive, 225
O
-o- browser prefix, 214
P
<p> tag, 18
pixel density, 63
pixel vs. vector graphics, 59
pixels (px), font-size, 154
polyline element, 67
<pre> tag, 32
root folder, 14
rotate(), transform, 233–234
S
<s> tag, 30
SCSS, 253
search form, 93
<section> tag, 52
<small> tag, 31
space.jpg image, 60
<strong> tag, 30
subdomain in URL, 37
subfolders, 13
submit format, forms, 95
<sup> tag, 31
T
<table> element, 76–77
tables, 76–80
tags
<a>, 43
<abbr>, 31
accessibility, 305–306
<address>, 83
<article>, 52, 83
<b>, 30
<blockquote>, 29
<body>, 22
<br>, 31
<canvas>, 113
<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
<i>, 30
<img>, 60–61, 63
<input>, 90
<ins>, 31
<legend>, 104
<li>, 28
<link>, 127
<meta>, 23
<meter>, 105
overlapping, 190–191
<p>, 18
<pre>, 32
vs. rulesets, 4
<s>, 30
<section>, 52
<select>, 96
<strike>, 30
<strong>, 30
<sub>, 31
<sup>, 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
TextEdit, 10
text-indent property, 159–160
<time> tag, 31
title attribute, 61
<title> element, 22
U
<u> tag, 30
<ul> tag, 28
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
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
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