0% found this document useful (0 votes)
571 views218 pages

HTML Intuitive Guide I PDF

Uploaded by

Ana Arcila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
571 views218 pages

HTML Intuitive Guide I PDF

Uploaded by

Ana Arcila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 218

Title: HTML: The Intuitive Guide

Edition: I
Release: March 12, 2018
Updated: March 3, 2020
Genre: Software Education
Publisher: Learning Curve Books
Imprint: Independently published
ISBN: 9781980538301
Author: Greg Sidelnikov
Contact: [email protected]

The primary purpose of Learning Curve Books publishing company is


to provide effective education for our readers. We hope you enjoy learning
from this edition of HTML: The Intuitive Guide. For questions and comments
about the book you may contact the author or send an email directly to our
office at the email address mentioned below.
Special Offers & Discounts Available
Schools, libraries and educational organizations may qualify for special prices.

Get in touch with our distribution department at


[email protected]

Learning Curve Books, LLC.

2018
c – 2020
Contents
0.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
0.2 Who Is This Book For? . . . . . . . . . . . . . . . . . . . . . . 1
0.3 Book Format . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
0.4 Where Do I Enter HTML Code? . . . . . . . . . . . . . . . . . 4
0.4.1 Windows PC . . . . . . . . . . . . . . . . . . . . . . . 4
0.4.2 Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
0.5 Integrated Development Environment . . . . . . . . . . . . . . 8
0.6 Viewing Your Website In a Web Browser . . . . . . . . . . . . 9

1 Chapter I – Primal HTML 11


1.1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.2 Anatomy of an HTML Tag . . . . . . . . . . . . . . . . . . . . 12
1.3 Pairing HTML Tags . . . . . . . . . . . . . . . . . . . . . . . 12
1.4 Closing Tags In Correct Order . . . . . . . . . . . . . . . . . . 13
1.5 Nested Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.6 HTML Comments . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.6.1 Multi-line Comments . . . . . . . . . . . . . . . . . . . 16
1.7 Relative, Absolute, Blocking And Inline Elements . . . . . . . 17
1.8 When Code Becomes Design . . . . . . . . . . . . . . . . . . . 18
1.9 Default Style . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.10 Overnesting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.11 Self-Closing Tags . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.12 Tags or Elements? . . . . . . . . . . . . . . . . . . . . . . . . 20
1.13 Using HTML Tags For Their Intended Purpose . . . . . . . . 21
1.14 Tag Attributes and Properties . . . . . . . . . . . . . . . . . . 22
1.15 Event Attributes . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.16 HTML Document Structure . . . . . . . . . . . . . . . . . . . 25
1.17 DOCTYPE . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.18 Specifying Website Title . . . . . . . . . . . . . . . . . . . . . 28
1.19 Inline, Internal & External Code . . . . . . . . . . . . . . . . . 28

2 Chapter II - Working With Color 31


2.1 The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.2 HTML Elements And Cascading Style Sheets . . . . . . . . . 33
2.3 Understanding Hexadecimal Values . . . . . . . . . . . . . . . 33
2.4 Setting Background and Font Colors . . . . . . . . . . . . . . 39
2.5 Using Single CSS Property To Set Multiple Values . . . . . . . 42
2.6 Setting Element’s Border Color . . . . . . . . . . . . . . . . . 43

3 Chapter III – Color Gradients 45


3.1 Birds-Eye View . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.2 Choosing an Arbitrary HTML Element for Displaying Gradients 46
3.3 Gradient Types . . . . . . . . . . . . . . . . . . . . . . . . . . 49

4 Chapter IV – Text 54
4.1 Font Family . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.2 Google Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.3 Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.4 Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

5 Chapter V – Hyperlinks 63
5.1 Creating Hyperlinks Using The Anchor Tag . . . . . . . . . . 63
5.2 Removing The Underline . . . . . . . . . . . . . . . . . . . . . 64

6 Chapter VI - Working With Images 65


6.1 Background Images . . . . . . . . . . . . . . . . . . . . . . . . 65
6.1.1 no-repeat . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.1.2 background-size . . . . . . . . . . . . . . . . . . . . . . 67
6.1.3 object-fit: fill—cover—contain—none . . . . . . . . . . 72
6.1.4 background-position . . . . . . . . . . . . . . . . . . . 73
6.1.5 repeat-x . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.1.6 repeat-y . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.1.7 Multiple Backgrounds . . . . . . . . . . . . . . . . . . 75
6.1.8 Image Transparency . . . . . . . . . . . . . . . . . . . 76
6.1.9 Specifying multiple background images . . . . . . . . . 76
6.1.10 Other background properties that take comma-separated
lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.2 Images As HTML Elements . . . . . . . . . . . . . . . . . . . 81
6.3 Changing Image Properties . . . . . . . . . . . . . . . . . . . . 84
6.4 Stretching and Rotating Images . . . . . . . . . . . . . . . . . 84

7 Chapter VII - Tables 89


7.1 If You Can’t Use a Desk Use a Table . . . . . . . . . . . . . . 89
7.2 Using <thead>, <tbody> and <tfoot> . . . . . . . . . . . . . 92
7.3 Decorating HTML Tables . . . . . . . . . . . . . . . . . . . . 93
7.4 Oh, And One More Thing About <th> Tag . . . . . . . . . . . 94

8 Chapter VIII - Forms 96


8.1 Creating Your First Form . . . . . . . . . . . . . . . . . . . . 96
8.2 Submitting Forms . . . . . . . . . . . . . . . . . . . . . . . . . 98
8.2.1 What Are HTTP Requests? . . . . . . . . . . . . . . . 99
8.2.2 GET Method . . . . . . . . . . . . . . . . . . . . . . . 99
8.2.3 POST Method . . . . . . . . . . . . . . . . . . . . . . 99
8.3 HTML Form Controls . . . . . . . . . . . . . . . . . . . . . . 100
8.4 Hidden Form Inputs . . . . . . . . . . . . . . . . . . . . . . . 105
8.5 Radio Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
8.5.1 Labeling Radio Buttons . . . . . . . . . . . . . . . . . 106
8.5.2 Determining Default Radio Button . . . . . . . . . . . 107
8.6 Checking Form’s Values Before Submitting Them . . . . . . . 107
8.7 HTML5 Form Validation . . . . . . . . . . . . . . . . . . . . . 108
8.7.1 Regular Expression Patterns . . . . . . . . . . . . . . . 110
8.7.2 First and Last Names . . . . . . . . . . . . . . . . . . . 111
8.7.3 Usernames . . . . . . . . . . . . . . . . . . . . . . . . . 111
8.7.4 Email Address . . . . . . . . . . . . . . . . . . . . . . . 112
8.7.5 Password . . . . . . . . . . . . . . . . . . . . . . . . . 113
8.7.6 Phone Numbers . . . . . . . . . . . . . . . . . . . . . . 114
8.7.7 Regular Expressions . . . . . . . . . . . . . . . . . . . 115
8.8 Clicking The Submit Button . . . . . . . . . . . . . . . . . . . 116
8.9 Using Custom Images To Replace Submit Button . . . . . . . 119

9 Chapter IX: Thinking In Pixels 121


9.1 Position and Size of HTML Elements . . . . . . . . . . . . . . 121
9.2 What Are Pixels? . . . . . . . . . . . . . . . . . . . . . . . . . 121
9.3 Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
9.4 Hierarchies of Coordinate Systems . . . . . . . . . . . . . . . . 123
9.5 Position & Display Properties . . . . . . . . . . . . . . . . . . 125
9.6 Text Spans . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
9.7 Default CSS Properties . . . . . . . . . . . . . . . . . . . . . . 127
9.8 From Inline to Block . . . . . . . . . . . . . . . . . . . . . . . 127
9.9 Top, left, bottom, right . . . . . . . . . . . . . . . . . . . . . . 128
9.10 HTML Element Size . . . . . . . . . . . . . . . . . . . . . . . 129
9.11 Margin, Padding and Borders . . . . . . . . . . . . . . . . . . 131
9.11.1 Changing Properties For Individual Sides of Elements . 132

10 Chapter X: Text Behavior 134


10.1 inline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
10.2 block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
10.3 inline-block . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

11 Chapter XII: HTML Elements – Common Properties 138


11.0.1 Anatomy of HTML Elements . . . . . . . . . . . . . . 138
11.0.2 Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . 144
11.0.3 Positioning . . . . . . . . . . . . . . . . . . . . . . . . 145
11.0.4 Floating Elements . . . . . . . . . . . . . . . . . . . . . 148
11.1 Element Modifications . . . . . . . . . . . . . . . . . . . . . . 149
11.1.1 Rounded Corners . . . . . . . . . . . . . . . . . . . . . 149
11.1.2 Z-Index . . . . . . . . . . . . . . . . . . . . . . . . . . 150
11.1.3 box-shadow . . . . . . . . . . . . . . . . . . . . . . . . 151
11.1.4 Scale, Translate, Rotate . . . . . . . . . . . . . . . . . 152

12 Chapter XII: Layout Structure 153


12.1 Flex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
12.2 Grid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

13 Chapter XIII: Building HTML Layouts 158


13.1 YouTube Example . . . . . . . . . . . . . . . . . . . . . . . . 159
13.1.1 Layout Scaffold . . . . . . . . . . . . . . . . . . . . . . 160
13.1.2 Second Level Elements . . . . . . . . . . . . . . . . . . 160
13.1.3 YouTube – Layout Elements . . . . . . . . . . . . . . . 161
13.1.4 YouTube – Source Code . . . . . . . . . . . . . . . . . 164
13.2 Twitter Example . . . . . . . . . . . . . . . . . . . . . . . . . 176
13.2.1 Twitter – Breaking down the layout into sections . . . 178
13.2.2 Twitter – Source code . . . . . . . . . . . . . . . . . . 180

14 Chapter XIV: Building Web Applications 188


14.1 Clock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
14.1.1 HTML – Semantic Structure . . . . . . . . . . . . . . . 190
14.1.2 CSS – Element Style . . . . . . . . . . . . . . . . . . . 190
14.1.3 JavaScript – Animating CSS Styles . . . . . . . . . . . 192
14.2 Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
14.2.1 HTML – Application Scaffold . . . . . . . . . . . . . . 196
14.2.2 CSS – Cascading Style Sheets . . . . . . . . . . . . . . 197
14.2.3 JavaScript – Programming Interactivity . . . . . . . . 200

15 Chapter XV: Creating Meaningful Websites 204


15.1 MetaTags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
15.1.1 Facebook Post Preview . . . . . . . . . . . . . . . . . . 208
15.1.2 Twitter Cards . . . . . . . . . . . . . . . . . . . . . . . 209
16 Thank You 210
0.1 Introduction

0.2 Who Is This Book For?


This book is an introduction to the HTML language. Careful choices were
made in order to provide maximum insight into HTML language for beginners
coming to the world of web design and development for the first time. My
hope is that this book accomplishes this task.

0.3 Book Format


A great deal of time was taken to deliver continuity of content that makes the
entire passage of this book readable from cover to cover gradually illuminating
the subjects that build knowledge on sections covered in prior chapters.
But this book can also be used as a reference where each chapter focuses on
one side of web design with HTML language that you may need to look up at
a particular time on demand.
In my personal experience as a web designer and software developer over the
last decade – looking back – it became clear to me that even though HTML is
an extensive language with seemingly never-ending tags, attributes, events and
CSS properties, in practical reality you need to gain good understanding only
of a handful techniques for developing professional websites and applications.
Besides, knowing too much of HTML in relation to CSS and JavaScript may
backfire on you since not all features are supported in the same way by all
browsers (Chrome, Firefox, Internet Explorer, Safari, Opera, etc.) as recom-
mended by the W3C(https://www.w3.org/html/).
Instead of providing complete documentation of the HTML language this book
has a humble goal of focusing on following issues:
1. Focus on Practical Features. Several years of experience with the
HTML language were poured out and converged into chapters of this book
dealing with issues that actually matter in practice. These are the subjects
that you would repetitively come across regardless of your experience level with
HTML.

1
2. Visual Diagrams. HTML is a visual language. By writing HTML
code, you co-dependently construct visual appearance of your website. A
large amount of time was spent on crafting custom diagrams to describe what
HTML elements look like on a web page. This helps if you’re reading the
book in your spare time riding a bus on your way to work. Perhaps you sim-
ply don’t have time to actually open the browser just to see what a single
HTML element looks like while reading the book.
3. Cascading Style Sheets. HTML is part of the ”trinity” of languages that
together help you create beautiful websites and web applications: HTML, CSS
and JavaScript. It would be a disservice to the beginner HTML developer
to not talk about CSS (Cascading Style Sheets) at all because the two are
so closely related. Instead of creating a pure HTML book, we decided that
describing how HTML layouts are affected by CSS would only add value to
this book.
4. JavaScript. The JavaScript language is an important element of web
development. It may have been acceptable to not talk about it at all in the
early 90’s, when HTML was a young language. But this cannot be said with
the same degree of certainty today. JavaScript provides a way to customize
dynamic functionality of your website. In 2018, the year this book was written,
JavaScript has long earned reputation of being more than just a scripting
language. Entire front-end for web applications is usually created with the help
of JavaScript. HTML structure is designed around DOM (Document Object
Model,) and JavaScript is the language that was originally designed to work
with the DOM. For these reasons it was decided that JavaScript code should
make casual appearance throughout the book. Toward the ending chapters
we will also demonstrate several examples of simple web applications such as
Clock and Calculator the dynamic features of which (tracking which buttons
were clicked, or animating the clock’s hand) would not be possible without
JavaScript.

2
Figure 1: HTML, CSS and JavaScript form The Holy Trinity of modern Web
Design and Development. No matter what type of HTML you will write,
there is always some overlap between the three. If you’re learning one – you’re
learning at least part of the other two.

In this volume we’ll focus just on HTML. However, chapters were carefully
chosen to help the beginners pave the path on their journey to becoming a
Front-End Web Developer and later a Full Stack Developer .
It is assumed that the reader will spend additional time to do the research on
their own. However, this is a fairly reasonable assumption to make for any
technical book.
The contents of this book were designed to help with the learning process.
Hopefully it will become an insightful and helpful tutorial book in your home
library of software books.
By focusing only on the most important parts of HTML language, we hope to
have created a good reference to help the reader become a better web designer,
and we truly hope this book accomplishes this task.
Well I think this is enough background for now and we’re getting ready to start
learning HTML!
But before we move forward, let’s take a look at how you can preview your

3
website files in your browser. After that we will deep-dive into construction of
websites and applications with HTML.

0.4 Where Do I Enter HTML Code?


You are probably an owner of a PC running Windows Operating System, or
Mac running OSX. Luckily for us, HTML can be written in any standard text
editor on the Operating System of your choice.
There are several IDEs (Integrated Development Environments) that help
speed up development time. These are usually the advanced text editors de-
signed specifically for writing code. But what if you don’t want to spend
money on an HTML editor? No problem. You can start by experimenting
with HTML using your standard text editors that already come free and pre-
installed with your Operating System.

0.4.1 Windows PC

If you are on a Windows based PC, you can type HTML into Notepad.exe,
the standard text editor that comes pre-installed with Windows.

Figure 2: Click on the ”Start” button in Windows, type ”Notepad” where it


says ”Search Programs and Files” and hit Enter.

4
Figure 3: Alternatively, you can find Notepad by holding down the ”Windows
Key” and pressing ”R” key at the same time. Type ”Notepad” in the box that
opens and hit ”Enter” key.

Do one of the steps above and after hitting Enter key a fresh copy of Notepad
editor should open!
There are other ways to access Notepad on Windows, and you may as well
create an icon on your Desktop to make repetitive access more convenient in
the future.
Here is some HTML code for a very simple page. It is typed directly into
Notepad, as shown in the following diagram:

5
Figure 4: An example of a very simple website typed into Notepad on Windows
Operating System. Just a few lines of HTML code can be used to construct a
page with a header and basic text. We’ll go in much greater detail to inspect
commonly used HTML tags throughout the rest of this book.

To save your file in HTML format, you must change file format in Window’s
”save file” Dialog Box after you click File > Save on the Notepad menu bar:

Figure 5: After clicking ”Save” this dialog shows up. It is important to change
default file type to All Files(*.*)" instead of Text Documents (.txt)

When saving your HTML files, you must save them using the .html file ex-
tension, and not the default .txt reserved for plain text files. Otherwise, your
browser will not recognize it as an HTML file and will not be able to render
your webpage in the view, but display it as plain text.
The HTML format is still technically a text file. But the browser will interpret
it as an HTML page only if its saved with .html extension.

6
The homepage file is usually saved as index.html. Other pages on your site
can be saved separately, for example: contact.html, about.html, etc.

0.4.2 Mac

Likewise, you can use textEdit, the built-in text editor on the Mac OSX. In
order to access it, locate the small magnifying glass in the upper right corner
of the screen, and start typing ”textEdit”. The OSX should automatically
find the application before you finish typing the whole name:

Figure 6: Click on magnifying glass and type ”textEdit”

Figure 7: Locate textEdit by typing it into the box that shows up.

Finally, once textEdit is opened, you can type your HTML into it in the same
way as you would in Notepad on Windows:

7
Figure 8: Typing HTML code into textEdit on a Mac.

A good editor on a Mac called TextWrangler can be used before moving on


to advanced IDE’s. It’s compact, allows working on multiple files at the same
time, and has support for automatically uploading your files to your web host
(the online web server hosting your files from a ”www” address.)
Basic editors are great for learning. But if you are looking to grow in your
web development career, I recommend finding a good IDE. When working
professionally, it is rare for developers to use just the basic text editors.

0.5 Integrated Development Environment


Numerous advanced editors called IDEs (short for Integrated Development En-
vironment) exist that will make your life as a web developer easier. With
features that make accomplishing common or repetitive tasks more efficiently,
they often help streamline the process of building a website or web application.
Using an IDE is optional and the best ones are usually not free. However

8
if I had to recommend absolutely the best IDE for HTML and JavaScript
development, it would have to be JetBrain’s WebStorm. These IDEs provide
useful features such as, ability to upload your site to your domain name simply
by saving the file. (Otherwise, you should use an ”FTP” program to upload
all web files manually to your web host.) IDEs provide many other features
that just get a lot of rudimentary work out of the way so you can focus on
coding.

0.6 Viewing Your Website In a Web Browser


You don’t have to upload your HTML website to a web host at a ”www”
location in order to preview it in your browser. You can preview it locally in
”offline” mode directly from your hard drive.
To view your HTML file in a browser, save it somewhere on your hard drive.
Open your browser (Let’s say Chrome) side by side with your Windows Ex-
plorer (or ”Finder” on a Mac.) Locate the HTML file you created containing
your website code (index.html for example) and then drag and drop it directly
into the browser.

Figure 9: Drag and drop your HTML file into your browser to preview it.

Now that we got the basics out of the way we’re ready to start learning HTML
language!

9
The rest of this book will guide you through descriptions of common HTML
tags. We will create and gain control over size, position and special properties
of common HTML elements. They are the blocks on the screen that help us
construct entire websites and common User Interface designs.
Together with your patience and creativity this book will guide you toward
creating beautiful websites. You can also take this knowledge to another level
and learn how to build layouts for web applications.
This book provides a solid foundation to get started.

10
1 Chapter I – Primal HTML
In the beginning of the 90’s HTML became the standard language for creating
websites. In those times, the language was pretty basic with just a number
of HTML tags defining a few visual elements for creating simple page design
similar to that of a newspaper.
Although HTML has not undergone many changes to its core specification
since its original conception, it is often the starting point language for those
who are new to the world of web development.
If web development is a brick house where a large majority of visual and
dynamic content is provided by Cascading Style Sheets (CSS) and JavaScript
respectively, then HTML is the cement laid in between.
Today, HTML is used to provide structure to websites, but more importantly
to web applications that display text, graphics and multimedia content. You
may have picked this book up because you were looking to become a graphic
designer and learn how to make websites.
Or perhaps you saw a web application and wanted to learn how create one
of your own. Although building complex web applications requires advanced
knowledge of languages such as JavaScript, at the fundamental level the struc-
tural layout of any website or application is created in HTML which stands
for Hypertext Markup Language.

1.1 Getting Started


Let’s begin our journey by learning the basics. In HTML, we use tags to
define structure. Most of your HTML code will consist of tags. When viewed
in browser a tag becomes an HTML element. Elements are tags represented
visually on the screen. Throughout this book the word tag and element will
be used interchangeably based on context. But what is an HTML tag exactly?

11
1.2 Anatomy of an HTML Tag
A tag is the single building block of your HTML document. They often begin
with an angular bracket that looks like < and end with a closing bracket >.
Whatever goes in between is referred to as the tag’s name. Each tag has a
unique purpose.
Let’s take a look at some examples:
1 <html> i s used f o r e n c l o s i n g your e n t i r e HTML document .
2 <head> i n c l u d e s non−c o n t e n t i n f o r m a t i o n , such a s
e x t e r n a l s c r i p t s , w r i t t e n i n J a v a S c r i p t , CSS and s o
on .
3 <s c r i p t> I n c l u d e a s c r i p t f i l e , u s u a l l y w r i t t e n i n
JavaScript .
4 <t i t l e> The b r o w s e r t i t l e o f your webpage .
5 <body> Content o f your e n t i r e webpage .
6 <p> A paragraph o f t e x t .
7 <h1> Large h e a d e r t e x t .

These are just a few tags out of hundreds that you can use to define structure
of your web page. To display anything meaningful within these tags, however,
tags listed above are usually paired with a closing tag with the same name.

1.3 Pairing HTML Tags


A large majority of HTML tags are used in pair with their closing equivalent.
Whatever goes in between the opening and closing tag is known as that tag’s
content.
For example:
1 <body> E n t i r e body o f our w e b s i t e
2 w i l l be p l a c e d h e r e </body>
3
4 <h1>A l a r g e h e a d e r t i t l e</h1>
5
6 <p> I am j u s t a paragraph o f t e x t . You can
7 w r i t e any t e x t h e r e . </p>

12
1.4 Closing Tags In Correct Order
It’s important to close tags around its content in the same order they were
opened. Otherwise you risk confusing the browser’s HTML code processor if
tags were supplied in mangled order. Try to avoid these common errors:
<body> E n t i r e body o f our w e b s i t e w i l l be p l a c e d h e r e

In this example the <body> tag was opened, but it was never closed. Here
HTML is forgiving enough to close the tag on its own when your page is
actually viewed in the browser. It will still appear correctly. Remember,
HTML was invented to deal with dynamic content even before a web page is
fully loaded into the browser. That means that it is essential for web browsers
to handle cases where HTML cuts off at some obscure place. However, this
doesn’t qualify it as correct HTML code or give us a good excuse not to
properly close HTML tags.
<p>I am an example o f <b>b o l d t e x t i n a s i n g l e paragraph .</p
>

Here we have forgotten to close <b> tag, which stands for bold text. The
browser will still apply the bold formatting to the remainder of the sentence,
but it’s not what we want. Correct version is displayed below:
<p>I am an example o f <b>b o l d t e x t</b> i n a s i n g l e paragraph
.</p>

Here the <b> tag is closed at a correct place, making the phrase ”bold text”
appear in bold letters when viewed from your browser.
We have just created some extremely basic examples demonstrating how HTML
is used to format text. In just a moment we will see what kind of result this
HTML code produces when it’s viewed in the browser. Throughout this book
we will use Google Chrome for displaying results of our HTML experiments!
And to move forward with that, let’s take a look at a slightly more complex
example where we will use tag nesting.

13
1.5 Nested Tags
Every HTML page usually contains a number of nested tags. They help us
semantically divide our HTML document into sections. Some tags will contain
plain text content as shown in the previous example. While other tags like
<div> use nesting to divide the web page into sub-sections to create your visual
layout structure. Below you will see a trivial nesting example.
1 <div>
2 <div>
3 <div>
4 <h1>A l i s t o f my i t e m s</h1>
5 <h2> S l i g h t l y s m a l l e r sub−h e a d e r t e x t .</h2>
6 <p><b>F i g u r e 1 .</b> My amazing l i s t o f i t e m s . <span>
C o n s i s t i n g o f random t e x t .</span></p>
7 <ul>
8 < l i>F i r s t item on my l i s t</ l i>
9 < l i>Second item on my l i s t</ l i>
10 < l i>Third item on my l i s t</ l i>
11 </ ul>
12 </ div>
13 </ div>
14 </ div>

Note that all tags close in the same oder they were opened. The <div> tags
here are used only as an example. They make no difference on the layout of
your page in this case, because they gracefully fold into one another. We’ll
discover how this actually works later in the book when we talk about position
of elements on the screen.
Go ahead, save this HTML in a file (nested.html for example) and drag and
drop it into your Chrome browser.
And here are the results:

14
Figure 10: Nested tags can be used to create general structure for displaying
content. Beside the nested <div> tags, that were used only as an example – and
have no visual effect – in this instance I used two HTML tags we haven’t seen
yet: <ul> and <li>. These tags form an ”unordered list”, a bulletin point
list where instead of numbers a leading dot character appears to indicate a
unique item on the list. Note also that text inside <h1></h1> tags appears
in much larger font. The <h1> tag, which stands for header, is used just for
that purpose. There are also <h2>, <h3>, <h4>, <h5> and <h6> tags used for
sub-header text. The <h6> header is the smallest of them all.

Some of the tags transform into a particular type of formatting when applied
to your text content. In general however, you will find yourself using <div>
tags a lot to accomplish the task of building out overall structure of a webpage
or user interface for your web application.
In the HTML source code that produces results shown in Figure 1. we have
a series of <div> elements which stands for ”division”. Later when we get
to CSS styling chapters we will see how <div> elements can be modified to
appear anywhere on the screen, rather than in sequential order one below the
other. Also, you will learn how to change background color and many other
properties of a <div> element with CSS.

15
1.6 HTML Comments
HTML comments are created using <!-- and //--> bracket pair. Anything
that goes in between these two brackets will not be processed by internal
HTML engine or appear on the screen. It will not become part of your page
structure. Instead, comments simply provide helpful description of the code
that follows.
In a real-world setting, if you happen to design websites for a living, you
are likely to work with other HTML programmers or web developers. Using
comments helps to evangelize the rest of your team so they get an idea of what
you were thinking about when you were writing your code.
1 <h1>Top 10 Albums o f A l l Time</h1>
2
3 < !−− A l i s t o f t o p music albums o f a l l time //−−>
4 <table>
5 <tr>
6 <td>P o s i t i o n</td>
7 <td>Album</td>
8 <td>A r t i s t</td>
9 </ tr>
10 </ table>

This line of code here:


1 < !−− A l i s t o f t o p music albums o f a l l time //−−>

It represents an HTML comment. None of the content in it is actually rendered


in the browser. The message is usually a side note for the web developers alone.

1.6.1 Multi-line Comments

An HTML comment can span across multiple lines.


1 <h1>Top 10 Albums o f A l l Time</h1>
2
3 < !−− A m u l t i −l i n e comment can be used t o t e m p o r a r i l y d i s a b l e
HTML

16
4 <table>
5 <tr>
6 <td>P o s i t i o n</td>
7 <td>Album</td>
8 <td>A r t i s t</td>
9 </ tr>
10 </ table> //−−>

Now the entire <table> is enclosed by comment brackets and will not be
rendered in the browser view but it will still be kept in the document. And if
you want to enable it later, simply uncomment it again.
Sometimes comments are used in a clever way to temporarily disable a block
of code without actually removing it from the document.

1.7 Relative, Absolute, Blocking And Inline Elements


In HTML there are two primary ways of determining positioning of an element:
”relative” and ”absolute.” A large number of tags in HTML have their position
set to ”relative” or ”unset” by default. This is why all of the tags in the
examples up to this point in the book appeared one after the other order
when rendered in browser.
A <div> or any other element can also be situated at what HTML refers to
as an ”absolute” position. In HTML an ”absolute” position of an element is
determined by two additional properties called ”top” and ”left” whose values
are specified in pixels. These values represent how far to the left and bottom
your element is located, relative to the position of its parent element. This
means you have control over exactly where the element will appear on your
page, or at least within its parent.

Quick Note. In HTML nested tags have a parent / child relationship.


Just like in real life, children come from parents. And some of the children
can have their own children. This means that some children elements are
also parents to the tags nested within them.

17
In addition, content within any of these types of elements can be set up to
either ”block” all other elements, or appear ”inline” with them. You’ll see how
this works in a later chapter of this book on page structure. Here we speak
about this only to give you an idea that you have more control over element
placement which we will explore in greater detail in this book.

1.8 When Code Becomes Design


But what about this example where tags are nested or written one after the
other? Simply nesting an element does not always automatically drop it to
the next line of text. Not all HTML tags are expected to behave in exactly
the same way based on their type. Even when they enclose the same type of
content.
For this reason, much of your mastery of HTML language will come from
practice. In my experience people who love to write HTML code also often
develop graphic design skills.
Because HTML code and the visual design of your page’s layout are correlated,
many HTML programmers acquire this type of knowledge intuitively as they
experiment and write more HTML code. Juggle around tags in your HTML
document to see how they affect the layout on the screen when you save your
document and refresh it in your browser to see the changes.

1.9 Default Style


In HTML many tags are assigned a ”default” CSS style even if you didn’t
specify it yourself.
For example, using two <span> tags in a row, will not generate a line break.
But two <div> tags in a row will. This is simply because span tag’s default
CSS ”display” style is set to ”inline-block”, which perpetuates any text added
after it just to the end of the previous tag. But <div> tag’s default ”display”
property style is ”block”, which will drop content added to your HTML doc-
ument immediately after the <div> tag right below it, based on the height of
that <div> element.

18
You’ll learn to intuitively understand what these default styles do for different
types of tags as you continue experimenting.
Notice also that the <b> tag (bold text) around ”Figure 1” is nested within
the <p> tag. One <ul> container tag and three <li> tags were used to create
an unordered list in this example. The <b> tag’s default ”display” style is
”inline-block”, and so for this reason the bold text ”Figure 1” neatly falls into
the integrity of the rest of the sentence in that paragraph.

1.10 Overnesting
In HTML, we can create ordered and unordered lists. An unordered list will
use a small character such as a filled or empty dot. An ordered list will
automatically assign a digit to the list’s item based on its order.
This is just one out of the dozens of tags you will use to construct your layout.
Although not entirely necessary, in a real-world scenario you probably want
to avoid long nesting chains, unless completely necessary. In this example we
have a series of empty <div> tags shown only as an example of how nesting
works.

Best Practice. When creating your layout try to avoid deep nesting, if
possible. While this will not affect performance of your website it might
affect its readability. It is also a lot easier to maintain clean code in the
long run, in case you want to update it with new functionality or adjust
an existing feature. Just a few levels of nesting is enough. Try to aim at 3
to 5 levels per unique User Interface element for best readability.

Websites like blogs and many others consist of several nesting levels. However,
some user Interface designs require that you go beyond that. This is commonly
true of building web applications. Just take a look at the source code of Twitter
or Facebook, if you’re not yet convinced.
More than often, though, deep nesting is an after effect of bad design.
In this book we will continue to keep things as simple as possible. Toward the
end we will build a simple web application just to demonstrate that HTML

19
is not limited to creating simple websites. An example of a fully functional
calculator application will put everything we talked about in the book together.
We’re a bit far from that point right now. Until then, let’s continue our journey
and exploration of primal HTML.

1.11 Self-Closing Tags


Self-closing tags do not require to be paired.
Most common examples of single self-closing tags are <br/> and <hr/> and a
few others. They do not need to be paired with a second closing tag. This is
because self-closing tags assume not to bear any content within them. Their
function is usually decorative. <br/> tag is the Break tag which is often used as
paragraph modifier. Some HTML programmers mistakenly use it for creating
spacing between elements. Because it’s so easy to copy and paste a bunch of
<br/> tags into your code!
1 <hr/> C r e a t e s a wide h o r i z o n t a l l i n e between p a r a g r a p h s o r
content
2 <br/> C r e a t e a l i n e break
3 <p>This i s a paragraph</p>
4 <br/>
5 <br/>
6 <br/>
7 <p>Another paragraph 3 l i n e b r e a k s down</p>

1.12 Tags or Elements?


Tags and Elements are often used interchangeably in conversation between
graphic designers. But are they really one and the same? An HTML element
is usually the visual representation of a pair of tags. Tags become elements
when they are rendered on the screen in your browser.
Here you can see how an element is an encompassing block consisting of two
tags: an opening <p> tag pairsed with its closing </p> equivalent to signify a
paragraph of text.

20
Figure 11: How tags construct elements.

But what about self-closing tag like </br> and </hr> for example?

Figure 12: A self-closing tag.

It is open to interpretation whether you want to call them self-closing tags or


elements. But generally, think of elements as a higher-order tags. Sometimes
you’ll hear programmers refer to the <img /> tag – the one responsible for
displaying images in your HTML document – as ”image element” or ”image
tag.” The same goes for most other tags.

1.13 Using HTML Tags For Their Intended Purpose


With time you will learn how to use each HTML tag for its intended pur-
pose. However, with enough experience some HTML developers start to use

21
Unordered Lists for the purpose of creating a navigation system, for example.
They just strip away the default CSS formatting.
This is often acceptable, and in fact desired, because search engines such as
Google treat site navigation semantically which usually helps your website
appear as more organized and sometimes improve search engine ranking.
In most cases, try not to follow short cuts if you doubt that there isn’t a better
way. There is a good chance that there exists a tag specifically dedicated for
solving a particular problem.
And if that isn’t the case, often CSS is used for applying modifications to
HTML tags. How they are used together with HTML is a whole different
story. Try to keep integrity of sticking to standard practice throughout your
code as much as possible.

Best Practice. Use tags for their intended purpose. For example, avoid
using <br/> tag simply to create more space between text or images. For
that purpose, use padding and margin in external CSS script or directly
within an attribute of the HTML tag in question.

We’ll discuss padding and margin properties later in the book. We’re not quite
there yet. We must first explore attributes and properties and this is the next
subject of this book.

1.14 Tag Attributes and Properties


Up to this point we learned how to create basic webpage structure with com-
mon nesting techniques. We also learned to create paragraphs of text and
make lists.
In order to make HTML tags display more intriguing content or provide ad-
ditional functionality to HTML elements we can use attributes and proper-
ties.
HTML tag attributes require values. Whereas properties are usually stand-
alone keywords that enable or disable certain feature of that tag. For example
a property can determine if a check box is checked by default on page load.

22
Here, checked is a property that was added to the input tag:
<input type = ” checkbox ” checked />

And here is another example. This time, the property disabled added to a
text input field will gray it out, and make changing the value of that input
field impossible:
<input type = ” t e x t ” disabled />

In the long past HTML elements used to support now deprecated attributes
such as color. For example, adding color attribute to a paragraph tag, would
paint the text red:
<p color = ” r e d ”>This paragraph used t o appear i n r e d
l e t t e r s</p>

Don’t get me wrong. If you use this code and display it in Chrome browser,
nothing will change. The attribute color is long deprecated.
I just want to demonstrate that we can use attributes to extend functionality
of HTML tags. Attributes usually have a name and a value. In example above
name was color and value was a text string ”red”. And valueless attributes
are called properties.
<input type = ” r a d i o ” name = ” animal ” d e f a u l t /> Cats
<input type = ” r a d i o ” name = ” animal ” /> Dogs
<input type = ” r a d i o ” name = ” animal ” /> Donkeys

Note that default here is a property. By its mere presence on this tag it
indicates that the radio button for ”Cats” will be selected as the default choice
when page loads.
Note. A string is a line of text. When we get to JavaScript in later chapters,
we will see how JavaScript variables also have a name and a value. This is
common in web development. Whenever we need a value in text format, these
values are often referred to as strings. You will know them by the fact that
they are often wrapped in single or double quotes.
Let’s consider this other example that will actually color text inside the <p>
tag in red color:

23
<p s t y l e = ” c o l o r : r e d ”>This paragraph w i l l appear i n r e d .</
p>

Here we used the style attribute to add CSS to our HTML tag. But the value
”color: red” is not written in HTML language. Here, instead of equal sign we
use a colon instead. Whatever is specified using style attribute will always be
written in CSS language. It has a different syntax than HTML.
This example shows how easy it is to combine HTML and CSS together in one
tag. And here is another example, this time using single quote strings. But
there is no difference:
<p s t y l e = ’ color : red ’>This paragraph w i l l appear i n r e d .</
p>

HTML, CSS and JavaScript are nearly inseparable languages that form the
holy trinity of web development as a whole. CSS provides the style. And
JavaScript provides custom, dynamic functionality to your HTML layout mak-
ing building interactive User Interfaces easier and more fun.
Because this is primarily an HTML book we won’t be diving into CSS or
JavaScript until later chapters. But to avoid talking about either one of the
two would be a disservice to the reader.

1.15 Event Attributes


At this point in the book what’s important to understand is that HTML tags
are often accompanied by attributes. Some attributes provide access to CSS.
While others act as events written in JavaScript language. For example, the
following paragraph tag will create a popup alert when clicked.
<p onclick = ” a l e r t ( ’ I am an a l e r t box ! ’ ) ”>C l i c k me !</p>

Clicking on this paragraph will display a modal Alert box in Chrome browser:
There is a multitude of events you can use in your HTML tags. They all will
be covered at an appropriate place in the book as we make progress.
All this is only touching the tip of the iceberg! Of course it is possible to write
entire programs in JavaScript and integrate them with your HTML layout,

24
Figure 13: An alert box triggered by onclick event on an HTML paragraph
tag.

all within a single HTML document (for example in a homepage file called
index.html). But I don’t want to go farther than this at this point in the
book. Until then, we have a few other things to cover.

1.16 HTML Document Structure


As you continue building out your page structure you will notice that overall
most pages will follow the same pattern where <head> and <body> will be
placed inside <html> tag.
Each tag with a unique name exists to serve its primary purpose. For example
<html> tag will encompass your entire HTML document. The <head> tag is
used to store non-content information such as meta tags, language, character
encoding, copyright and general information about the site.
HTML Document Structure. Before we provide details for all kinds of
different HTML elements later in the book it’s good to get a bird’s eye view
of the full picture. Below is a common structure of an HTML page:
1 < !DOCTYPE html>
2 <html>
3 <head>
4 <t i t l e>B a s i c HTML Document</ t i t l e>
5 <meta name = ” d e s c r i p t i o n ”
6 content = ”My w o n d e r f u l w e b s i t e , i n c l u d i n g c a t
p i c t u r e s , and a few o f my own e x p e r i m e n t s with t h e
a r t i s t i c e l e m e n t s o f photography . ”>

25
7 <meta name = ” keywords ”
8 content = ” c a t s , photos , e x p e r i m e n t s ”>
9 <head>
10 <body>
11 <ul>
12 < l i>F i r s t item on my l i s t</ l i>
13 < l i>Second item on my l i s t</ l i>
14 < l i>Third item on my l i s t</ l i>
15 </ ul>
16 </body>
17 </html>

Instead of aimlessly trying to create HTML elements that do nothing in par-


ticular, we are now looking at a legitimate HTML document structure. All
pages you will create from now on will have at least this skeletal design!
Notice here the addition of two <meta> tags. A meta tag does not affect visual
layout of your page. The same goes for any tag located within the head tags
in your HTML document. They’re here for descriptive purpose alone. Or for
adding external scripts (more on this later.) In other words these meta tags
are here only to suggest some information about the content of your website.
These meta tags require both attributes: name and content. In name, you
will specify the type of the meta tag. And in description, you will specify the
value of the meta tag related to its name.
Meta tags are present on almost all web pages that exist on the Internet. They
serve this simple purpose:

• description meta tags are read by Google search engine to provide


information shown along with your website when it appears as a search
result, just below the website title. They briefly outline the purpose of
your website.
• keyword meta tags are also used by search engines. For its value, use
targeted keywords that describe your website with as much precision as
possible. Each keyword should be separated by a comma or space.

Be as specific as possible. What you enter in meta tags may (or may not)

26
affect how your website ranks on Google. This technique used to be much more
effective among those who wanted to ”search-engine optimize” their website
for better ranking. And although modern search engine algorithms give meta
tags less attention when trying to determine relevancy of a website, it is still
important to be as descriptive as possible when using them.

1.17 DOCTYPE
While we will not cover all of the meta tags and various details of constructing
a complete site header in HTML (primarily because they have no practical
effect on either success of your website with search engines, or achieving useful
layout or design function,) DOCTYPE deserves a little of our attention.
<!DOCTYPE html> directive determines HTML version of the document. Nowa-
days this is the most common directive. Although there are a few other alter-
natives, but we’re not concerned with them right now. For now, let’s assume
that all HTML pages will start with <!DOCTYPE html>.
We’ve also used <head>, <title> and <body> tags to define a basic HTML
document structure. You will find this common pattern in just about every
site. This pattern is the standard way of starting any webpage, and it has not
changed since the 90’s.
Just as an example we’ve also used the now familiar HTML tags used for
creating Unordered Lists: <ul> and <li>. It will create a list of items as
shown in the screen shot below when this HTML code is displayed in Chrome
browser:

Figure 14: Notice ”Basic HTML Document” appears as name of the tab.

27
1.18 Specifying Website Title
By specifying text between <title>here</title> tags we tell the browser
what to display in the tab when our website is viewed online. Note that the
title tag should be nested under head tag.

1.19 Inline, Internal & External Code


In one of our previous examples we demonstrated how JavaScript can be called
directly from an HTML attribute. As your website grows in size you will
find yourself adding a lot more CSS and possibly JavaScript code. It’s not
uncommon for a medium size web application to draw a distinction between
HTML, CSS and JavaScript by providing a place to separate one language
from the other.
Inline – Writing CSS or JavaScript directly into an HTML style attribute or
various event attributes.
Internal – To associate CSS or JavaScript code internally right within your
HTML code you can place CSS code inside stand-alone <style> tags. And
JavaScript inside stand-alone <script> tags. This all can be done within the
same index.html file together with your main HTML code.
External – In order to prevent large convoluted files HTML offers ability to
store CSS and JavaScript files externally in separate files apart from the main
index.html file. For example all of your CSS code could go inside ”style.css”
and JavaScript code could be stored in script.js. Then, these files are ”in-
cluded” or ”added” using <link> (for CSS) or <script> tags respectively.
Source Code Examples
Let’s expand on previous source code by adding inline, internal and external
definitions of CSS and JavaScript code. Why we have so many different ways
of adding foreign code into our HTML document will become more clear as
we move forward.
Below we’ll take a look at a piece of HTML code that demonstrates the fol-
lowing:

28
Line 4: Include external javascript file script.js
Line 5: Include external javascript file utility.js
Lines 6-9: Provide free space for writing internal JavaScript directly in
your HTML document. This code typically executes at the same time
while the webpage is actually downloading into the browser.
Lines 10-12: Include external CSS file style.css
Lines 13-15: Include internal CSS. Write directly into the HTML file.
Lines 18-21: Include internal CSS. Same as above but only inside <body>
tag.
Lines 27-31: Include internal JavaScript at the very bottom of the page
(different.)

1 <DOCTYPE html>
2 <html>
3 <head>
4 <s c r i p t src = ’ s c r i p t . j s ’ type = ” t e x t / j a v a s c r i p t ”></
s c r i p t>
5 <s c r i p t src = ’ u t i l i t y . j s ’ type = ” t e x t / j a v a s c r i p t ”></
s c r i p t>
6 <s c r i p t type = ” t e x t / j a v a s c r i p t ”>
7 var t e x t = ” H e l l o t h e r e . ” ;
8 var number = 1 ;
9 </ s c r i p t>tb
10 <l i n k r e l = ” s t y l e s h e e t ”
11 type = ” t e x t / c s s ”
12 href = ” s t y l e . c s s ”>
13 <s t y l e type = ” t e x t / c s s ”>
14 #l i s t { c o l o r : b l u e ; }
15 </ s t y l e>
16 <head>
17 <body>
18 <s t y l e type = ” t e x t / c s s ” s c o p e d>
19 body { background : w h i t e ; }
20 #l i s t { c o l o r : r e d ; }
21 </ s t y l e>
22 <ul id = ” l i s t ”>

29
23 < l i>F i r s t item on my l i s t</ l i>
24 < l i>Second item on my l i s t</ l i>
25 < l i>Third item on my l i s t</ l i>
26 </ ul>
27 <s c r i p t type = ” t e x t / j a v a s c r i p t ”>
28 var t e x t = ” H e l l o t h e r e a g a i n . S e c r e t number i s =” ;
29 var number = 1 0 ;
30 c o n s o l e . l o g ( t e x t + number ) ;
31 </ s c r i p t>
32 </body>
33 </html>

This is a slightly more advanced example of mixing HTML, CSS and JavaScript.
The purpose of this example is to demonstrate the places within an HTML
document where it’s possible to write code written in languages other than
HTML, because they are so commonly used together.
Note that according to HTML4, an older version of HTML <style> is not
allowed within <body> tag. Even though placing it there would not generate
an error or break your page design in any way. It would still work because
most browsers support it against the specification rules. This is why it’s still
a good habit to try and keep CSS and JavaScript within <head> tab whenever
possible.
In HTML5, however, a tag property called scoped was added. Adding it
to style tag itself makes specifying <style> tags within <body> legal. This
doesn’t really change a lot because as we mentioned earlier writing CSS code
without scoped property will still work in both HTML4 and HTML5.
While these types of details are important if you’re interested in writing valid
HTML code, HTML itself is a very forgiving language. Some mistakes will
not affect the way your design is actually displayed in the browser. This can
be a good and a bad thing. It’s just something to be mindful of.
And finally, notice on lines 027-031 here JavaScript is included internally but
just before the closing </body> tag. Remember that internal JavaScript is ex-
ecuted simultaneously as the webpage continues to download into the browser.
Including JavaScript at the very bottom ensures that most HTML elements
will be loaded into the browser before any JavaScript is executed. This pre-

30
vents a situation where your JavaScript is trying to access an HTML element
that has not yet loaded into the browser. In almost every case this will gener-
ate a JavaScript error which will result in all consequent JavaScript execution
come to a halt, regardless if there was more JavaScript statements to execute.
<link>, <style> and <script> tags can use HTML attributes just the same
like any other element. In case where they refer to another language they need
to specify the format of that language to tell the browser about which type of
content will be used within that tag.
Let’s take a closer look:
1. Specify external CSS file: ”style.css”:
<l i n k type = ” t e x t / c s s ” href = ” s t y l e . c s s ”>

2. Attribute value ”text/javascript” means that content of this tag is JavaScript


code:
<s c r i p t type = ” t e x t / j a v a s c r i p t ”></ s c r i p t>

3. The ”text/css” value informs us that this tag contains internal CSS code
embedded directly into HTML document:
<s t y l e type = ” t e x t / c s s ”></ s t y l e>

4. Same as above but scoped to the enclosing parent tag:


<s t y l e type = ” t e x t / c s s ” s c o p e d></ s t y l e>

Other than ”text/css” and ”text/javascript” HTML provides a few other pos-
sible content types. But at this point, we are not concerned with them. For
example advanced types such as ”WebGL shaders” are useful for making 3D
games on HTML canvas tag. But this is not covered by the scope of this book.

2 Chapter II - Working With Color


One of the first questions a web designer learning HTML for the first time will
inevitably ask is: ”How can I change color of a particular HTML element? ”

31
2.1 The Basics
When HTML language came out for the first time in the 90’s, color was usually
set directly through HTML attributes color and background:
<body background = ” b l a c k ” color = ” w h i t e ”>H e l l o t h e r e , t h i s
i s my webpage</body>

Or an equivalent, using the same colors but in hexadecimal format:


<body background = ”#000000” color = ”# f f f f f f ”>H e l l o t h e r e ,
t h i s i s my webpage</body>

Notice that we are assigning attributes to the <body> tag, which is the parent
container element of the entire page. Therefore, these examples demonstrate
how to invert the default background color of a web page (white) to black and
change text color to white.
This looks simple enough. But don’t rush to use these in your own code just
yet!
These deprecated features were later completely replaced by CSS (Cascading
Style Sheets) implementation. In modern HTML the attributes background,
color and others have been moved to CSS (Cascading Style Sheets).
We’ve learned from a previous chapter that CSS can be applied to HTML
elements by specifying it as a value of the style attribute. For instance, to
produce the same inverted colors from examples above they can (and should )
be assigned to an HTML element using the following CSS:
<body s t y l e = ” background : b l a c k ; c o l o r : w h i t e ”>
H e l l o t h e r e .</body>

Or using hexadecimal (more on this shortly) values:


<body s t y l e = ” background : #000; c o l o r : # f f f ”>
H e l l o t h e r e .</body>

32
2.2 HTML Elements And Cascading Style Sheets
Although CSS is not primary subject of this book, it would be difficult to
provide concrete examples of styling HTML elements without it. For example,
text of a warning or alert message is commonly set to red or orange color. As
we have just pointed out, in HTML color is usually specified in CSS language
using the style attribute.
In this chapter, we have already taken a quick look at setting background
and text colors to an HTMl element. We’ll finish our discussion with a brief
explanation of the Hexadecimal color format and setting the border color (and
size) of HTML elements. By doing so we will briefly touch on CSS, an integral
part of styling HTML.
Note that you should always think of HTML and CSS separately. HTML
should be used to provide only the hierarchical structure of elements in your
document. CSS is layered on top of that structure to modify visual appearance
of those elements.
Another reason for including CSS in an HTML book is because literally none
of the websites you will browse today are ever constructed merely of HTML
alone. If we never talked about CSS, it would be difficult to make examples in
this book look interesting enough or resemble their application in a real-world
scenario.

2.3 Understanding Hexadecimal Values


Let’s start with doing a brief review of how color works in HTML. In HTML
common colors already have named values such as ”red”, ”black”, ”brown”,
”purple” and so on... ready to be used.
But these colors limit us only to the named colors provided by HTML. To get
a full range of colors we must use a slightly advanced color system represented
by numbers stored in hexadecimal format.
Just like in the familiar decimal system where numbers range between 0-10, in
hexadecimal format, we use values between 0-15 to represent a number. Except
instead of using digits 10-15 we use letters A, B, C, D, E and F respectively.

33
Figure 15: Just like in the decimal numbering system that ranges between 0-9,
numbers in Hexadecimal format range from 0 to F. The letters A, B, C, D, E
and F represent digits 10 - 15 in decimal system.

And here are some random examples of colors specified using hexadecimal
format. Note that the # character is decorative. But it’s necessary to use it
when passing colors in hexadecimal format as values to CSS properties.

34
Figure 16: A few colors represented by their equivalent value in hexadecimal
format.

A pair of two hexadecimal digits (0 to F) can be used to represent exactly 256


values between 0 - 255 (note, counting starts with 0, not 1). But how does
HTML really know how to generate a color from values in this format?
Two hexadecimal digits can be used to represent one single color channel
(Red, Green or Blue). Therefore, the value consisting of 6 hexadecimal digits
contains enough data to represent a single color by forming a RGB composite
value!

35
Figure 17: Red in hexadecimal format consists of 255 (#FF) for red channel
and 0 (#00) for both green and blue channels.

Figure 18: Hexadecimal format helps us break colors down in 3 unique chan-
nels: Red, Green and Blue. This gives you complete control over the full range
of colors it’s possible to create using this format.

Figure 19: In HTML, you can pass color values represented in any of the 4
different ways shown on this diagram to the style attribute of an element in
parameters that accept color as a value.

The four color formats are 1. Hexadecimal, 2. Hexadecimal shortened to


three digits, 3. Named colors (red, blue, black, etc.) and 4. by using the RGB
macro that takes Red, Green and Blue channel values as numbers in decimal

36
format between 0 - 255. It’s up to you how you wish to specify colors for your
elements.
Using one format consistently throughout your HTML documents is ideal for
keeping your code uniform and easy to read.

37
Figure 20: Switching the color of a pixel on your monitor to blue consists of
juggling around the R (red), G (green), B (blue) values. In this case, we want
to turn R and G values to 0 and switch the blue channel (B) all the way up
to its highest possible value of (255) or #FF in hexadecimal format.
38
Hexadecimal values provide 16,777,216 unique color values you can use to
color elements on your website. It’s rare for web designers to create HEX
colors manually. Instead Photoshop or online color picker tools can be used
to intuitively determine the value you’re looking for.

2.4 Setting Background and Font Colors

Figure 21: Using style attribute of an HTML element it is possible to modify


its background and text colors.

The example above will produce the default web page look: black text on
white background, so you may not visually see any changes. But this is just
an example!
Alternatively to using the style attribute, you can use the following CSS code:
body { background : w h i t e ; c o l o r : b l a c k ; }

In that case, the code above should be placed between <style></style> tags
nested within <head> tags in your HTML document as mentioned in a previous
chapter.
Of course setting background and text color is not limited just to the body
HTML tag. It will work in exactly the same way on any other HTML element.

39
Figure 22: Likewise, we can set our web page background color to ”sil-
ver”, a named HTML color. In Hexadecimal ”silver” color is represented
by #C0C0C0. Using the RGB macro, you can also specify it as RGB(192,
192, 192). This basically means that setting the average of 192 to each color
channel (red, green and blue), a light grayish color will be produced since the
value of light is distributed equally.

body { background : s i l v e r ; }
body { background : #C0C0C0 ; }
body { c o l o r : #333; }

The text color in this example is set to #333. It is a dark gray color that
is the equivalent of #303030 in Hexadecimal format. HTML accepts shorter
representation of the same color. In the case of gray and few other colors (for
example red can be represented as #FF0000 as well as #F00) it makes sense
shortening the value to 3 digits without losing color precision. Here the color
will be ”scaled” to less color possibilities without losing precision. But in other
cases, it may not be possible, because #000000 format gives you the highest
precision over color contrast in each channel. For example, it is impossible to
represent the color #CF0000 using only 3 digits (The closest you could end
up with either #C00 or #F00 which are visibly different colors.)

40
Figure 23: You can also set background and text colors to any element within
your HTML document. In this example, an arbitrary DIV element is present,
positioned somewhere in the middle of the screen.

Positioning individual HTML elements on your page will be covered through-


out the rest of this book.

Figure 24: Setting background and color of the BODY element by inserting
”inline” CSS directly into style attribute.

Figure 25: Setting font color to black in four different ways. They all create
the same color: ”black” represented by four different color formats.

41
Figure 26: You can also use background-color instead of background property.
The background property is often used to provide a full scope of properties
to how you wish to handle element’s background, including using an image
instead of a color value.

2.5 Using Single CSS Property To Set Multiple Values


Some HTML elements contain multiple values for the same property. This is
why CSS properties can be set individually. For example background-color is
only the color component of the background property. To demonstrate, let’s
break down the background property into individal composite values:
background−c o l o r : #000000;
background−image : u r l ( image . png ) ;
background−p o s i t i o n : top l e f t ;
background−r e p e a t : no−r e p e a t ;
background−s i z e : 100% 100%;

There are a few others, but we’re not concerned with them at this moment.
We can rewrite the code above into the full composite of the CSS background
property. The following format is also completely acceptable by CSS process-
ing engine:
background : #000000 u r l ( image . png ) top l e f t no−r e p e a t ;

Here we set background color, background image URL source, position back-
ground image to start in upper left corner, and finally tell the element not to
”repeat” the background image if the size of the element is larger than the
original size of the image. All of this is done by assigning multiple values to
just a single CSS property called: background.
Many other CSS properties can be set in this way, as well as individually. The
background-repeat property can also be set to ”no-repeat” for example, if you

42
wanted to single it out. In addition other CSS properties such as borders,
padding and margins of an element follow a similar pattern. We’ll take a
look at how this works in practice and in much greater detail in the following
sections of this book.
We’re not concerned with images until one of the next chapters. But it’s nice
to know at this point that it’s also possible to assign a JPG or PNG image as
a background of an HTML element (instead of, or in addition to a solid color)
via the background CSS property.

2.6 Setting Element’s Border Color


Following a similar principle of CSS property composition let’s take a look at
how we can also set color to an element’s border.

Figure 27: Imagine that we have an arbitrary HTML element positioned some-
where in the middle of our page. This can be a DIV, a TABLE or any other
HTML element.

43
Figure 28: To specify the color of the border, we must first construct it using
these three CSS properties: border-width, border-style and finally set the color
with border-color.

Figure 29: To save space, CSS provides this shorthand version where you can
specify width, color and style of the border all in one property value: 10px
solid gray. Here ”solid” stands for the type of the border you wish to draw
around the element. For example setting this property to ”dashed” would
produced a dashed-line border. Or ”dotted” for a dotted line.

Because ”dashed” and ”dotted” lines are implemented differently in browsers


they are sort of a bad practice when it comes to web design. If you wish to
create a dotted or a dashed border around your element (which in itself is a
rare case) and want to ensure that it looks the same in all browsers, you might
need to use custom images or construct it from multiple DIV elements.

44
3 Chapter III – Color Gradients
Gradients can be used for a variety of reasons. But the most common thing
they’re usually used for is to provide a smooth shading effect across the area
of some User Interface element.
Here are a couple more reasons for using them:
Smooth Background Color Shading provides an elegant solution for mak-
ing your HTML elements more appealing to the eye.
Saving Bandwidth is another benefit of using gradients, because they are
automatically generated in browser by an efficient color shading algorithm.
This means that they can be used instead of images, which would otherwise
take a lot longer to download from the web server.
Simple Definitions can be used in background property to create some quite
interesting and sometimes surprising effects. You will be supplying the min-
imum required parameters to either linear-gradient or radial-gradient
properties to create any of the effects demonstrated in the next section.

3.1 Birds-Eye View


In this chapter we will learn how to create these gradients in HTML:

45
Figure 30: If this is a black and white print, you will not see the difference
between gradients that actually use color. However, to master gradients you
really only need a good grasp on their direction and type of which there are
four – linear-gradient, radial-gradient, repeating-linear-gradient
and repeating-radial-gradient. This diagram gives you a good idea of
the variety of gradients it is possible to create for your HTML elements with
CSS.

I cheated a little here... the images above are files from my gradients folder
that I created while working on this book. But how do we actually create
them using CSS commands? The rest of this chapter will provide a solution!

3.2 Choosing an Arbitrary HTML Element for Display-


ing Gradients
We will perform our experiments with the background gradients using this
simple DIV element. Let’s set some basic properties to it first, including
width=500px and height=500px.
For now, we just need a simple square element. Paste this code anywhere in
between <head> tags in your HTML document.
<s t y l e type = ” t e x t / c s s ”>
div {

46
position : relative ;
display : block ;
width : 500 px ;
h e i g h t : 500 px ;
}
<s t y l e>

This CSS code will turn every <div> element on the screen to a square with
dimensions of 500 by 500 pixels. The position and display properties will
be explained further in the book.
Alternatively, we probably want to assign gradients only to one HTML ele-
ment. In which case you can either specify the CSS to an individual div ele-
ment using a unique ID such as #my-gradient-box or any other that makes
sense to you.
<s t y l e type = ” t e x t / c s s ”>
d i v#my−g r a d i e n t −box { p o s i t i o n : r e l a t i v e ; d i s p l a y : b l o c k ;
width : 500 px ; h e i g h t : 500 px ; }
<s t y l e>

And then add it somewhere within your <body> tag as:


< !−− E x p e r i m e n t i n g w i t h Color G r a d i e n t Backgrounds i n HTML
//−−>
<div id = ”my−g r a d i e n t −box ”></ div>

Or type the same CSS commands directly into style attribute of an HTML
element you wish to apply a color gradient to:
<div s t y l e = ” p o s i t i o n : r e l a t i v e ; d i s p l a y : b l o c k ; width : 500
px ; h e i g h t : 500 px ; ”></ div>

47
Figure 31: A div element with dimension of 500 x 500 pixels. The row and
column on the right hand side demonstrate how gradients automatically adapt
to the element’s size. The gradient property was not changed here. Only the
element’s dimensions, yet the gradient looks quite different. Keep this in mind
when making your own gradients!

CSS gradients will automatically adapt to the element’s width and height.
Which might produce a slightly different effect.

Figure 32: The basic idea behind gradients is to interpolate between at least
two colors. By default, without providing any extra values, vertical direction
is assumed. The starting color will begin at the top of the element, gradually
blending in with 100% of the second color at the bottom. It’s possible to create
gradients by combining more than two colors. We’ll take a look at that in a
moment!

48
All CSS gradient values are supplied to CSS background property!
Having said that, here’s an example of creating a simple linear gradient:
background : l i n e a r −g r a d i e n t ( black , w h i t e ) ;

These values will be demonstrated in action below, shown just underneath the
gradient effect they produce.

3.3 Gradient Types


Let’s walk through different gradient styles one by one and visualize the type
of gradient effects you would expect to be rendered within the HTML element,
when these styles are applied to it.

Figure 33: A simple linear gradient. Left: black to white. Right: yellow to
red.

49
Figure 34: Horizontal gradients can be created by specifying a leading value
of either ”to left” or ”to right”, depending on which direction you wish your
gradient to flow across the element.

Figure 35: You can start gradients at corners too to create diagonal color
transitions. Values ”to top left”, ”to top right”, ”to bottom left” and ”to
bottom right” can be used to achieve that effect.

50
Figure 36: When 45 degree corners are not enough, you can supply a cus-
tom degree between 0 – 360 directly to the linear-gradient property as in
linear-gradient(30deg, black, white); Notice how in this example the
gradient gradually changes direction from flowing toward the bottom, toward
the left hand side when angle is changed in progression from 10 to 90 degrees.

Figure 37: Radial gradients can be created by using radial-gradient prop-


erty. Swapping colors around will produce an inverse effect.

51
Figure 38: In the same way as linear gradients, radial gradients can also take
origin at any of the four corners of an HTML element.

52
Figure 39: Repetitive patterns for linear and radial gradients can be cre-
ated using repeating-linear-gradient and repeating-radial-gradient
respectively. You can provide as many repetitive color values in a row as
needed. Just don’t forget to separate them by a comma!

Figure 40: Finally – the most advanced type of a gradient can be created using
a series of HSL values. HSL values don’t have named or RGB equivalents, they
are counted on a scale from 0 – 300. See the explanation below.

53
Figure 41: You can cherry-pick any color by using values between 0 – 300.

We’ve already provided examples of property values associated with each gra-
dient. But here they are again in one place. Play around with the values and
see what type of effects they produce on your custom UI elements:
background : l i n e a r −g r a d i e n t ( y e l l o w , r e d ) ;
background : l i n e a r −g r a d i e n t ( black , w h i t e ) ;
background : l i n e a r −g r a d i e n t ( t o r i g h t , blac k , w h i t e ) ;
background : l i n e a r −g r a d i e n t ( t o l e f t , bl ack , w h i t e ) ;
background : l i n e a r −g r a d i e n t ( t o bottom r i g h t , bl ack , w h i t e ) ;
background : l i n e a r −g r a d i e n t ( 9 0 deg , blac k , w h i t e ) ;
background : l i n e a r −g r a d i e n t (
h s l (0 ,100% ,50%) ,
h s l (50 ,100% ,50%) ,
h s l (100 ,100% ,50%) ,
h s l (150 ,100% ,50%) ,
h s l (200 ,100% ,50%) ,
h s l (250 ,100% ,50%) ,
h s l (300 ,100% ,50%) ) ;
background : r a d i a l −g r a d i e n t ( black , w h i t e ) ;
background : r a d i a l −g r a d i e n t ( a t bottom r i g h t , bl ack , w h i t e ) ;
background :
r e p e a t i n g −l i n e a r −g r a d i e n t
( w h i t e 100 px , b l a c k 200 px , w h i t e 300 px ) ;
background :
r e p e a t i n g −r a d i a l −g r a d i e n t
( w h i t e 100 px , b l a c k 200 px , w h i t e 300 px ) ;

4 Chapter IV – Text
Text is the most simple type of content in HTML.

54
In this section we will explore how to change appearance of HTML text by
adjusting following properties: Font Family, color, and size.

4.1 Font Family


Font-family is just another way of referring to font style or font type, for
example: Arial, Verdana, Tahoma or the default Times New Roman.
To set Arial as the font for text written inside the web page parent element
<body> and all of its children elements you can use this CSS code:
body { f o n t −f a m i l y : A r i a l ; }

To set Verdana as the font for absolutely all HTML elements in your document,
you can use the star (”*”) character:
∗ { f o n t −f a m i l y : Verdana ; }

Although not absolutely necessary, HTML text is often enveloped in <span>


tags. When this is the case, these span elements will inherit the width of
the text contained within them and be treated as ”inline” elements by default
(we’ll explore inline elements in a lot more detail later in the book.) The width
of the span elements containing text is automatically determined by taking in
consideration font’s family and size.
Examples below demonstrate not only that, but also the fact that the upper
left corner of span elements is counted as their origin point. For example, if
you rotate this element around (we’ll take a look at this also later in the book,)
the element will be rotated around its upper left corner. Most other elements
in HTML also share the upper left corner as the element’s pivot. So from now
on in the book if you see a small circle with a dot and arrows, it will indicate
the assumed starting location point of the element. Why this is important
will become more clear when we reach chapters on element positioning on the
screen.
Let’s take a look at some commonly used HTML fonts:

55
Figure 42: Times New Roman is the default font type in HTML.

Figure 43: Verdana.

Figure 44: Arial. Google’s favorite.

Figure 45: Computer Modern (The font this book was written in.)

Figure 46: Computer Modern Classical.

56
Figure 47: Sectioning text using span elements.

You can section text into blocks using different styles. Sometimes italicizing
or making text bold becomes necessary.

4.2 Google Fonts


Arial, Verdana and Courier (for code listings) are all great fonts. But some-
times, the standard set provided by your Operating System is not sufficient for
creating a particular impression. This is especially true when planning unique
wire-frames for website layouts or user interfaces, where the style of text is
part of the subtle impression created by the design itself.
Many beautiful fonts are available at fonts.google.com – the font repository
created by Google.

57
Figure 48: Point your browser at fonts.google.com to browse a set of alternative
fonts from Google Fonts.

Select one or more fonts by clicking on the red plus button next to each. You
will notice a new tab appearing toward the bottom of the screen. Click on the
tab to open instructions on how to install selected fonts on your website:

58
Figure 49: The ”Roboto” font was selected. The tab provides installation
instructions.

Google Fonts come in different flavors. You can type your own phrases to see
what they look like in the selected font before installing it. For example, here
is what the title of this book looks like in several different manifestations of
the ”Roboto” font:

59
Figure 50: The title of this book rendered using the custom ”Roboto” Google
font.

Thin fonts are really great for achieving that ”modern” look you see on many
brand websites.
Embedding the font into your HTML code is a straightforward process. Copy
and paste the <link> tag generated from this tab into your HTML document
anywhere between <head> tags.
<l i n k href=” h t t p s : / / f o n t s . g o o g l e a p i s . com/ c s s ? f a m i l y=
Roboto ” r e l=” s t y l e s h e e t ”>

Every time you want to use ”Roboto” font in your HTML, simply specify it
as a value to the CSS property font-family.

4.3 Color
Changing font color is probably the easiest thing you can do in CSS. But
Hexadecimal color values can be a little tricky to figure out, especially if you’ve
never used them before.

60
< !−− Let ’ s p a i n t t h i s paragraph ’ s text b l u e //−−>
<p s t y l e = ” c o l o r : b l u e ; ”>A p i e c e o f t e x t i n b l u e .</p>

< !−− Same as above , e x c e p t u s i n g a h e x a d e c i m a l


color value f o r ” b l u e ” //−−>
<p s t y l e = ” c o l o r : #0000 f f ; ”>A p i e c e o f t e x t i n b l u e .</p>

< !−− Same as above , u p p e r c a s e c h a r a c t e r s


a r e a l l o w e d i n hex f or m a t //−−>
<p s t y l e = ” c o l o r : #0000FF ; ”>A p i e c e o f t e x t i n b l u e .</p>

< !−− Same as above , b u t r e d u c e d t o 3 d i g i t s


( n o t e ; not a l l c o l o r s can be a b b r i v i a t e d t h i s way ) //−−
>
<p s t y l e = ” c o l o r : #00F ; ”>A p i e c e o f t e x t i n b l u e .</p>

Luckily, we’ve already covered hexadecimal values in an earlier chapter Chapter


II – Working With Color.
Head over there if you need a refresher!

4.4 Size
To set font size to a paragraph the font-size property is used:
<p s t y l e = ” f o n t −s i z e : 12 px ; ”>
This l i n e o f t e x t w i l l be d i s p l a y e d u s i n g a f o n t
with i t s s i z e s e t t o 12 p i x e l s .</p>

In HTML it is possible to specify font size using em (relative to capital M in


typography), px (pixels), pt (points) and in (inches).
It would be difficult to see the subtle difference these measurement units pro-
duce in comparison to each other without rendering some code in the browser.
However, this diagram will hopefully make it a bit more clear:

61
Figure 51: Comparison between default HTML font Times New Roman and
the way different measurement units affect its size.

They’re all slightly different – but in general 1em = 12pt = 16px = 100%
The em in typography stood for the width of the capital letter M.
<p s t y l e = ” f o n t −s i z e : 1 . 6 em ; ”>A l i n e o f t e x t with
f o n t s e t i n ”em” typography u n i t .</p>

The most common unit, pixels or px is used to measure font size in pixels.
<p s t y l e = ” f o n t −s i z e : 12 px ; ”>A l i n e o f t e x t whose
s i z e i s s e t i n p i x e l u n i t s .</p>

A point or pt is a unit of measurement used for real life ink on paper typog-
raphy.
<p s t y l e = ” f o n t −s i z e : 17 pt ; ”>A l i n e o f t e x t with i t s
s i z e s e t u s i n g p o i n t u n i t s .</p>

The in unit can be used to match your font size to the actual size of an inches
on the screen, or its fraction.
<p s t y l e = ” f o n t −s i z e : 0 . 2 5 i n ; ”>A l i n e o f t e x t with
f o n t s i z e s e t t o q u a r t e r o f an i n c h .</p>

62
5 Chapter V – Hyperlinks
In HTML hyperlinks are clickable links that appear inside text blocks. Clicking
on them will redirect your browser to the URL specified in the HREF attribute.
It is my guess that HREF stands for Hyperlink Reference. This value can also
be a DIV element’s ID, and if such is the case, clicking on the link will move
your browser view to the element matching that ID.

5.1 Creating Hyperlinks Using The Anchor Tag


Hyperlinks are created using the <A> HTML tag (which stands for anchor ).

Figure 52: This is what a hyperlink appears as in your HTML document. You
see them all the time! But they also have a special purpose of linking your
sites to other sites, or other web pages on your own domain name.

But how exactly do we create one? Below is an example of HTML code


required to create a fully fledged hyperlink that also includes title text.
Specifying text in the extra title attribute is usually done to add detail to
the description of the page the hyperlink is pointing to. Search engines are
very clever at using this subtle information to categorize websites. So it is
advised to spend an extra moment to decide what the title text should say.
Use keywords or full sentences that describe the page the hyperlink is pointing
to to the best of your ability. But don’t forget to be as accurate as possible.
Some of your page ranking on search engines such as Google depends on this!

63
Figure 53: The composition of an HTML hyperlink. That’s really all there is
to it. Hyperlinks behave just like any other text elements. The only difference
is that they are clickable and automatically inherit the ”pointing hand” cursor.

5.2 Removing The Underline


Sometimes web designers remove the default text underline style from a hy-
perlink. You can easily achieve that by setting text-decoration property to
”none”:
<a href = ” h t t p : / /www. g o o g l e . com”
t i t l e = ” Google s e a r c h e n g i n e ! ”
s t y l e = ” t e x t −d e c o r a t i o n : none ; ”>Google</a>

This will effectively remove the line underneath the hyperlink.

64
6 Chapter VI - Working With Images
In this chapter we will take a look at using images in your HTML document.
There are two notably unique ways of using images in HTML.
First, you can use images as a background fill for an element. But you can
also use images as individual blocking HTML elements, in the same way you
would use a <div> or any other blocking element.
Background images fill the entire content area of an HTML element with a
source image, instead of a solid color.

6.1 Background Images


Note: If the element’s dimensions are bigger than those of the source image,
the image will be repeated within the body of that element – repetitively filling
the remainder of the element’s sides with the contents of the image. It’s almost
like stretching infinite wall paper over an element. See example below:

Figure 54: The default background image behavior.

To set the background image to any element you can use the following CSS

65
commands.
< !−− s e t background image t o body //−−>
<body s t y l e = ” background : u r l ( ’ k i t t e n . jpg ’ ) ”></body>

< !−− or a l t e r n a t i v e l y . . . //−−>


<body s t y l e = ” background−image : u r l ( ’ k i t t e n . jpg ’ ) ”></body>

You can also use internal CSS, placing this code between <style></style>
tags:
body { background−image : u r l ( ’ k i t t e n . jpg ’ ) ; }

Or...
body { background : u r l ( ’ k i t t e n . jpg ’ ) ; }

6.1.1 no-repeat

Let’s take a look at the same kitten background, except this time with no-repeat
value set to background-repeat property;
You can prevent a background image from following its default behavior, by
setting background-repeat property to the value of no-repeat, provided that
the image was also already set via background-image: url("kitten.jpg"):

66
Figure 55: You can prevent the background image from repeating itself
by setting either the individual property background-repeat: no-repeat
or together with the image source file background: url("kitten.jpg")
no-repeat;

6.1.2 background-size

The background-size property gives you control over the size of the back-
ground image. In particular, it is helpful when the image needs to be scaled
across the element’s dimensions. Different values will produce various tiling
effects and patterns. They will be demonstrated in this section.
The background-size property takes following values: unset, none, initial,
auto, percent, percent percent (separated by space for x-axis and y-axis
respectively,) cover and contain:

67
Figure 56: Default settings. Any of the values unset, none, initial and auto
produce default behavior under standard circumstance.

68
Figure 57: background-size can optionally take x-axis and y-axis parameters
separated by space character.

69
Figure 58: cover and contain.

Figure 59: By combining background-repeat: no-repeat; with


background-size: 100% it is possible to stretch the image only horizontally,
across the entire width of the element.

What if you want to repeat background vertically but keep it stretched across
the width? No problem, simply remove no-repeat from previous example.
This is what you will end up with:

70
Figure 60: This is really useful if you need to blow up a large image across the
screen without sacrificing vertical repeat.

Sometimes it is needed to stretch the image across to fit the bounding box of
an element. This often comes at a price of some distortion, however:

Figure 61: background-size: 100% 100%

Note here, 100% 100% is repeated twice. The first value tells CSS to ”stretch
the image vertically”, the second 100% does the same horizontally. In HTML,
whenever you need to specify multiple values, they are often separated by a
space. Vertical coordinates always come first.

71
6.1.3 object-fit: fill—cover—contain—none

Cover and contain values from previous section can also be used on HTML el-
ements such as images, videos and similar media. In this case, when cover and
contain are used with object-fit CSS property, behavior of these elements
follows rules demonstrated in the diagrams below:

Figure 62: fill, cover, contain and none produce similar results to
background-size property, except they work on HTML media elements, rather
than background images.

72
6.1.4 background-position

Figure 63: Center on the screen without repeat can be achieved by combin-
ing background-repeat: no-repeat and background-position: center
center;

In another scenario you can force the image to be always in the center and
keep the repeat:

Figure 64: background-position: center center; with


background-repeat: repeat;

73
6.1.5 repeat-x

You can repeat the image across the x-axis only (horizontally) using repeat-x:

Figure 65: CSS style: background-position: center center;


background-repeat: repeat-x;

6.1.6 repeat-y

To the same effect but on the y-axis repeat-y property can be used:

Figure 66: The background-repeat property set to repeat-y

74
Like any other CSS property, you have to juggle around the values to achieve
the results you want. I think we covered pretty much everything there is about
backgrounds. Except one last thing...

6.1.7 Multiple Backgrounds

It is possible to add more than one background to the same HTML element.
The process is rather simple.
Consider these images stored in two separate files:

Figure 67: Two images that will be used for creating multiple backgrounds.

The chessboard pattern in the image on the right is only used to indicate
transparency here. The white and grayish squares are not an actual part of
the image itself. This is the ”see-through” area, which you would usually see
in digital manipulation software.
When the image on the right is placed on top of other HTML elements or
images, the checkered area will not block that content underneath. And this
is the whole idea behind multiple backgrounds in HTML.

75
6.1.8 Image Transparency

To fully take advantage of multiple backgrounds, one of the background images


should have a transparent area. But how do we create one?
In this example, the second image (image2.png) contains 5 black dots on a
transparent background (indicated by a checkered pattern.)

Figure 68: To create images with transparent backgrounds, tools such as Pho-
toshop can be used. Just select the Magic Eraser tool from the toolbox.

Like many other CSS properties that accept multiple values – all you have
to do – to set up multiple backgrounds is to provide a set of values to the
background property separated by comma.

6.1.9 Specifying multiple background images

To assign multiple (layered) background images to the same HTML element,


the following CSS can be used:
body { background : u r l ( ’ image2 . png ’ ) , u r l ( ’ image1 . png ’ ) ;
}

76
The order in which you supply images to the background’s url property is
important. Note that the top-most image is always listed first. This is why
we start with image2.png
This code produces the following result:

Figure 69: Multiple background in use. Here image2.png is superimposed on


top of image1.png.

In this example we demonstrated multiple backgrounds in theory on a subjec-


tive <div> (or similar) element with square dimensions. Let’s take a look at
another example:

77
Figure 70: A puppy and a linoleum-like pattern.

Note here again, that the puppy.png image will be the first item on the comma-
separated list. This is the image we want to superimpose on top of all of the
other images on the list.
Combining the two:
body { background : u r l ( ’ puppy . png ’ ) , u r l ( ’ p a t t e r n . png ’ ) ;
}

We get the following result:

78
Figure 71: Multiple backgrounds.

6.1.10 Other background properties that take comma-separated


lists

In the same way, you can supply other parameters to each individual back-
ground, using the other background properties demonstrated below:
background
background−attachment
background−c l i p
background−image
background−o r i g i n
background−p o s i t i o n
background−r e p e a t
background−s i z e

The following property cannot be used with a list, for obvious reasons:
background−c o l o r

79
What would it mean to provide multiple color values to a background? When-
ever color background property is set, it usually fills the entire area with a
solid color. Therefore, it cannot be used in the case of multiple backgrounds
for any meaningful purpose.

80
6.2 Images As HTML Elements
When I started working with HTML images, for some reason I always thought
that they were completely separate entities from your standard HTML ele-
ments such as <div> for example. Perhaps this is because images by nature
are so much more impressive than text content.
The Morris Marina is a car that was manufactured by Austin-Morris division
of British Leyland from 1971 until 1980.

Figure 72: A simple image <img = "auto.png" alt = "Morris Marina">


specimen that we will use to demonstrate working with images in HTML in
this chapter.

I was wrong. The image element in HTML that can be used as <image> or
<img> is just like any other HTML element. The only difference is the content
area, which now contains an image, instead of text.
To prove that, here is an image with border, padding and margin set to some
arbitrary values:

81
Figure 73: An image is just like any other blocking element containing border,
padding, and margin. To be precise, an image is actually an inline and blocking
element at the same time. In other words display: inline-block.

If you set any HTML element’s display property to inline-block that ele-
ment will behave exactly like an HTML image, even if it contains some other
type of content inside.
One of the most common placement for images is in the middle of the page.

Figure 74: An image with img {margin: auto} margin set to auto.

Automatic margins will ensure that the image is aligned to the center of the
page, and if there is any text surrounding the image it will appear above or

82
below it, based on where it is located in your HTML document.

Figure 75: Margin property can be used to position an image within its parent.

The example above assumes that the image’s display property is set to block
and its position is set to relative.
Image margins are often used to bump text away from the image to create
more white space, making the surrounding text easier to read.
But images can be also positioned using display: block and position:
absolute combo. You just need to provide additional values for top and left
properties to define its precise location on the screen relative to its parent
element.
The above example can be interpreted as though the image’s top/left proper-
ties were set to top: 100px and left: 200px to position it within parent
element at exactly the same spot without having to do it via the margin prop-
erty. Which is often the preferred way of doing it.
Note: In order for any HTML element to be accurately positioned within its
parent container element using absolute pixel location the parent element is
required to set its display property to a value of either absolute or relative.
If you fail to do this, the behavior of the child element is unpredictable. But
it will be most likely positioned relative to the root parent element such as
<body>.

83
6.3 Changing Image Properties
For examples in this section, let’s use another image of this barn owl.

Figure 76: owl.png

Figure 77: Owl image with padding, margin and border.

6.4 Stretching and Rotating Images


To stretch an image, simply specify its width property to a number in pixels
or percent. If the value is larger than the original width of the image it will
appear stretched:

84
Figure 78: width: 200%

Likewise, it is possible to stretch an image vertically using height property.

Figure 79: height: 200%

Around 2016 images with round corners started to be in wide use on social
network websites:

85
Figure 80: border: 4px solid black and border-radius: 16px

As of the writing of this book – most social network profiles have turned to
the round image appearance displayed below:

Figure 81: Turning a square image into a circle by maxing out border-radius
property. here we also set border: 4px solid black for a slightly more
dramatic effect.

This look can be achieved by maxing out the border-radius property. Setting
it to an unrealistically high value such as 1000px will ensure that images whose
dimensions are less or equal to 1000px will appear as circles.
You should probably set it to the actual width height of the image if you are

86
absolutely sure that it will never be shown in larger size.

Figure 82: transform: rotate(45deg)

Rotating an image is as simple as providing a degree of rotation in percent


0–360. The value must be post-fixed by ”deg”.

Figure 83: float: left

In newspaper articles, it is common to move the image left or right, so it


doesn’t interfere with the text in the body of the article. To achieve this we

87
can assign the float property to the image with a value of either left or
right.

Figure 84: float: right

But float property will not save us from creating enough space between
text and the image. For this reason we can additionally use the image’s
margin-left or margin-right property.

Figure 85: Using additional margin (margin-left: 16px) we can add more
spacing between the image and the surrounding text.

88
7 Chapter VII - Tables

7.1 If You Can’t Use a Desk Use a Table


Tables are used to display tabular data. Similar to an Excel spreadsheet tables
display information by treating it as rows and columns.
Tags <tr> and <td> are required to be nested within <table> tag, and cannot
and should not be ever used outside of it. They are responsible for creating
blocks of elements that help with construction of a table where <tr> represents
a row and <td> represents a column.

Figure 86: Basic structure of a table element.

Let’s create a basic table displaying Top 10 Albums of All Time:


1 <h1>Top 10 Albums o f A l l Time</h1>
2 <table>
3 < !−− F i r s t row , h e a d e r i n f o r m a t i o n //−−>
4 <tr>
5 <td>P o s i t i o n</td>
6 <td>Album</td>

89
7 <td>A r t i s t</td>
8 </ tr>
9 < !−− Consequent rows l i s t i n g music albums //−−>
10 <tr>
11 <td>1</td>
12 <td>Dark S i d e o f t h e Moon</td>
13 <td>Pink Floyd</td>
14 </ tr>
15 <tr>
16 <td>2</td>
17 <td>Sgt . Pepper ’ s Lonely H e a r t s Club Band</td>
18 <td>The B e a t l e s</td>
19 </ tr>
20 <tr>
21 <td>3</td>
22 <td>Led Z e p p e l i n IV ( aka ZOSO)</td>
23 <td>Led Z e p p e l i n</td>
24 </ tr>
25 <tr>
26 <td>4</td>
27 <td>Abbey Road</td>
28 <td>The B e a t l e s</td>
29 </ tr>
30 <tr>
31 <td>5</td>
32 <td>The Wall</td>
33 <td>Pink Floyd</td>
34 </ tr>
35 <tr>
36 <td>6</td>
37 <td>Nevermind</td>
38 <td>Nirvana</td>
39 </ tr>
40 <tr>
41 <td>7</td>
42 <td>R e v o l v e r</td>
43 <td>The B e a t l e s</td>
44 </ tr>

90
45 <tr>
46 <td>8</td>
47 <td>A Night a t t h e Opera</td>
48 <td>Queen</td>
49 </ tr>
50 <tr>
51 <td>9</td>
52 <td>Ok Computer</td>
53 <td>Radiohead</td>
54 </ tr>
55 <tr>
56 <td>10</td>
57 <td>Pet Sounds</td>
58 <td>The Beach Boys</td>
59 </ tr>
60 </ table>

This HTML table code will produce the following output:

Figure 87:

Creating HTML tables using the structure defined by nested <tr> and <td>
tags as was shown in this example is a straightforward process.

91
7.2 Using <thead>, <tbody> and <tfoot>
Additional table-related HTML elements exist <thead>, <tbody> and <tfoot>,
all three of which are used in conjunction with each other. They determine
purpose of a specific area in your table. These tags are optional and rarely
used in construction of HTML tables. Nonetheless, they might be useful for
improving structural integrity of your tables.
1 <table>
2
3 <thead>
4 <tr>
5 <td>November</td>
6 <td>2 f t .</td>
7 </ tr>
8 </thead>
9
10 <tbody>
11 <tr>
12 <td>December</td>
13 <td>3 f t .</td>
14 </ tr>
15 </tbody>
16
17 <t fo o t>
18 <tr>
19 <td>T o t a l</td>
20 <td>5 f t .</td>
21 </ tr>
22 </ t fo o t>
23
24 </ table>

Regardless where in nesting hierarchy <thead> or <tfoot> are specified, they


will always appear in their proper place when rendered in the browser. The
correct order is retained. For example, consider this intentionally jumbled up
order:
1 <table>

92
2 <t fo o t>f o o t</ t f o o t> < !−− t f o o t f i r s t //−−>
3 <thead>head</thead> < !−− thead second //−−>
4 <tbody>body</tbody> < !−− tbody t h i r d //−−>
5 </ table>

Nonetheless, when viewed in browser, the rows will still be rendered in the
proper order:
− head
− body
− foot

We’ve just summarized the process of creating structure for simple tables.
You may want to experiment by creating a few of your own. In the next
section, we’ll take a look at improving the visual appearance of our tables
using Cascading Style Sheets.

7.3 Decorating HTML Tables


We’ve just considered a few basic HTML tables. But they look plain and a
bit boring. When designing real websites you will probably want to decorate
your table to make them look less visually desolate.
Let’s write some very basic CSS to change the look of any HTML <table>
and make it appear as though it has a lining of 1 pixel in width around its
border and the cells within it.
1 <s t y l e type=” t e x t / c s s ”>
2 t a b l e { border −c o l l a p s e : c o l l a p s e ; }
3 t a b l e , th , t r , td { b o r d e r : 1px s o l i d b l a c k ; }
4 t a b l e td { f o n t −f a m i l y : A r i a l ; f o n t −s i z e : 12 px ; padding :
4px ; }
5 </ s t y l e>

Here CSS style border-collapse: collapse; will make sure that there
are no ”double” borders between each cell in the table. A better font (Arial
is a good font, in my opinion) and some cell padding has been added to <td>
tags.

93
It’s interesting how just simple tweaks to the styling of HTML elements can
produce significant updates to the overal look and feel:

Figure 88:

This looks a lot more readable, compared to the ”default” style-less HTML
table. All this was accomplishes by specifying just a few CSS commands within
<style> tag.

7.4 Oh, And One More Thing About <th> Tag


Up to this point we used <thead> tag to specify table header placement. And
it is the proper tag to use when it is used together with <tbody> and <tfoot>.
In fact it is assumed that you use all 3 tags together whenever you use any
one of them.
But we skipped the <th> tag that basically stands for <thead> as well. The
difference? You don’t have to use <th> tag in combination with any other
table-related tag. However, it is usually used to replace <td> tags individually
to apply a header ”look” to a cell.
Applying it to a table will style the <th> cell as if it was a header. In other
words:
1 <th> t a g w i l l a l i g n t e x t t o t h e c e n t e r
2 <th> t a g makes i t s c o n t e n t b o l d

94
The <td> tag should probably only be used in the context of a header. But
here just to demonstrate its versatility, I applied it to all cells within the first
row, and one cell in the third column on row 3:

Figure 89:

Notice that because our previous CSS was applied only to <td> tags, the font
family in <th> tag as shown in the example above did not inherit Arial font.
It’s still the default Times New Roman.
But that can also be quickly corrected by adding th to previously written CSS:
1 <s t y l e type=” t e x t / c s s ”>
2 t a b l e td ,
3 t a b l e th
4 {
5 f o n t −f a m i l y : A r i a l ;
6 f o n t −s i z e : 12 px ;
7 padding : 4px ;
8 }
9 </ s t y l e>

Remember to insert this CSS block nested somewhere within the <head> tags
in your HTML document or inside <body> tags, in which case you would also
want to add scoped property to style tag. Alternatively, you can remove
the style tags from this example, and simply enter its contents to a separate
”external” CSS file (for example style.css) and include it in your document
using <link href = "style.css"> tag within <head> tags.
Don’t worry if you don’t fully understand CSS syntax yet. We’ll explore CSS
in much greater detail in a future chapter of this book. But it would be
difficult to talk about HTML alone in any depth, without bringing up CSS.
So far, we’re making great progress and we’ll go through those subjects later

95
in the book as we continue putting pieces of the puzzle together to form the
full picture.

8 Chapter VIII - Forms


HTML forms provide an interface for taking user input. Input elements can
manifest themselves as following HTML controls:

• Text Input fields for taking username or any similar text-based inputs.

• Password Input is a field with all letters replaced by star (*) characters.

• Clickable Buttons that provide custom function, for example ”Calcu-


late Result.”

• Check Boxes for creating a single ”Yes” or ”No” choice.

• Radio Buttons for creating a multiple choice selection.

• Usually one Submit Button is created at the bottom of the form for
sending all form data to another HTML page or an external script for
further processing. For example, user-entered data can be sent for per-
manent storage in a database via a script written in another language,
such as PHP or server-side JavaScript.

Note that the HTML form can pass on information entered into it to scripts
written in any language. It’s up to the web developer to implement that part
separately. In this chapter we will only explore creation of the form controls.

8.1 Creating Your First Form


Creating an HTML form is quite simple. And although most forms you will
find today are modified by custom CSS to match the overall theme of the
website, the HTML code is trivial.

96
Forms are collections of input elements enclosed by <form> and </form> tags.
Forms usually have a single submit button that sends all of the form input for
processing to a script page.
1 <form action = ” h t t p : / / example . com/ thankyou . php” method = ”
POST”>
2
3 <p>F i r s t name :</p>
4 <input type = ” t e x t ” name = ” f i r s t ” value = ” ” />
5
6 <p>Last name :</p>
7 <input type = ” t e x t ” name = ” l a s t ” value = ” ” />
8
9 < !−− s u b m i t t h i s form t o ” a c t i o n ” s c r i p t //−−>
10 <input type = ” submit ” value = ” Update Record ” />
11
12 </form>

This form contains two <input> elements and one submit button.
Both input elements contain 3 attributes described below:

• type specifies text input type where ”text” stands for plain text input.

• name is the unique name of this input field.

• value is the default value of this input field (can be empty.)

I intentionally skipped placeholder attribute from the source code for clarity.
But it’s possible that you may want to use it in your own forms.

• placeholder attribute provides a hint value for the form’s viewer that
appears only when text field is empty to provide a clue for what type of
information this text field expects.

And finally, this is what the form we just created would look like in the Chrome
browser:

97
Figure 90: A basic HTML form with just two text inputs and a submit button.

The type attribute of input fields will physically change the appearance of the
control. And beside standard text input, there exist various other elements
that can be used to decorate our form with controls that ask the visitor enter
all kinds of details.
To name just a few, the type can be text, password, radio, checkbox or
submit all of which would create a different type of user input control. In one
of the next section of the book 1.3 Creating Realistic HTML Forms we will
take a look at all possible combinations.
Note that the submit button is created using the <input type = "submit">
tag. Setting its type attribute to "submit" ensures that when the button
is pressed the browser will send form data to the URL specified in action
attribute of the <form> tag itself.
In the case of our example the submit button will alert the browser for the
data to be sent to the imaginary URL at http://example.com/thankyou.php
assuming that thankyou.php script exists at that location.

8.2 Submitting Forms


In our first form example we’ve taken a look at how the action attribute
tells the form to which page the information will be sent. It can refer to a
”Thank You” page, or a similar page where your website lets the user know
that information has been received.
But there is a little more to the process than it seems.

98
8.2.1 What Are HTTP Requests?

Here we need to briefly mention the concept of an HTTP request. Whenever an


HTML page loads into the browser, it is usually a result of an HTTP request.
Whatever you enter into address bar is the location of the URL you wish to
access. The browser sends a request to that location in order to retrieve the
HTML document.
Although the very page that your form is on was initiated by an HTTP request,
the form’s submit button itself will also initiate one, but this time, to the URL
location specified as a value in its action attribute. The difference is that the
form will actually pass data to that page as well, which is different from simply
typing it into your browser’s Address Bar.
Both name and the value pair of each element will be submitted to the target
page as part of the HTTP request.

8.2.2 GET Method

When you specify GET as a value of the method attribute on the <form> tag
, all of the data will be converted to a string, and sent as part of the URL
itself. This way, you can submit the form without even being on the website,
by simply typing the parameters into the URL itself.
GET requests are the simplest ones to understand. We’ll take a look at how
they actually send the information over to a Thank You page in just a moment.
And if your target script specified in action attribute of the form allows it,
it will read that data from the GET array it receives. Arrays are objects that
contain a set of multiple properties.

8.2.3 POST Method

When using POST method, the form does not append data to the URL. In-
stead, values will be hidden and contained within the request’s data payload
itself. It will be visible only to the script page specified in action attribute of
the form by reading it from a POST array.

99
The POST method is recommended as the more secure one for submitting
form data. That’s because it will not be exposed in the address bar as part
of the URL. However, this does not fully prevent data from being intercepted
either.
Simply using a POST method is not enough to create adequate security for
your site. For this reason, when building advanced web applications that
require a reasonable degree of security, you will be usually dealing with some-
thing called OAuth 2.0 and either REST or GraphQL. But these subjects are
way outside of the scope of this book.
Don’t get this wrong, none of this actually prevents us from experimenting
with HTML forms and passing data to a target page! I just wanted to briefly
mention it here, in case you’re interested in further exploring the subject of
web development.

8.3 HTML Form Controls


We’ve briefly taken a look at the logic of HTML forms. In this section, you
will be introduced to an example of an HTML form for inputting various types
of information represented by different HTML controls.
The example in this section can be used as a reference for using most common
HTML input controls, such as text input, radio boxes, drop-down menus and
so on.
Once our form is constructed, we will also verify user input before it’s sub-
mitted to the processing script, written in PHP language. Do not worry if
you don’t know PHP for now, it is a very simple example. This script called
submitted.php will be provided as an example only, to demonstrate how an
HTML page can send user input for further processing by your website or
web application. Advanced PHP scripting is outside the scope of this book,
however. It is recommended that you get a separate book for that!
The HTML source code for creating a basic form from is listed below. Note
that here, HTML is formatted to match the book format for clarity, and
element’s attributes are aligned one under the other. However, in your HTML
document you can format the HTML code in any way you wish.

100
1 <body>
2
3 < !−− Change c u r s o r arrow t o hand p o i n t e r when h o v e r i n g on
l a b e l HTML e l e m e n t s //−−>
4 <s t y l e type=” t e x t / c s s ”>l a b e l { c u r s o r : p o i n t e r ; }</ s t y l e>
5
6 < !−− Begin HTML form by o p e n i n g t h e form t a g //−−>
7 <form action = ” s u b m i t t e d . php” method = ”POST”>
8
9 <b>Enter b a s i c i n f o r m a t i o n :</b><br/>
10
11 <input type = ” hidden ”
12 name = ” s e c r e t t o k e n ”
13 value = ” 75 ” />
14
15 Email Address<br />
16 <input type = ” t e x t ”
17 name = ” e m a i l ”
18 p l a c e h o l d e r = ” Enter your e m a i l a d d r e s s ” /><br />
19
20 F i r s t Name<br />
21 <input type = ” t e x t ”
22 name = ” f i r s t n a m e ”
23 p l a c e h o l d e r = ” Enter your f i r s t name” /><br />
24
25 Last Name<br />
26 <input type = ” t e x t ”
27 name = ” l a s t n a m e ”
28 p l a c e h o l d e r = ” Enter your l a s t name” /><br />
29
30 Age<br />
31 <input type = ”number”
32 name = ” age ”
33 p l a c e h o l d e r = ” Enter your age ” /><br />
34
35 Year o f B i r t h<br />
36 <input type = ”number”
37 name = ” y e a r ”

101
38 p l a c e h o l d e r = ” Enter y e a r o f b i r t h ”
39 min = ” 1997 ”
40 max = ” 2025 ” /><br />
41
42 Password<br />
43 <input type = ” password ”
44 name = ” password ”
45 placeholder = ” Enter your password ” /><br />
46
47 <hr />
48
49 <b>Choose one c a r make :</b><br/>
50
51 <input id = ” a s t o n m a r t i n ”
52 type = ” r a d i o ”
53 name = ” car make ” />
54 <l a b e l f o r = ” a s t o n m a r t i n ”>Aston Martin</ l a b e l>
55 <br/>
56
57 <input id = ” f e r r a r i ”
58 type = ” r a d i o ” name = ” car make ” CHECKED />
59 <l a b e l f o r = ” f e r r a r i ”>F e r r a r i</ l a b e l>
60 <br/>
61
62 <input id = ” p o r s c h e ”
63 type = ” r a d i o ” name = ” car make ” />
64 <l a b e l f o r = ” p o r s c h e ”>Porsche</ l a b e l>
65 <br/>
66
67 <input id = ” c o r v e t t e ”
68 type = ” r a d i o ” name = ” car make ” />
69 <l a b e l f o r = ” c o r v e t t e ”>C o r v e t t e</ l a b e l>
70 <br/>
71
72 <hr />
73
74 <b>S e l e c t a l l t h a t apply :</b><br/>
75

102
76 <input id = ” d r i v i n g ”
77 type = ” checkbox ”
78 name = ” d r i v i n g ” CHECKED />
79 <l a b e l f o r = ” d r i v i n g ” checked>D r i v i n g</ l a b e l>
80 <br/>
81
82 <input id = ” c r a w l i n g ”
83 type = ” checkbox ”
84 name = ” c r a w l i n g ” />
85 <l a b e l f o r = ” c r a w l i n g ”>Crawling</ l a b e l>
86 <br/>
87
88 <input id = ” f l y i n g ”
89 type = ” checkbox ” name = ” f l y i n g ” />
90 <l a b e l f o r = ” f l y i n g ”>F l y i n g</ l a b e l>
91 <br/>
92
93 <input id = ”swimming”
94 type = ” checkbox ” name = ”swimming” />
95 <l a b e l f o r = ”swimming”>Swimming</ l a b e l>
96 <br/>
97
98 <input id = ” d i v i n g ”
99 type = ” checkbox ” name = ” d i v i n g ” />
100 <l a b e l f o r = ” d i v i n g ”>D iv in g</ l a b e l>
101 <br/>
102
103 <hr />
104
105 <b>S e l e c t f a v o r i t e f r u i t :</b><br/>
106
107 <s e l e c t name = ” f a v o r i t e f r u i t ”>
108 <option value = ” a p p l e ”>Apple</ option>
109 <option value = ” o r a n g e ”>Orange</ option>
110 <option value = ” banana ”>Banana</ option>
111 <option value = ” s t r a w b e r r y ”>S t r a w b e r r y</ option>
112 <option value = ” peach ”>Peach</ option>
113 <option value = ” lemon ”>Lemon</ option>

103
114 <option value = ” g r a p e ”>Grape</ option>
115 </ s e l e c t>
116
117 <hr />
118
119 < !−− C l i c k i n g on t h i s ” submit ” button w i l l send form ’ s
data t o s c r i p t s p e c i f i e d by t h e form ’ s action a t t r i b u t e
//−−>
120 <input type = ” submit ” value = ” Submit This Form” />
121
122 < !−− F i n a l l y , we now need t o c l o s e t h e form e l e m e n t //−−>
123 </form>
124
125 </body>

This code will produce the output shown in Figure 10, when viewed in a web
browser.
So what’s going on here? We have created several input elements of different
types. In HTML, you can change the input controls by modifying the value of
the type attribute of an <input> tag.
For example:
1 < !−− Cr e a t e p l a i n text input //−−>
2 <input type = ” t e x t ” />
3
4 < !−− R e p l a c e e n t e r e d l e t t e r s w i t h s t a r ( ∗ ) c h a r a c t e r //−−>
5 <input type = ” password ” />
6
7 < !−− Cr e a t e a c l i c k a b l e c h e c k b o x //−−>
8 <input type = ” checkbox ” />
9
10 < !−− Cr e a t e a r a d i o button option //−−>
11 <input type = ” r a d i o ” />
12
13 < !−− Cr e a t e a h i d d e n value //−−>
14 <input type = ” hidden ” value = ” 1 ” />

These attributes are pretty basic and easy to remember. They will render

104
Figure 91: A form asking to enter visitor’s email address, first and last names,
password and a few options.

different types of clickable HTML elements, determined by the needs of your


form.
Note that the last type of the input type shown here is a ”hidden” value of 1.

8.4 Hidden Form Inputs


Hidden inputs will not visually show up on the form itself. It’s for passing
custom strings of text or numeric values to the form’s target script. The value
is usually determined dynamically by JavaScript. It can contain a secret code,
a token ID of some sorts, or any other custom information that you wish to

105
send via the form, but don’t necessarily require the user to choose or modify
it.

8.5 Radio Buttons


Radio buttons behave in a special way by giving the visitor one choice from
the same group of answers. To give user a chance to select their favorite car
make, for example, you could create a group of choices united by radio button
group name. This name is specified under the ”name” attribute for each radio
button:
1 <input type = ” r a d i o ” name = ” car make ” value = ” Aston
Martin ” />
2 <input type = ” r a d i o ” name = ” car make ” value = ” F e r r a r i ” />
3 <input type = ” r a d i o ” name = ” car make ” value = ” Porsche ” />
4 <input type = ” r a d i o ” name = ” car make ” value = ” C h e v r o l e t ”
/>

This will render just the clickable radio buttons.

8.5.1 Labeling Radio Buttons

You can further decorate them by adding additional text to the right of each
radio button. Usually this text is provided by using an HTML tag created
specifically for this purpose called label:
1 <input type = ” r a d i o ”
2 name = ” car make ”
3 value = ” F e r r a r i ”
4 id = ” f e r r a r i i d ” />
5 <l a b e l fo r = ” f e r r a r i i d ”> C l i c k t o c h o o s e F e r r a r i</ l a b e l>

The label is associated to the id of a radio button by specifying it as a value


in its for attribute. Here, it is ferrari id. Once this link between the label
and the radio button is established, clicking on the label will produce the
same effect as clicking on the radio button itself. Doing this improves user

106
experience when presented with a selection consisting of more than one radio
button.

8.5.2 Determining Default Radio Button

By assigning CHECKED property to a radio button element, HTML will display


it as the default choice once the web page finished loading in your browser.
1 <input type = ” r a d i o ” name = ” car make ” value = ” Aston
Martin ” />
2 <input type = ” radio ”
3 name = ” car make ”
4 value = ” F e r r a r i ” CHECKED />
5 <input type = ” r a d i o ” name = ” car make ” value = ” Porsche ” />
6 <input type = ” r a d i o ” name = ” car make ” value = ” C h e v r o l e t ”
/>

Leaving a selection consisting of several radio buttons without a default checked


value is usually not a good idea.

8.6 Checking Form’s Values Before Submitting Them


So far, we’ve built a very basic HTML form. It doesn’t even check whether
the values that were entered by the user could be considered as acceptable.
Clicking on the update record submit button will send the browser to action
URL and if no data was entered the default values will be used. The form will
be submitted regardless of whether data was entered into the form at all.
The problem? Even blank values may be sent to the server, but this behavior
is usually not intended. For example, the fields could be an email address
required for account creation or a password that still needs to be validated
against a second password field.
In our first example we’ve taken a look at how to send form values to a PHP
script. But there is a catch. Online forms on reputable websites take an extra
step and ensure that the data was entered correctly after the submit button is

107
clicked but before the form is actually sent to the next page. If only we could
intercept the values before they are sent to the ”thank you” PHP script.
This process is also known as Form Validation. In next section an example of
testing for accurately entered usernames, email addresses and passwords will
be provided using HTML5.

8.7 HTML5 Form Validation


Browser form validation didn’t exist out of the box until HTML5. And you had
to provide your own JavaScript solution which often meant writing between
50-100 lines of code or more.
Today, just about any common browser supports it via HTML5. To enable it
on your form’s input elements, all we have to do is add the HTML5 require
property to the fields we want to validate.
Let’s create an HTML5 form where all four fields are required to be validated:
1 <form action=” / u s e r s / s i g n u p ” method=” p o s t ”>
2 <l a b e l f o r=” username ”>Username</ l a b e l>
3 <input id=” username ” type=” t e x t ” r e q u i r e d>
4 <br/>
5 <l a b e l f o r=” e m a i l ”>Email</ l a b e l>
6 <input id=” e m a i l ” type=” e m a i l ” r e q u i r e d>
7 <br/>
8 <l a b e l f o r=” password ”>Password</ l a b e l>
9 <input id=” password ” type=” password ” r e q u i r e d>
10 <br/>
11 <l a b e l f o r=” password2 ”>Repeat Password</ l a b e l>
12 <input id=” password2 ” type=” password ” r e q u i r e d>
13 <br/>
14 <input type=” submit ” value=” Submit ”>
15 </form>

That’s it!
Just an aesthetic add on: to make sure all labels are the same width, let’s
write this CSS to force a width of 125 pixels on all label tags from the

108
HTML example above:
1 l a b e l { d i s p l a y : i n l i n e −b l o c k ; width : 125 px }

The result is this form:

Figure 92: A basic HTML5 form with 4 required fields.

And when you try clicking submit button on this empty form, built-in HTML5
validator will produce this message on the first field:

Figure 93: Clicking Submit produces a warning. Username cannot be blank,


form is not submitted until this is fixed.

The same goes for all other four fields.


HTML5 can even tell the difference between a username and email address:

109
Figure 94: Email address was entered in incorrect format. The HTML5 form’s
input field with required property knows to test for email address because
attribute type is set to the value of email.

The email address requires at least one @ character. HTML5 form will trigger
this warning message on empty text input fields with type = "email".
We can take form validation with HTML5 a step further by specifying an exact
pattern the user is expected to match.
These patterns are created using yet another language called Regular Expres-
sions. Unlike JavaScript that helps us write entire programs, Regular Expres-
sions match patterns.

8.7.1 Regular Expression Patterns

In addition to standard form validation in HTML5 we are able to fine tune


how we want to validate each input field based on a pattern.
Traditionally a password must contain only alpha-numeric values, a telephone
number must be limited to a number of characters and not contain text... and
an email address must contain the ”at” character (@).
To verify these requirements a web developer usually writes an additional script
in JavaScript language using a built-in object called RegEx. But in HTML5,
this functionality is provided out of the box using the pattern attribute.
Let’s cover a few examples here. This gives us full control over exactly how
we want to validate our input fields.

110
8.7.2 First and Last Names

You might think this one is easy. All we have to do is check for A through z
characters. But upon a closer examination, names come in a variety of formats.
And what about those double-barrelled names? The ones that contain a dash?
Let’s take a look:
1 C l a r e O’ Connor
2 Martin Luther King , Jr .
3 Mathias d ’ Arras
4 John−Paul
5 Anne−Marie

This regular expression pattern (that should be provided as the value of the
pattern attribute on any text input field you wish to validate as a first or last
name) will pass most common cases:
1 / ˆ [ a−z ,. ’ −]+\ $ / i

HTML5 field Example for matching first and last names:


1 F i r s t name :<br/>
2 <input type = ” t e x t ”
3 id = ” f i r s t n a m e ”
4 type = ” f i r s t n a m e ”
5 p a t t e r n = ” / ˆ [ a−z ,. ’ −]+\ $ / i ” r e q u i r e d />
6
7 Last name :<br/>
8 <input type = ” t e x t ”
9 id = ” l a s t n a m e ”
10 type = ” l a s t n a m e ”
11 p a t t e r n = ” / ˆ [ a−z ,. ’ −]+\ $ / i ” r e q u i r e d />

8.7.3 Usernames

Usernames are usually alpha-numeric values that can also contain dots and
underscores. In this example we also added the dash (-) to the valid character
set:

111
1 / ˆ [A−z0 −9.− ]+$ / i

HTML5 field Example for matching usernames:


1 Username :<br/>
2 <input type = ” t e x t ”
3 id = ” username ”
4 type = ” username ”
5 p a t t e r n = ” / ˆ [A−z0 −9.− ]+$ / i ” r e q u i r e d />

8.7.4 Email Address

Email addresses are some of the most complex regular expression patterns we
must test against when it comes to form validation. It is possible to create
a pattern that matches most email addresses, but discards some of the less
common (yet, completely valid ) emails.
If you want to be complete by matching any email address in existence with
100% accuracy the following Regular Expression provides a means for validat-
ing a fully RFC 822 compliant regular expression.
1 ( ? : [ a−z0 −9!#$%&’∗+/=?ˆ ‘ { | } ˜ − ] + ( ? : \ . [ a−z0 −9!#$%&’∗+/=?ˆ
‘ { | } ˜ − ] + ) ∗ | ” ( ? : [ \ x01−\x08 \ x0b \ x0c \ x0e −\x 1 f \ x21 \ x23−\x5b \
x5d−\x 7 f ] | \ \ [ \ x01−\x09 \ x0b \ x0c \ x0e −\x 7 f ] ) ∗ ” )@ ( ? : ( ? : [ a−z0
− 9 ] ( ? : [ a−z0 −9 −]∗[a−z0 −9]) ? \ . ) +[a−z0 − 9 ] ( ? : [ a−z0 −9 −]∗[a−z0
−9]) ? | \ [ ( ? : ( ? : ( 2 ( 5 [ 0 − 5 ] | [ 0 − 4 ] [ 0 − 9 ] )
|1[0 −9][0 −9]|[1 −9]?[0 −9]) ) \.) {3}(?:(2(5[0 −5]|[0 −4][0 −9])
| 1 [ 0 − 9 ] [ 0 − 9 ] | [ 1 − 9 ] ? [ 0 − 9 ] ) | [ a−z0 −9 −]∗[a−z0 − 9 ] : ( ? : [ \ x01−\
x08 \ x0b \ x0c \ x0e −\x 1 f \ x21−\x5a \ x53−\x 7 f ] | \ \ [ \ x01−\x09 \ x0b \
x0c \ x0e −\x 7 f ] ) +) \ ] )

Luckily for us, not only do you not have to use this dinosauruc pattern – you
don’t need to.
It’s good to keep email validation simple. Just check for presence of @ sign,
and a dot:
1 /ˆ\S+@\S+\.\S+$ /

112
Although this regular expression might pass a few odd cases that are not
considered valid email addresses, it is simple and gets the job done for the
most part.
HTML5 field Example for matching email addresses:
1 Email a d d r e s s :<br/>
2 <input type = ” e m a i l ”
3 id = ” e m a i l ”
4 type = ” e m a i l ”
5 p a t t e r n = ” /ˆ\S+@\S+\.\S+$ / ” r e q u i r e d />

8.7.5 Password

Password validation will depend on what you, as the site owner, wish the
password patterns to match. Below are listed a few different cases testing for
different required conditions of a password string.
The string must contain at least 1 lowercase alphabetical character:
1 ( ? = . ∗ [ a−z ] )

The string must contain at least 1 uppercase alphabetical character:


1 ( ? = . ∗ [A−Z ] )

The string must contain at least 1 numeric character:


1 (?=.∗[0 −9])

The string must be eight characters or longer:


1 (?=.{8 ,})

You can also combine them into one Regular Expression.


And finally... our password validation pattern could look this way:
1 Username :<br/>
2 <input type = ” password ”
3 id = ” password ”
4 type = ” password ”

113
5 p a t t e r n = ” ˆ ( ? = . ∗ [A−Za−z ] ) (?=.∗\ d ) [ A−Za−z \d ] { 8 , } $ ”
r e q u i r e d />

8.7.6 Phone Numbers

Here is a regular expression that will validate most cases:


1 ˆ(\+\d { 1 , 2 } \ s ) ? \ ( ? \ d { 3 } \ ) ? [ \ s . −]\ d { 3 } [ \ s . −]\ d{4} $

It matches the following numbers:


1 123−456−7890
2 ( 1 2 3 ) 456 −7890
3 123 456 7890
4 123.456.7890
5 +91 ( 1 2 3 ) 456 −7890

And our HTML5 would be:


1 Phone number :<br/>
2 <input type = ” t e x t ”
3 id = ” phone ”
4 type = ” phone ”
5 p a t t e r n = ” ˆ(\+\d { 1 , 2 } \ s ) ? \ ( ? \ d { 3 } \ ) ? [ \ s . −]\ d { 3 } [ \ s . −]\ d
{4} $ ” r e q u i r e d />

Regular Expressions are helpful for matching text patterns. But there is no
way we can possibly cover the entire scope of Regular Expressions in this book.
If you are interested in exploring them further, here is a diagram that provides
some very basic examples.

114
8.7.7 Regular Expressions

Figure 95: Regular Expression examples.

115
8.8 Clicking The Submit Button
Our HTML5 form is completed and validated, given user provides some sort
of input. But what do we do with the data entered into it?
Forms send the data to another, usually separate script file. That script file
can be a ”Thank You” page, or some type of confirmation letting the user
know that the information has been received.
This file needs to be created separately in your project. Let’s just say that for
this example, we will create a fresh file and call it submitted.php.
Although server-side PHP language is beyond the scope of this book, it is one
of the simplest choices made by beginner web developers for solving slightly
more advanced programming problems (Because PHP language runs on the
server, and not in your browser, it is often used to upload images, work with
application data, and processing form input.) Note that for the stated rea-
son, PHP requires some additional set up to work properly locally on your
computer.
In other words, it will not work out of the box in your browser (like HTML
does,) unless you install Apache server with PHP on your computer first.
However, web hosting servers (companies that provide ability to serve your
website from a www. location,) have PHP already set up out of the box. If
you are eager to start experimenting with more advanced subjects and don’t
have the time to install Apache on your computer, I recommend getting a web
hosting account.
If you’re looking to grow in your career as a Web Developer, it is strongly
recommended to spend some time learning how to set up a web server to
run locally on your PC (or Mac) as this will come up a lot in the future
when you move on to advanced web application development. In professional
environment if you ever find yourself hired by a software company, this is not
only required knowledge but expected as second-nature.
We’ve chosen PHP as the language for processing our HTML form’s submit
action. But what does this PHP language look like? Here is a short piece
of PHP code (the part of an HTML document wrapped between <?php ?>
brackets,) that will in fact take the input from our form and display the values

116
that the user entered.
Note also that this script is the one we specified as a value of the action
attribute in the HTML form: <form action = "submitted.php"> we created
earlier. This is important. The submit button automatically sends the entered
form data to this script.
The listing of the script written in PHP language submitted.php is saved in
the same folder together with your index.html file and it contains only four
lines of code.
1 <html>
2 <head><t i t l e>Submitted Form</ t i t l e> </head>
3 <pre><?php p r i n t r ($ REQUEST) ; ?></pre>
4 </html>

A PHP script can actually be an HTML document! The PHP itself is only
embedded into it using PHP brackets. However, nothing is stopping a PHP
script from containing only PHP. In fact, some PHP scripts can potentially
generate and print HTML tags. For example, when you need content of your
HTML page to be dynamically generated.
The difference is that instead of using .html file extension, you should save
your PHP files using the .php file extension. Web servers are usually configured
to automatically process .php files as PHP scripts. If that isn’t the case, PHP
code between <?php ?> brackets will be rendered as plain text and no PHP
code will actually be executed. Properly setting up a PHP server fixes that
problem.
When the submit button is clicked, we are sent to this page. This simple PHP
script uses a PHP command print r, which in turn prints out the received
form data as an object of type Array. Again, you will need to brush up on
your PHP scripting in order to fully understand this. But basically, in this
case an Array is a collection of property names and values.
The built-in PHP array called $ REQUEST will contain form data. Remember
how earlier we mentioned that HTML forms send data via something called
HTTP requests? That’s the purpose of the $ REQUEST array. To receive form
data. Once the button is clicked, the output of this PHP script is as follows:
1 Array

117
2 (
3 [ s e c r e t t o k e n ] => 75
4 [ e m a i l ] => r o b e r t . smith@gmail . com
5 [ f i r s t n a m e ] => Robert
6 [ l as t na m e ] => Smith
7 [ age ] => 24
8 [ y e a r ] => 1997
9 [ password ] => MyOrangeCat175 !
10 [ car make ] => on
11 [ d r i v i n g ] => on
12 [ f a v o r i t e f r u i t ] => o r a n g e
13 )

Notice how our HTML form converted the received values from HTML controls
into a neatly organized list that is easy to read. We can now access each value
individually from PHP or send it back to JavaScript. What you will do with
entered information is up to you.
Note that from the script’s point of view, the values entered into password
field are no longer blocked by stars. Of course, this is because the server can
actually see all received values.
Normally, email and password combinations are used to create log in forms.
The PHP script receives the email and password values entered by the visitor.
Then the email and password are matched with values in the database on your
web server, just to check if that user exists. If entered email and password
pair match, the user can be considered logged into your website. If you are
interested in learning to build this type of functionality for your own websites,
I again recommend picking up a PHP book. You can also create similar func-
tionality with server-side JavaScript and libraries such as React.js, Angular.js
or Vue.js.
Because we wrapped PHP script with HTML tags <pre>, the array is neatly
formatted by line breaks, forming a readable one column of names associated
to entered values on the submitted form. Had that not been the case, you
would see something like this in the browser:
1 Array ( [ s e c r e t t o k e n ] => 75 [ e m a i l ] => r o b e r t . smith@gmail .
com [ f i r s t n a m e ] => Robert [ l a s t n a m e ] => Smith [ age ] => 24
[ y e a r ] => 1997 [ password ] => MyOrangeCat175 ! [ car make ]

118
=> on [ d r i v i n g ] => on [ f a v o r i t e f r u i t ] => o r a n g e )

It looks a bit more garbled and less readable. But that’s just the result of the
output produced by the PHP function print r.
It is not uncommon for input in Array format (a list of name and values,
also often separated by commas) to be sent and received back and forth be-
tween the server and the front-end of your applications developed in HTML
and JavaScript. In fact, a special format in JavaScript exists called JSON
(JavaScript Object Notation) to help web developers deal with lists of prop-
erties.
Forms can represent user sign up boxes, newsletter subscriptions, places where
financial information such as credit cards and so on can be entered. What you
will do with received data will depend primarily on the purpose of your website
or application.
Many online newsletter websites such as Mailchimp and Constant Contact
provide HTML and JavaScript code you can simply embed directly into your
website. They will take care the server-side part and provide you with a list
of email addresses that subscribed to your form. But nothing is stopping you
from continuing to explore server-side programming on your own.

8.9 Using Custom Images To Replace Submit Button


If you’ve ever installed a PayPal donation or payment button on your website,
you have installed an HTML form. You may have wondered how the PayPal
flavor of HTML form makes their orange buttons appear on the page, instead
of the generic gray (or transparent on Mac operating systems) HTML button:

Figure 96: Custom PayPal HTML form button. How was it made?

119
When you specify type of an input element as image then HTML will interpret
it as a submit button. But additionally, it will look for the actual image you
wish to use as the submit button! Image must be specified as URL using sec-
ondary src (or alternatively, source) attribute as in <input type = "image"
src = "my-image.png" />. Here is an example of what it would look like in
HTML source code:
1 <form>
2 < !−− c r e a t e s e v e r a l input e l e m e n t s h e r e . . . //−−>
3 <input type = ” t e x t ” /> < !−− e t c . //−−>
4
5 < !−− Within <form> e l e m e n t s , input o f type ” image ” w i l l
6 a u t o m a t i c a l l y f u n c t i o n l i k e a s u b m i t button //−−>
7 <input type = ” image ” src = ”my−submit−button . png” />
8 </form>

In this case my-submit-button.png is the filename of the custom image that


replaces the submit button in your form. And even though theoretically this
should work, it can probably be considered a slightly outdated way of styling
a submit button.
In modern web development, the style of a submit button is usually specified
using external CSS and not an input element of type ”image”. That attribute
is a relic from the old days, before CSS had the capacity to change the look
and feel of a form button.
I don’t want to spend time talking about features that are slowly becoming
deprecated in HTML. But I wanted to mention type=image submit buttons
as one of the many examples where outdated features still work in modern
browsers. The lesson here is, just because something works, it doesn’t mean
that it should be used, if you wish to follow modern development standards.
And there are quite a few of these features!
When we get to later chapters of the book, you will see that CSS is the ideal
way of styling all of your HTML elements. HTML provides only the structure
of your layout.

120
9 Chapter IX: Thinking In Pixels

9.1 Position and Size of HTML Elements


We covered several types of HTML elements and what they appear like in
the browser when you hit refresh. But HTML also gives us control over the
position and size of elements on the screen.
Up until this point in the book we thought of HTML element positioning as
arbitrary. In order to get a good grasp on controlling our element’s position
and size with a lot more precision we need to start thinking in pixels.
Having control over position of an element provides flexibility. They allow for
more freedom of expression when it comes to website style. Because HTML is
closely related to graphic design, when positioning your elements you will be
asking questions like: ”Should this element be located 4 or 8 pixels away from
the left side of the screen?” or ”How does increasing height of a button by 5
pixels contributes to overall look & feel of my layout?”

9.2 What Are Pixels?


A pixel is the single unit of space used for measuring distance between text
and other HTML elements. Getting close enough to the computer screen you’ll
notice that pretty much everything you are seeing on it is constructed from
tiny squares. Each one of those square boxes is a pixel.
A pixel is simply the tiniest square dot on the screen! Pixels also have a color
value created from three channels: Red, Green and Blue. HTML allows us to
set color to any element using hexadecimal numbering system. We’ll take a
look at color shortly. For now just know that pixels can be located at a precise
position on the screen.
Let’s demonstrate how if we zoom in close enough, we can see that letters are
actually made up of pixels.
Thinking about HTML elements on this microscopic level is important because
User Interface wire-frames created by graphic designers are usually to be fol-
lowed with ”pixel-perfect” precision. And who can blame them? Hallmark of

121
Figure 97: Zooming in on text displayed in your HTML document reveals that
text and other HTML elements actually consist of pixels.

good design is caring about every pixel on the screen.

9.3 Position
In the context of creating websites you will be often dealing with pixels to set
location and size of HTML elements.

Figure 98: An area with dimensions of 10 x 5 and a 8 x 3 box inside, measured


in pixels.

122
Website layouts are constructed to adapt to a large variety of devices. For
example a standard monitor can go up to 1920 x 1080 to fill the entire screen.
One of the latest Amazon Kindle Fire devices spans across 1200 x 1920 and
an Apple iPad Pro can reach up to 2048 x 2732 screen resolution in pixels. A
4K monitor has a resolution of 4096 x 2304.
Your website or web application will deal with smaller resolutions. This is
because your website is assumed to appear within the boundaries of a browser
which can be resized by the user.
In addition, traditional website layouts are often ”centered” vertically on the
screen and consist of multiple, smaller blocks making up the entire layout.
This avoids situations where your website is viewed on a very large screen. If
its layout is set to 100% of the screen’s width, its design may disintegrate and
no longer appear natural.

9.4 Hierarchies of Coordinate Systems


All HTML elements we create are usually located somewhere within other
elements.
This means that each HTML element contains its own local coordinate system.
For example, if you wish to position a child element within a parent element
already located somewhere in your HTML document, the child will inherit
parent’s coordinate system which takes origin in the upper left corner of the
parent element.
This can be further demonstrated by this minimalistic diagram shown in Figure
9. Note that upper left corner is at 0 x 0, not 1 x 1.
When designing your own HTML layouts you will often start with thinking
about the upper left corner of an element first. You can calculate the position
of any child element within it with pixel-precision using this corner as a starting
point. This is why it’s often referred to as element’s relative position.
Elements within other elements inherit relative positioning to one another by
default.
If you need a certain element to appear at a precise location within another

123
Figure 99: Arrange elements on the screen any way you wish. The sky is the
limit.

element you will change position property from its default value of relative
to absolute and provide pixel location using two additional CSS properties
top and left. If neither top nor left values are provided position:absolute;
will be ignored by HTML.
In CSS the upper left corner is defined as {left:0px; right:0px}. You can
further reduce it to {left:0; right:0;}. Note, however, you are required to
append px to non-0 positioning and size values, whereas {left:32;} is illegal
and {left:32px;} should be used instead. But {left:0;} is acceptable.
This is only because px unit – while the most common – is not the only way
to specify size or position of an element. When it comes to font size, it can
also be specified in em units instead of px.

Originally, em in typography stood for the width of the capital letter M.

124
This was true for traditional printing before the Internet. This is because M
was the type of a character that could fit into a square box. These so called
em-quads or mutton-quads were used by the first printing press. Johann
Gutenberg holds the distinction of being the inventor of the movable-type
printing press. In 1455, Gutenberg produced what is considered to be the
first book ever printed: a Latin language Bible, printed in Mainz, Germany.
A town that by incident also starts with letter M!

As far as HTML is concerned, an em is a single unit equal to the currently


specified point size. Therefore if font-size of the document is 12pt, then 1em is
equal 12pt. Size specified in em units is scalable. If current point size is 12pt
then 2em would equal 24pt. Likewise, a fractional .5em would equal 6pt.

9.5 Position & Display Properties


Using intuitive diagrams below we’ll quickly go over CSS properties position
and display which give us ability to modify element’s default behavior.
We’ll start with simple text spans, but by modifying these properties on just
about any other element will produce the same or similar behavior.

9.6 Text Spans


The examples below demonstrate basic idea behind how HTML thinks of rel-
ative positioning of simple elements. Since we know that <body> is a required
tag in any HTML document, we will assume that elements in these examples
are nested within it (or a similar parent element, such as <div>, etc).
That makes it easy to see that every element will be placed within another
element, usually referred to as its parent. The element itself then becomes its
child.
To demonstrate default text position behavior, we’ll assume that most ex-
amples will be based around some text entered between <span>here<span>
tags.

125
The example on the left is this simple HTML. Note that HTML automatically
calculates width of text spans, depending on length of text.
1 <body>
2 <span>h e l l o</span>
3 </body>

Example to the right was generated using following code:


1 <body>
2 <span>h e l l o</span> <span>t h e r e</span>
3 </body>

Here we’ve used <span> tags only as an example, but they’re great for mod-
ifying appearance of words or phrases that go beyond italic or bold text that
can be imitated with <b> and <i> tags. For example, you can highlight a sin-
gle word or a phrase within a sentence by applying CSS via element’s style
attribute:
1 <body>
2 ”The o n l y <span s t y l e = ” background : b l a c k ; c o l o r : w h i t e
; ”>d i f f e r e n c e </span> between me and a madman i s t h a t
I ’m not mad . ” − S a l v a d o r D a l i (1904 −1989)
3 </body>

This HTML code will produce the output shown in Figure 11.
Here, we’ve changed the background color of the word difference to black and
set its font color to white.

126
Figure 100: A quote by Salvador Dali, spanish Surrealist painter.

9.7 Default CSS Properties


Remember that all HTML tags have default CSS style settings even if none
are provided by you. By default the <span>’s CSS property display is set
to value of: inline. This is why no matter how many span tags there are,
they will always appear inline or in other words in ”one immediately after the
other ” order producing a continuous string of text.
But this default behavior can be modified. And although isolated cases like
this one may not make a lot of sense right now, the situation in which chang-
ing default properties of an element becomes useful is based on the specific
behavior you’re trying to achieve when designing your own layouts.

9.8 From Inline to Block


Let’s set the display property of the <span> tag to block and see how it
affects the element.

Figure 101: Changing a display property of a text span from ”inline” to


”block”.

127
Overriding display:inline with display:block has extended the element’s
width all the way down to the right margin of the parent element!
In other words, this means that this element will ”block” all other elements to
its right, effectively ”bumping” them down underneath it.
Moreover, any elements that follow with display:inline (or any other display
property, for that matter) will now appear just below the blocking element.

9.9 Top, left, bottom, right


In addition to top and left properties, elements with {position:absolute}
may also specify their position using bottom and right properties. You might
already guess what they do. Let’s take a look at this drawing to demonstrate
it.

Figure 102: The innermost child is positioned at the right bottom corner using
bottom and right properties. These values can also be negative! Which, in
this case would push the innermost child outside its parent.

The property top cannot be used together with property bottom. Likewise,
left cannot be used with right at the same time.
Another lesson learned here is that some relative elements will appear within
absolute elements, and the other way around. But there is one HTML rule that
might throw you off guard at first. If an absolute element is specified within an

128
element whose display type is missing or unset, then the child element within
it that has absolute position will be relative to the upper left corner of the
screen itself (or the root element in the whole parental hierarchy) and not its
direct parent!
For this reason to maintain good control over where you wish your elements to
appear, always remember to specify display as either relative or absolute.
In fact sometimes the CSS star directive is used to set relative position to all
elements on the screen * {display:relative;}.
We’re slowly moving toward elements using absolute positioning. While we’re
on the subject let’s take a look at one more example where we will specify both
position and size of an element and see how it sometimes affects its children
elements.

9.10 HTML Element Size


Size of elements is determined by CSS properties width and height. It’s really
that simple. Just add them to CSS describing your element:
1 <body>
2 <div s t y l e = ’ p o s i t i o n : a b s o l u t e ;
3 top : 24 px ;
4 l e f t : 32 px ;
5 width : 100 px ;
6 height : 46 px ;
7 border : 1px s o l i d b l a c k ; ’>
8 Determine element ’ s width and h e i g h t .
9 </ div>
10 </body>

This example will produce a <div> element with width=100 and height=50.
Additionally there is a 1px solid line border in gray color, just to visualize the
new size of the element:
Notice that in this case the text does not fully fit into the box. If the con-
tainer is too small for the text, it will leap outside of its bounds. It’s your
responsibility as a designer to make sure this doesn’t happen.

129
Figure 103: CSS is unforgiving when text area is greater than that of its parent
element.

But what if it is your intention to hide overlapping text within a given element?
No problem. CSS offers a special property overflow to handle this case. Let’s
apply overflow:hidden to this example to see what happens:
1 <body>
2 <div s t y l e = ’ p o s i t i o n : a b s o l u t e ;
3 top : 24 px ;
4 l e f t : 32 px ;
5 width : 100 px ;
6 height : 46 px ;
7 border : 1px s o l i d b l a c k ;
8 o v e r f l o w : hidden ’>
9 Determine element ’ s width and h e i g h t .
10 </ div>
11 </body>

With overflow:hidden, the text now cuts off at the element’s bounding box:

130
Figure 104: By using overflow:hidden CSS property we have effectively re-
stricted children from visually escaping the bounding box of the parent ele-
ment. This works with other HTML elements as well, not just text.

9.11 Margin, Padding and Borders


We’ve explored position and size of HTML elements. But there are many more
default properties to each one of them. Together they help us gain even more
control over their appearance and style.
For example properties padding, margin and border can significantly modify
visual appearance of an HTML element.
The diagram in Figure 18. explores relationship between the element’s size
and other properties. You can see here that the element itself can occupy a
relatively small area, compared to the area taken up by its padding or margin.
In typography using white space around text can help its readability. Using
these properties can help you make elements containing text more readable
and pleasing to the eye.

131
Figure 105: When present, CSS properties margin, borders and padding
can make the actual width and height of the element larger than the values
specified using the width and height for that element.

9.11.1 Changing Properties For Individual Sides of Elements

CSS properties margin, border and padding can be specified for each indi-
vidual side separately. For example, to add a border only to the left side of
the element, the property border-left can be used as follows:
1 <div s t y l e = ’ border− l e f t : 1px s o l i d b l a c k ; ’>Message</ div>

Similarly, you can apply the border to any other side of the element individu-
ally:
With time this can get tedious. So an alternative way of specifying border
style to an element was created. You can specify border on any side of the
element with just one command. The format is simple:
b o r d e r : top r i g h t bottom l e f t ;

Where top, right, bottom and left is the border thickness in pixels.
But this shorthand format requires that border style and color are specified
separately. If this step is skipped this shorthand will not work. So our CSS
therefore is:

132
Figure 106: Applying border to any side of the element.

border −c o l o r : b l a c k ;
border −s t y l e : s o l i d ;
b o r d e r : 1px 1px 0 0

Finally, HTML code above will produce the following outcome:

Figure 107: Shorthand format for borders on two sides of an element at the
same time.

Just to be complete, here is how you can set up borders on either top and
bottom or left and right sides of an element:

Figure 108: Setting borders on both sides of the element.

Likewise, to set margin or padding to 10px only on the left side of an ele-
ment you can use shorthands margin:0 0 0 10px and padding:0 0 0 10px
properties respectively.

133
Figure 109: Display borders only on top and bottom sides of the element.

You can also set these values with padding-left:10px or margin-left:10px.

10 Chapter X: Text Behavior


In HTML element position is determined by default properties of an HTML
tag. For example, a span tag is treated as text, therefore it inherits inline
behavior. A div tag is treated is a ”blocking” element and is assumed to
behave as an element whose display property is set to block.
Images are treated as inline and blocking at the same time (inline-block ). It
takes some time to play around with all of the CSS properties to learn how
default values affect behavior of various elements and what happens when you
override them with your own.
Iteratively – over a long period of time – you will develop awareness of these
special sets of rules that govern element position in HTML. Inevitably, you
will also develop your own style of writing HTML and CSS.
Because writing HTML code and layout design are just two different sides
of the same coin, many web designers learn about these rules intuitively, by
interacting with their own code in the browser.
To accurately visualize what happens in each case, we will add a border around
each element, which normally wouldn’t appear there. This will give us an
idea of how default CSS properties affect element’s behavior, dimensions and
placement within a parent element.

134
Figure 110:

10.1 inline

Figure 111: Default inline behavior (set as display: inline) interprets ele-
ments as text. This means that content placed within a series of inline elements
will begin at the place where the previous inline element ends.

The span element is automatically assumed to behave as an inline element.


But setting display: inline to any HTML element will convert it to this
form.

135
10.2 block

Figure 112: When working with display: block it is assumed that the
element’s width will stretch horizontally across the entire width of its parent
element. In other words, blocking elements will ”block” an entire row of space,
in contrast to inline elements that abruptly end at the width of the inner
content.

Setting width of a blocking element’s to something less than its parent’s width
will continue blocking the rest of the row anyway:

Figure 113: Setting smaller width to blocking elements doesn’t modify its
blocking behavior. This introduces the concept of separation between ele-
ment’s behavior and its content area.

136
10.3 inline-block
If you need both inline and blocking behavior inline-block can be used.
Assuming a number of square div elements, following result can be achieved:

Figure 114: display: inline-block; is like inline, except it allows you to


specify element size.

Figure 115: Two elements side by side with display: block and width:
50%

The same two elements but now with display: inline-block:

Figure 116: display: inline-block and width: 50%

137
However, centering text within an inline element is impossible. Changing the
sample above to display: inline will treat each element as span of text
again:

Figure 117: Text inside two span elements is always inline by default and it
makes no sense centering it.

In this chapter we’ve taken a look at basic text behavior within inline, block
and inline-block elements.
Once you get a good grasp on how that works, you’ll be ready for moving on
to slightly more advanced techniques of arranging elements on your HTML
page. They will be visualized in the next chapter.

11 Chapter XII: HTML Elements – Common


Properties
Every HTML element, blocking or inline has structural composition that may
not be obvious at first – because all properties that deal with size are set to 0
by default.

11.0.1 Anatomy of HTML Elements

In reality, an HTML element consists of content area, padding, a border and a


margin.

138
Figure 118: HTML Element Anatomy – structural composition of an HTML
element.

Note that the X and Y location of an element (determined by top and left
CSS properties) refers to the upper left corner of the content area when
padding, border and margin are set to 0.
Changing padding, border or margin to something greater than its default
value of 0 will not automatically change neither its location nor its dimensions
(top and left, width and height values of the element.) even though the
element will noticeably be located at a different location on the screen.
How can we then determine the actual width and height of the element in these
cases? You can use JavaScript library such as jQuery that provides methods
that calculate these values for you. But this is outside of the scope of this
book.
Increasing padding value to the element will increase its blocking width, but
not the width of its content area. So at times it’s difficult to determine as to
what should be the element’s actual width.

139
Figure 119:

However, you can retain the padding and suppress this from happening by
setting your element’s box-sizing property to a value of border-box:

140
Figure 120: box-sizing: border-box;
Notice that the padding now occupies the inner area of the element. Now
width and height of the element are their original values, and the content is
still padded within the element.

Another common thing to do to HTML elements is to max out their rounded


corners properties to create a circle using border-radius property:

Figure 121: border-radius: 500px; (or set it to actual width of the square
element)

141
To expand on the previous example, a shadow can be added to create an even
more dramatic effect:

Figure 122: box-shadow: 0 0 10px #0000

The values of the box-shadow property are explained below:

Figure 123: Four values supplied to box-shadow property separated by space.


Here color black (hexadecimal #000 ) is used to provide the base shadow color.

These techniques are often used for decorating HTML buttons:

Figure 124: Rounded corners and a shadow used to create a Subscribe button
with centered text.

Box shadow can be used in creative ways to add double (or even triple) border
effect.

142
We’ve taken a look at stacking multiple backgrounds earlier in the book. In
the same exact way, providing multiple values to the box-shadow property, it
is possible to create multiple borders.
Although doing it this way does not guarantee 100% browser support, since
this is literally a hack, and not standard implementation, it’s still good to
know that this ability exists:

Figure 125: Multiple borders can be used by ”hacking” the box-shadow prop-
erty. Provide each shadow value separated by comma.

In this example the three elements are set to inline-block. But in reality,
visibility property is independent of the element’s display type. The idea is
the same – retain the placement of an element but don’t draw it.
Thus far we covered a few interesting modifications that can be applied to
styling HTML elements. In the next chapter we’ll take an even closer look by
shifting focus to positioning elements on the screen.

143
11.0.2 Visibility

Visibility of an HTML element is controlled by visibility property.


Possible values are visible (default) and hidden.

Figure 126: Left: Three elements with visibility:visible (default).


Right: The same three elements, with element b’s visibility set to hidden.

Setting visibility property to hidden doesn’t actually remove the element from
the document. The browser simply skips drawing it. But structurally, it is
still part of the document:

144
11.0.3 Positioning

It is very common to want to position an element exactly at the middle of the


screen. This technique is often used to create the main container for the entire
website. It’s convenient because even if the browser is resized, the element
remains automatically aligned to the center.
One way of accomplishing that would be to simply add automatic margins to
an HTML element whose display property is set to block:

Figure 127: display: block; margin: auto; width: 500px;

To place an element at an exact location, relative to its parent element position:


absolute property can be used. It also requires supplying display: block
and the actual placement in pixels using top and left properties:

145
Figure 128: display:block; position:absolute; top:85px;
left:100px; width:500px; height:200px;

One of my favorite features of CSS when it comes to absolute positioning of


elements is the ability to define the origin of location, based on any of the four
corners of an element.
This is useful when you want to create a placeholder for pop-up notification
messages that can potentially appear in any corner of the screen:

Figure 129: You can use left, right, top and bottom properties to change
origin of location. But you cannot use left together with right, or top
together with bottom on the same element... for obvious reasons.

146
Figure 130: Absolute position applied to HTML elements containing text.

To fix your element on the screen relative to the browser view (regardless if
the horizontal scroll bar changes location) is often used for creating ”overlay”
effect. The idea behind it is simple:

Figure 131: display:block; position:fixed; top:16px; left:16px;


width:50%; height:100%;

Elements ”fixed” to the screen can be used to ”gray out” the background when
you need to display a custom modal dialog box as depicted on the following
diagram:

147
Figure 132: When you post a tweet, the background is shaded out by a full
screen element with 50% opacity. The primary user interface controls are then
displayed on top of that layer.

11.0.4 Floating Elements

Elements that use relative and absolute position are great for making our life
easier when creating various layouts. But there comes a time when you need to
”float” an element to make room for other content. Floating elements usually
shift to either left or right side, opening up more room for elements specified
right after them in your HTML code.

Figure 133: Two elements with float:left behave similar to standard inline
text. Another element with float:right was added here to demonstrate
that content doesn’t have to leave the same horizontal area, at the expense of
creating a gap if the combined width of all floating elements is shorter than
the parent.

Here you have to make a fair judgment based on your layout, as to how you
want to handle floating elements. As you will see from the following example,
when both floating element’s widths combined are greater than the width of
their parent container, the second element inherits block-like behavior:

148
Figure 134: Floating can sometimes be blocking.

But what if you wanted to push a floating element that was set to float in
the same direction, onto the next line? You can use clear:both directive to
accomplish that:

Figure 135: Clearing floating content with clear:both.

11.1 Element Modifications


11.1.1 Rounded Corners

Figure 136: Round corners in a nutshell.

149
Rounded corners are used to create buttons:

Figure 137: Buttons with rounded corners.

11.1.2 Z-Index

Let’s say we mastered HTML element placement on the screen in two dimen-
sions (X and Y.) Still you will encounter cases where you need to pick out
some elements to appear ”on top” of the others. Even if this isn’t how they
were listed in your HTML code structure.
The z-index property to the rescue. You can bring out any element whose
display property was set to value of absolute and ensure that it is always
displayed ”above” the rest. In other words, on the Z-axis.

Figure 138: Natural order of elements in HTML document.

150
Figure 139: The z-index property can bring out elements to the front.

11.1.3 box-shadow

We already covered box shadow earlier. But here are a few more examples.

Figure 140: Shadow is centered at the element.

Figure 141: Shadow is displaced by a few pixels from the element to create a
drop-shadow effect.

151
And finally... by specifying light colors you can turn a shadow into this glowing
effect:

Figure 142: Glowing effect can be simulated by using bright colors with
box-shadow property.

11.1.4 Scale, Translate, Rotate

Figure 143: Scaling, rotating and translating.

152
12 Chapter XII: Layout Structure
Aside from creating semantic structure of your document, looking from the
vantage point of graphic design, the very purpose of HTML code is to provide
structure. This cannot be stressed enough. Structural composition is all around
us. We see it in automobiles, airplanes, large high-rise buildings or even a
country road barn!
Structure cannot be avoided if your plan is to create meaningful user experi-
ence. This is why it’s important to spend some time mapping out the structure
of your creation on a piece of paper before even writing a single line of HTML
code. Thinking in terms of structure makes your design easier to adapt to new
circumstance in the future.
Structure is why blogs look like blogs – continuous blocks of text stories with
a smaller box at the bottom to leave a comment after reading. Your car (if
you have one) is designed with particular structure in mind. The front door
is right by the seat and the steering wheel. The wheels balance the vehicle on
the ground. It may be different medium, but the principle is the same.
Think of what your website is trying to accomplish and choose to build a
proper layout around that intent. By combining various CSS style properties,
you will use common sense and your innate graphic design talent to build
out initial wireframe. Then, by using various HTML elements and CSS styles
discussed in this book (and based on your own experiments) you will arrange
them to create a layout that matches your creative vision.
———
Up to this point we’ve covered enough to get us started on the journey to
building your own web application layouts. At least, their initial basic struc-
ture. Practice and experiment. And remember...this – or any other – book
should serve only as a starting point! It cannot replace actual experience
writing code.

153
12.1 Flex
Flex or ”flex box” (also known as CSS Flexible Box ) is a way of arranging
your HTML elements in a way that automatically adjusts across a given span
of space – the arbitrary page width in the browser – for example.
Flex was also created to make it easier to create layouts consisting of columns
and rows for various situations. Two of which are depicted on following dia-
grams:

Figure 144: A possible HTML layout that can be constructed using CSS flex
properties.

Figure 145: Another layout that can be efficiently solved using CSS flex prop-
erties.

Flex cells whose flex-wrap property is set to the value of wrap will automati-
cally adapt to the current browser’s dimensions. Consider this example of the

154
same exact layout being viewed in an increasingly narrowing browser window:

Figure 146: flex-wrap: wrap

155
I wish we could talk more about flex in this book. Because it’s such a neat
system of aligning HTML elements to the parent window with unknown di-
mensions. But we cannot dedicate too much space to CSS specification in this
book. My suggestion is to find a good flex tutorial online.

12.2 Grid
Because this is not primarily a CSS book we cannot spend much time talking
about CSS grid – a fairly recent addition to the CSS language (it is 2018 as
of the writing of this book.) However, it helps to know it exists, because it is
already gaining popularity among web designers.
Unlike other layout-creation strategies (floating and flex for instance) the CSS
grid provides an intuitive way of arranging your HTML elements by dividing
them into cells.

Figure 147: CSS grid with parent container set to grid-template-columns:


auto auto auto

156
Figure 148: Unlike functionality provided by any of the other CSS properties,
CSS grid is mindful of numbering spaces in between the cells. This is useful
for providing start and end lines, when you want to stretch a container across
multiple cells, as will be shown in the next example.

157
Figure 149: Reserving a larger space for an element within the grid.

This layout was achieved by setting following properties:


g r i d −column−s t a r t : 1 ;
g r i d −column−end : 3 ;
g r i d −row−s t a r t : 1 ;
g r i d −row−end : 3 ;

CSS grid naturally adapts to any screen resolution, but also provides enough
properties that can be used to tweak it. In a sense, CSS grid builds on and
behaves very similar to <table> HTML element but its far more versatile.

13 Chapter XIII: Building HTML Layouts


This chapter will demonstrate creating entire HTML layouts using two of the
most popular websites at the writing of this book – YouTube and Twitter.
I’m not saying that we will create an exact replica of each website with all of
the features in their glory. That would take months to do for an experienced

158
team of software engineers and web developers! In fact the server-side and
much of the dynamic front-end usually created with JavaScript will be avoided
completely. For that, I recommend getting a solid JavaScript book.
Instead, the thinking that goes into the process of creating HTML structure
and the accompanying CSS styles will be demonstrated here. We will take
everything we have learned so far in this book to create these layouts. So
if you feel like something doesn’t make sense, you can refer to some of the
previous chapters of this book.
Let’s get started with our first example...

13.1 YouTube Example


The YouTube scaffolding roughly consists of the following structure:

Figure 150: A rough draft of YouTube video page.

The first thing you want to do is to chart out the wireframe of the page. This
rough draft will represent the break down of most important components of
the layout. It is the guideline you will follow in constructing the page by
writing actual HTML code.

159
13.1.1 Layout Scaffold

The wireframe is rather complex when shown as a whole. Let’s break it down
into core compartments:

Figure 151: YouTube video page dissected into primary design elements.

Here in Section 1 we have the main video area. This is also where you will
see the channel description box, and just below it users will leave comments.
To the right we see Section 2 where we have the video suggestions list.
Finally Section 3 to the left is the overlay pane that appears when the ham-
burger button right next to the search bar is clicked.

13.1.2 Second Level Elements

We’ve determined and compartmentalized the parent scaffold – the primary


blocks of the entire layout. Now, let’s drill down into them and figure out the
basic idea behind child elements within each.

160
Figure 152: Second level elements in a YouTube-like layout.

Each one of these elements will narrow down on even smaller elements of each
User Interface block.

13.1.3 YouTube – Layout Elements

Before going into the source code, let’s further dissect the site into these blocks
so they can be through of separately:

Figure 153: YouTube header or <div id = "header">... in the source code.

161
Figure 154: YouTube primary video area or <div id = "primary">... in
the source code. And its children <div id = "video">... and <div id =
"video-description">...

162
Figure 156: An individual video preview block <div class = "preview">...
As you can see, in itself this element contains several unique items: the videos’
length, video title, channel name, number of views, and a small label indicating
whether it’s a new video – in other words, it has been recently published.

Figure 155: The section containing video suggestions is <div id =


"secondary">... and it also contains within itself elements <div id =
"extras">..., <div id = "preview">..., and a series of <div class =
"preview">... elements.

I think we’ve broken down the layout enough. Now let’s write some HTML
code to put it all together!

163
13.1.4 YouTube – Source Code

This source code listing contains both the CSS and the HTML scaffold work
to recreate examples from this chapter.
First, lets open the HTML document with roughly the minimum required
code:
<html>
<head>
<t i t l e>YouTube Layout</ t i t l e>
<s c r i p t type = ” t e x t / j a v a s c r i p t ”></ s c r i p t>
</head>
<body>

<s t y l e type = ” t e x t / c s s ”>

We’ve just opened our first style tag. Normally, you would use external CSS
file, but for this example we’d like to keep everything in one file for clarity’s
sake.
/∗ −− D e f a u l t f o n t f o r a l l components −− ∗/
∗ { f o n t −f a m i l y : A r i a l ; f o n t −s i z e : 13 px ; }

/∗ −− Website ’ s s k e l e t o n −− ∗/
#c o n t a i n e r { p o s i t i o n : r e l a t i v e ; width : 1200 px ; margin : auto
; }
#body { p o s i t i o n : r e l a t i v e ;
width : 1200 px ;
margin : auto ;
display : flex ;
padding : 16 px ;
box−s i z i n g : border −box ; }
#primary { f l e x −grow : 5 0 ; }
#s e c o n d a r y { f l e x −grow : 1 ; }
#o v e r l a y { p o s i t i o n : a b s o l u t e ; }

/∗ −− Header −− ∗/
#h e a d e r { d i s p l a y : f l e x ; padding−bottom : 4px ; border −bottom :
1px s o l i d s i l v e r ; }

164
#h e a d e r ∗ { f l e x −grow : 1 ; }

/∗ −− YouTube l o g o −− ∗/
. youtube−l o g o { d i s p l a y : i n l i n e −b l o c k ; c u r s o r : p o i n t e r ; }

/∗ −− Header e l e m e n t s −− ∗/
#i c o n −more−c o n t a i n e r { p o s i t i o n : r e l a t i v e ; h e i g h t : 32 px ; }
. i c o n −more {
position : relative ;
d i s p l a y : i n l i n e −b l o c k ;
width : 28 px ;
h e i g h t : 28 px ;
background : u r l ( ” hamburger . png” ) no−r e p e a t ;
margin : 3px ;
cursor : pointer ;
}
#s e a r c h −c o n t a i n e r { p o s i t i o n : r e l a t i v e ; h e i g h t : 32 px ; }
#s e a r c h −box {
position : relative ;
margin : 0 auto ;
width : 500 px ;
h e i g h t : 28 px ;
b o r d e r : 1px s o l i d #999;
border −r a d i u s : 3px ;
}
#s e a r c h −i n p u t {
width : 84%;
h e i g h t : 28 px ;
padding− l e f t : 8px ;
border : 0 ;
}
#s e a r c h −button {
position : relative ;
width : 80 px ;
h e i g h t : 28 px ;
float : right ;
background : #D1D1D1 u r l ( ” magnifying −g l a s s . png” ) 50% 3px
no−r e p e a t ;

165
}
#username {
position : relative ;
h e i g h t : 32 px ;
l i n e −h e i g h t : 32 px ;
t e x t −a l i g n : r i g h t ;
}
#s m a l l −avatar −c o n t a i n e r { p o s i t i o n : r e l a t i v e ; }
. s m a l l −a v a t a r { d i s p l a y : r e l a t i v e ;
float : right ;
width : 32 px ;
h e i g h t : 32 px ;
background−c o l o r : gray ;
border −r a d i u s : 32 px ;
}

/∗ −− V e r i c a l s e p a r a t o r l i n e −− ∗/
. separator {
width : 100%;
h e i g h t : 1px ;
border −bottom : 1px s o l i d s i l v e r ;
margin−bottom : 10 px ;
c l e a r : both ;
}

/∗ −− Video p r e v i e w box −− ∗/
. preview {
position : relative ;
width : 275 px ;
h e i g h t : 70 px ;
b o r d e r : 1px s o l i d s i l v e r ;
float : right ;
c l e a r : both ;
margin−bottom : 10 px ;
}
. video −i n f o { padding : 5px ; }
. video −box {
position : relative ;

166
float : left ;
width : 100 px ;
height : i n h e r i t ;
background : gray ;
margin−r i g h t : 5px ;
}
. video −l e n g t h {
position : absolute ;
bottom : 5px ;
r i g h t : 5px ;
width : auto ;
c o l o r : white ;
f o n t −s i z e : 12 px ;
background : b l a c k ;
padding : 1px 3px 1px 3px
}
. preview−vid eo − t i t l e { f o n t −w e i g h t : b o l d ; }
. secondary −i n f o { f o n t −s i z e : 12 px ; c o l o r : gray ; }
. video −i n f o { padding : 5px ; }

/∗ −− E x t r a s −− ∗/
#e x t r a s { padding : 5px ; h e i g h t : 20 px ; }
#up−next { width : 50%; f l o a t : l e f t ; }
#a u t o p l a y { width : 50%; f l o a t : r i g h t ; t e x t −a l i g n : r i g h t ; }

/∗ −− Video box −− ∗/
#v i d e o { width : 850 px ; h e i g h t : 500 px ; background−c o l o r :
silver ; }
#video −d e s c r i p t i o n { box−s i z i n g : border −box ; padding : 32 px ;
}
#video −s h a r e b a r {
h e i g h t : 32 px ;
border −bottom : 1px s o l i d gray ;
width : 850 px ;
}
#video −v i e w s { c o l o r : gray ; }
#s h a r e −button {
width : 80 px ;

167
float : right ;
t e x t −a l i g n : c e n t e r ;
}
#d i s l i k e s {
width : 80 px ;
float : right ;
t e x t −a l i g n : c e n t e r ;
}
#l i k e s {
width : 80 px ;
float : right ;
border −bottom : 2px s o l i d gray ;
t e x t −a l i g n : c e n t e r ;
}

/∗ −− D i s a b l e t e x t s e l e c t i o n i n v i d e o p r e v i e w c a r d −− ∗/
#s e c o n d a r y ∗ {
−webkit−touch−c a l l o u t : none ; /∗ iOS S a f a r i ∗/
−webkit−u s e r −s e l e c t : none ; /∗ S a f a r i ∗/
−khtml−u s e r −s e l e c t : none ; /∗ Konqueror HTML ∗/
−moz−u s e r −s e l e c t : none ; /∗ F i r e f o x ∗/
−ms−u s e r −s e l e c t : none ; /∗ I n t e r n e t E x p l o r e r /Edge ∗/
u s e r −s e l e c t : none ; /∗ Non−p r e f i x e d v e r s i o n , c u r r e n t l y
s u p p o r t e d by Chrome and Opera ∗/
}

/∗ −− Comment −− ∗/
. comment { d i s p l a y : f l e x ; padding−top : 16 px ; }
. comment−a v a t a r { f l e x −grow : 1 ; margin−r i g h t : 16 px ; }
. comment−username { f o n t −w e i g h t : b o l d ; }
. comment−body−c o n t a i n e r { f l e x −grow : 5 0 ; }
. comment−body { padding−top : 8px ; }
. comment−r e p l i e s { f o n t −w e i g h t : b o l d ; margin−top : 8px ;
cursor : pointer ; }

/∗ −− Autoplay s w i t c h e r −− ∗/
#autoplay −s w i t c h −c o n t a i n e r {
position : relative ;

168
d i s p l a y : i n l i n e −b l o c k ;
width : 50 px ;
h e i g h t : 16 px ;
b o r d e r : 1px s o l i d gray ;
border −r a d i u s : 16 px ;
background : gray ;
cursor : pointer ;
}
#autoplay −s w i t c h {
position : absolute ;
top : 0 ;
l e f t : 0;
width : 14 px ;
h e i g h t : 14 px ;
border −r a d i u s : 32 px ;
b o r d e r : 1px s o l i d gray ;
background : w h i t e ;
}
#autoplay −s w i t c h . on {
l e f t : unset ;
r i g h t : 0 ! important ;
}

#channel −i n f o −c o n t a i n e r { p o s i t i o n : r e l a t i v e ; padding : 10 px ;
}
#channel −i n f o { margin− l e f t : 50 px ; }

#video −about { c l e a r : both ; padding : 16 px 0 16 px 0 ; }


#video −a v a t a r {
position : relative ;
float : left ;
display : block ;
width : 32 px ;
h e i g h t : 32 px ;
background−c o l o r : gray ;
border −r a d i u s : 32 px ;
}
#s u b s c r i b e −button {

169
float : right ;
position : relative ;
display : block ;
background : gray ;
c o l o r : white ;
t e x t −a l i g n : c e n t e r ;
f o n t −f a m i l y : A r i a l , sans− s e r i f ;
padding : 1px 10 px 1px 10 px ;
l i n e −h e i g h t : 32 px ;
cursor : pointer ;
}

/∗ −− Overlay −− ∗/
#o v e r l a y −c o n t a i n e r {
d i s p l a y : none ;
position : fixed ;
top : 0 ;
l e f t : 0;
width : 100%;
h e i g h t : 100%;
background−c o l o r : rgba ( 0 , 0 , 0 , 0 . 5 ) ;
}
#o v e r l a y −c o n t a i n e r . on {
d i s p l a y : block ! important ;
}
#o v e r l a y {
background−c o l o r : w h i t e ;
padding : 32 px ;
h e i g h t : 100%;
}

HTML source code listing follows:


</ s t y l e>

< !−− Main v i e w //−−>

<div id = ” c o n t a i n e r ”>
<div id = ” h e a d e r ”>

170
<div id = ” i c o n −more−c o n t a i n e r ”
onclick = ” document . getElementById ( ’ o v e r l a y −c o n t a i n e r ’ ) .
className = ’ on ’ ; ”>
<div c l a s s = ” i c o n −more”></ div>
</ div>
<img c l a s s = ” youtube−l o g o ”
. . . src = ” youtube−l o g o . png”
. . . a l t = ”YouTube Logo ” />
<div id = ” s e a r c h −c o n t a i n e r ”
. . s t y l e = ” f l e x −grow : 7 ; ”>
<div id = ” s e a r c h −box ”>
<input type = ” t e x t ”
. id = ” s e a r c h −i n p u t ”
p l a c e h o l d e r = ” S e a r c h YouTube” />
<div id = ” s e a r c h −button ”></ div>
</ div>
</ div>
<div id = ” username ” s t y l e = ” f l e x −grow : 2 ; ”>username</ div
>
<div id = ” s m a l l −avatar −c o n t a i n e r ”>
<div c l a s s = ” s m a l l −a v a t a r ”></ div>
</ div>
</ div>

<div id = ” body ”>


<div id = ” primary ”>
<div id = ” v i d e o ”></ div>
<div>
<h1>Video Part 1 − The Most Amazing Video Ever</h1>
</ div>
<div id = ” vi deo −s h a r e b a r ”>
<div id = ” vi deo −v i e w s ”>1 5 , 4 9 3 v i e w s</ div>
<div id = ” s h a r e −button ”>SHARE</ div>
<div id = ” d i s l i k e s ”>22</ div>
<div id = ” l i k e s ”>450</ div>
</ div>
<div id = ” vi deo −d e s c r i p t i o n ”>
<div id = ” channel −i n f o −c o n t a i n e r ”>

171
<div id = ” s u b s c r i b e −button ”>SUBSCRIBE</ div>
<div id = ” vi deo −a v a t a r ”></ div>
<div id = ” channel −i n f o ”>Meow Channel<br/>Streamed
live on January 3 1 , 2018</ div>
</ div>

<div id = ” vi deo −about ”>Some amazing v i d e o f o o t a g e


about c u t e k i t t e n s t h a t p l a y and jump around and do
a l l k i n d s o f v a r i o u s t h i n g s t h a t you would e x p e c t
from an amazing v i d e o about c u t e k i t t e n s t h a t p l a y
and jump around and . . . </ div>

<div c l a s s = ” s e p a r a t o r ”></ div>


44 Comments <span s t y l e = ” width : 50 px ; d i s p l a y :
i n l i n e −b l o c k ; ”></span>
SORT BY <img src = ” s t a t s . png” a l t = ” s t a t s ” />
< !−− comment 1 //−−>
<div c l a s s = ”comment”>
<div c l a s s = ”comment−a v a t a r ”>
<div c l a s s = ” s m a l l −a v a t a r ”></ div>
</ div>
<div c l a s s = ”comment−body−c o n t a i n e r ”>
<span c l a s s = ”comment−username ”>London Grammar</
span>
<span c l a s s = ”comment−timestamp ”>4 y e a r s ago</
span>
<div c l a s s = ”comment−body ”>And when your house
b e g i n s t o r u s t<br/>Oh, i t ’ s j u s t , metal and
d u s t .</ div>
<div c l a s s = ”comment−r e p l i e s ”>View a l l 4 r e p l i e s<
/ div>
</ div>
</ div>

< !−− comment 2 //−−>


<div c l a s s = ”comment”>
<div c l a s s = ”comment−a v a t a r ”>
<div c l a s s = ” s m a l l −a v a t a r ”></ div>

172
</ div>
<div c l a s s = ”comment−body−c o n t a i n e r ”>
<span c l a s s = ”comment−username ”>Someone E l s e</
span>
<span c l a s s = ”comment−timestamp ”>4 y e a r s ago</
span>
<div c l a s s = ”comment−body ”>This i s j u s t a n o t h e r
comment .</ div>
<div c l a s s = ”comment−r e p l i e s ”>View 1 r e p l y</ div>
</ div>
</ div>

< !−− comment 3 //−−>


<div c l a s s = ”comment”>
<div c l a s s = ”comment−a v a t a r ”>
<div c l a s s = ” s m a l l −a v a t a r ”></ div>
</ div>
<div c l a s s = ”comment−body−c o n t a i n e r ”>
<span c l a s s = ”comment−username ”>
Furry V i s i t o r
</span> <span c l a s s = ”comment−timestamp ”>4 y e a r s
ago</span>
<div c l a s s = ”comment−body ”>More o p i n i o n s about
t h i s amazing v i d e o .</ div>
<div c l a s s = ”comment−r e p l i e s ”>View a l l 3 r e p l i e s<
/ div>
</ div>
</ div>
</ div>
</ div>

<div id = ” s e c o n d a r y ”>
<div id = ” e x t r a s ”>
<div id = ”up−next ”>Up next</ div>
<div id = ” a u t o p l a y ”>
<div id = ” aut op la y −s w i t c h −c o n t a i n e r ”>
<div id = ” aut op la y −s w i t c h ”
onclick = ” t h i s . className == ’ on ’ ?

173
t h i s . className = ’ ’ :
t h i s . className = ’ on ’ ”></ div>
</ div>
</ div>
</ div>

<div c l a s s = ” p r e v i e w ”>
<div c l a s s = ” v ideo −box ”>
<div c l a s s = ” v ideo −l e n g t h ”>0 1 : 5 1 : 2 8</ div>
</ div>
<div c l a s s = ” v ideo −i n f o ”>
<span c l a s s = ” preview−vid eo − t i t l e ”>
Video T i t l e 1 − The Most Amazing Video Ever
</span><br/>
<span c l a s s = ” secondary −i n f o ”>
Meow Channel
</span><br/>
<span c l a s s = ” secondary −i n f o ”>1 . 1K v i e w s</span>
</ div>
</ div>

<div c l a s s = ” s e p a r a t o r ”></ div>

<div c l a s s = ” p r e v i e w ”>
<div c l a s s = ” v ideo −box ”>
<div c l a s s = ” v ideo −l e n g t h ”>0 1 : 5 1 : 2 8</ div>
</ div>
<div c l a s s = ” v ideo −i n f o ”>
<span c l a s s = ” preview−vid eo − t i t l e ”>
Video Part 2 − The Most Amazing Video Ever
</span><br/>
<span c l a s s = ” secondary −i n f o ”>Meow Channel</span>
<br/>
<span c l a s s = ” secondary −i n f o ”>1 . 1K v i e w s</span>
</ div>
</ div>

< !−− Repeat t h e b l o c k ab o ve 7 t i m e s t o c r e a t e a l i s t

174
−− web d e v e l o p e r s u s u a l l y u s e ” i t e r a t o r s ” c o n n e c t e d
t o a d a t a b a s e i n o r d e r t o s c r o l l through an
e x i s t i n g l i s t o f v i d e o s ( o r o t h e r i t e m s . ) //−−>

</ div>
</ div>
</ div>

< !−− O v e r l a y //−−>


<div id = ” o v e r l a y −c o n t a i n e r ” c l a s s = ” ”>
<div id = ” o v e r l a y ”>
<div c l a s s = ” i c o n −more” onclick = ” document .
getElementById ( ’ o v e r l a y −c o n t a i n e r ’ ) . className = ’ ’ ; ”>
</ div>
<img c l a s s = ” youtube−l o g o ” src = ” youtube−l o g o . png” a l t
= ”YouTube Logo ” />
<ul>
< l i>Home</ l i>
< l i>Trending</ l i>
< l i>S u b s c r i p t i o n</ l i>
</ ul>
LIBRARY
<ul>
< l i>H i s t o r y</ l i>
< l i>Watch l a t e r</ l i>
< l i>WebGL T u t o r i a l s</ l i>
< l i>React JS T u t o r i a l s</ l i>
< l i>Show more</ l i>
</ ul>
SUBSCRIPTIONS
<ul>
< l i>Cats I n c o r p o r a t e d</ l i>
< l i>Meowing R e c o r d i n g s</ l i>
< l i>The Meow Channel</ l i>
</ ul>
</ div>
</ div>

175
</body>
</html>

It took us about 4 pages of code to construct a basic YouTube layout.


Running this code in a browser will produce the following result:

Figure 157: Actual HTML and CSS rendered in Chrome browser. Note the
autoplay switch actually works here! Thanks to the CSS and some inline
JavaScript code.

13.2 Twitter Example


In this chapter we will create another layout. This time we will be learning
from Twitter – one of the most popular social network sites – as of this writing.
If you haven’t used Twitter before, there is a good chance you have at least
heard of it.

176
Figure 158: Twitter-like layout.

Following the same principle of separating design element by breaking them


down into individual sections – we can think of Twitter layout as consisting
of these core elements:

Figure 159: Twitter layout broken down into sections.

177
13.2.1 Twitter – Breaking down the layout into sections

Figure 160: Header is an essential component of any modern web ap-


plication or website. Twitter is no exception from this rule. In source
code that we’re about to see this location will be created with <div id =
"navigation-container">... and <div id = "navigation">... HTML
elements.

Figure 161: Main profile header area.

Figure 162: Avatar.

178
Figure 163: An area under the avatar with user profile details and photo
gallery.

Figure 164: An individual tweet.

Figure 165: Secondary navigation bar.

Lets build out these elements with HTML and CSS. The complete source code
is listed in the next section.

179
13.2.2 Twitter – Source code

The source code for Twitter website is a bit more simple than YouTube.
<html>
<head>
<t i t l e>YouTube Layout</ t i t l e>
<s c r i p t type = ” t e x t / j a v a s c r i p t ”></ s c r i p t>
</head>
<body>

<s t y l e type = ” t e x t / c s s ”>

body { margin : 0 ; padding : 0 ; }


body ∗ { }

/∗ −− D e f a u l t f o n t f o r a l l components −− ∗/
∗ { f o n t −f a m i l y : A r i a l ; f o n t −s i z e : 13 px ; }

/∗ −− Website ’ s s k e l e t o n −− ∗/
#c o n t a i n e r {
display : grid ;
position : relative ;
width : 1200 px ;
h e i g h t : auto ;
margin : auto ;
b o r d e r : 2px s o l i d b l u e ;
}

#n a v i g a t i o n −c o n t a i n e r {
position : fixed ;
top : 0 ;
l e f t : 0;
h e i g h t : 40 px ;
width : 100%;
b o r d e r : 2px s o l i d b l u e ;
background : w h i t e ;
z−i n d e x : 1 ;
}

180
#n a v i g a t i o n {
position : relative ;
width : 1200 px ;
margin : auto ;
b o r d e r : 2px s o l i d r e d ;
}

#n a v i g a t i o n d i v {
d i s p l a y : i n l i n e −b l o c k ;
padding : 10 px ;
}

. sub−n a v i g a t i o n −c o n t a i n e r −1 {
margin− l e f t : 298 px ;
margin−bottom : 16 px ;
h e i g h t : 37 px ;
b o r d e r : 1px s o l i d gray ;
background : w h i t e ;
}

. sub−n a v i g a t i o n −c o n t a i n e r −1 d i v {
d i s p l a y : i n l i n e −b l o c k ;
padding : 10 px ;
}

. sub−n a v i g a t i o n −c o n t a i n e r −2 {
margin− l e f t : 0px ;
margin−bottom : 16 px ;
h e i g h t : 37 px ;
b o r d e r : 1px s o l i d gray ;
background : w h i t e ;
}

. sub−n a v i g a t i o n −c o n t a i n e r −2 d i v {
d i s p l a y : i n l i n e −b l o c k ;
padding : 10 px ;
}

181
#h e a d e r {
background : u r l ( ’ p r o f i l e −image . jpg ’ ) ;
h e i g h t : 375 px ;
}

#body {
position : relative ;
width : 1200 px ;
margin : auto ;
padding : 8px ;
box−s i z i n g : border −box ;
display : grid ;
g r i d −gap : 10 px ;
g r i d −template −columns : 280 px auto 250 px ;
}

#o v e r l a y −c o n t a i n e r { p o s i t i o n : f i x e d ; }
#o v e r l a y { p o s i t i o n : a b s o l u t e ; }

/∗−− t w e e t −− ∗/
. tweet {
position : relative ;
display : grid ;
padding− l e f t : 30 px ;
g r i d −template −columns : 50 px auto ;
margin−bottom : 16 px ;
}

. tweet−a v a t a r {
position : relative ;
width : 48 px ;
h e i g h t : 48 px ;
background : gray ;
border −r a d i u s : 100 px ;
}

. tweet−message {

182
d i s p l a y : i n l i n e −b l o c k ;
width : 400 px ;
min−h e i g h t : 50 px ;
margin− l e f t : 8px ;
}

. tweet−username {
display : block ;
margin−bottom : 4px ;
f o n t −w e i g h t : b o l d ;
min−h e i g h t : 18 px ;
}

. tweet−o p t i o n s { margin−top : 16 px ; }

. option {
width : 16 px ;
h e i g h t : 16 px ;
b o r d e r : 2px s o l i d s i l v e r ;
d i s p l a y : i n l i n e −b l o c k ;
margin : 0 16 px
}

#avatar −c i r c l e −1 {
position : absolute ;
top : −200px ;
l e f t : 64 px ;
width : 200 px ;
h e i g h t : 200 px ;
background : w h i t e ;
border −r a d i u s : 150 px ;
b o r d e r : 2px s o l i d s i l v e r ;
}

#avatar −c i r c l e −2 {
position : absolute ;
top : 13 px ;
l e f t : 13 px ;

183
width : 170 px ;
h e i g h t : 170 px ;
background : u r l ( ”meow . png” ) ;
background−s i z e : 100% 100%;
border −r a d i u s : 150 px ;
b o r d e r : 2px s o l i d s i l v e r ;
}

. s e l e c t e d −tab { border −bottom : 2px s o l i d gray ; }

. sub−c o n t a i n e r {
b o r d e r : 1px s o l i d gray ;
border −r a d i u s : 3px ;
padding : 5px ;
}
</ s t y l e>

< !−− f i x e d h e a d e r //−−>


<div id = ” n a v i g a t i o n −c o n t a i n e r ”>
<div id = ” n a v i g a t i o n ”>
<div>Home</ div>
<div>Moments</ div>
<div>N a v i g a t i o n</ div>
<div>Messages</ div>
<div>Logo</ div>
<div>S e a r c h</ div>
<div>Avatar</ div>
<div>Tweet</ div>
</ div>
</ div>

< !−− Main v i e w //−−>


<div id = ” c o n t a i n e r ”>
<div id = ” h e a d e r ”>h e a d e r</ div>
<div c l a s s = ” sub−n a v i g a t i o n −c o n t a i n e r −1”>
<div>button 1</ div>
<div>button 2</ div>
<div c l a s s = ” s e l e c t e d −tab ”>button 3</ div>

184
<div>button 4</ div>
<div>button 5</ div>
<div>button 6</ div>
</ div>
<div id = ” body ”>

< !−− p r o f i l e d e t a i l s //−−>


<div id = ” p r o f i l e −d e t a i l s ”>

<div id = ” avatar −c i r c l e −1”>


<div id = ” avatar −c i r c l e −2”></ div>
</ div>

<div c l a s s = ” sub−c o n t a i n e r ”>


F e l i x<br/>
@felixmeow
</ div>

<div c l a s s = ” sub−c o n t a i n e r ”>


S i t t i n g t h e r e w a i t i n g f o r someone t o p i c k me up . I am
F e l i x , p l e a s e t a k e me home .
</ div>

</ div>

< !−− message f e e d //−−>


<div id = ” f e e d ”>

<div c l a s s = ” sub−n a v i g a t i o n −c o n t a i n e r −2”>


<div c l a s s = ” s e l e c t e d −tab ”>Tweets</ div>
<div>Tweets & r e p l i e s</ div>
<div>Media</ div>
</ div>

<div c l a s s = ” t w e e t ”>
<div c l a s s = ” tweet−a v a t a r ”></ div>
<div c l a s s = ” tweet−message ”>
<div c l a s s = ” tweet−username ”>F e l i x</ div>

185
<div c l a s s = ” tweet−body ”>This i s q u i t e a message and
O what a message t h i s i s .<br/>Maybe t h i s i s s e c o n d
l i n e .</ div>
<div c l a s s = ” tweet−o p t i o n s ”>
<div c l a s s = ” o p t i o n ”></ div>
<div c l a s s = ” o p t i o n ”></ div>
<div c l a s s = ” o p t i o n ”></ div>
</ div>
</ div>
</ div>

<div c l a s s = ” t w e e t ”>
<div c l a s s = ” tweet−a v a t a r ”></ div>
<div c l a s s = ” tweet−message ”>
<div c l a s s = ” tweet−username ”>F e l i x</ div>
<div c l a s s = ” tweet−body ”>This i s q u i t e a message
and O what a message t h i s i s .<br/>Maybe t h i s i s
s e c o n d l i n e .</ div>
<div c l a s s = ” tweet−o p t i o n s ”>
<div c l a s s = ” o p t i o n ”></ div>
<div c l a s s = ” o p t i o n ”></ div>
<div c l a s s = ” o p t i o n ”></ div>
</ div>
</ div>
</ div>

<div c l a s s = ” t w e e t ”>
<div c l a s s = ” tweet−a v a t a r ”></ div>
<div c l a s s = ” tweet−message ”>
<div c l a s s = ” tweet−username ”>F e l i x</ div>
<div c l a s s = ” tweet−body ”>This i s q u i t e a message
and O what a message t h i s i s .<br/>Maybe t h i s i s
s e c o n d l i n e .</ div>
<div c l a s s = ” tweet−o p t i o n s ”>
<div c l a s s = ” o p t i o n ”></ div>
<div c l a s s = ” o p t i o n ”></ div>
<div c l a s s = ” o p t i o n ”></ div>
</ div>

186
</ div>
</ div>

</ div>

< !−− s i d e b a r //−−>


<div id = ” s i d e b a r ”>s i d e b a r</ div>
</ div>
</ div>
</body>
</html>

These examples only demonstrate construction of HTML layouts. Building


entire applications requires additional knowledge of JavaScript and server-side
programming.
This code was included here at the last chapters of this book, to give the reader
an idea of what’s involved in creating realistic website layouts.
In the next section, we will explore creation of a couple simple web applications:
Clock and Calculator, respectively. The goal of the author here is to show
potential next steps that the reader new to HTML should explore, if he (or
she of course) is interested in skill-set expansion required for creating web
applications professionally.

187
14 Chapter XIV: Building Web Applications
Even though this book is only an introduction to HTML language it wouldn’t
be fair to the reader if we didn’t show any examples of small applications at
all.
While we won’t be building full blown applications here, the examples provided
here will serve as a starting point to crafting something more interesting than
basic layouts.
The purpose of this chapter was intended to demonstrate the place of HTML
in overall application composition consisting of two other languages: CSS and
JavaScript.

188
14.1 Clock
By the end of this section we will create this simple clock:

Figure 166: The notches and clock hands are actually HTML elements posi-
tioned using combination of techniques covered in this book.

No images were used in creation of this clock. Everything is a DIV element.


Here is the same clock with border: 1px solid black; and background:
white; properties that expose its wireframe structure:

Figure 167: Wireframe view of the HTML clock showing transparent elements.

189
Head over to this jsFiddle URL created to see how this clock works in action:
https://jsfiddle.net/7ngueqh8/134/
To create this clock application, we need to separate our code in three distinct
parts: HTML for semantic structure, CSS for determining position, rotation
angles and size of elements, and JavaScript for animating the clock hands.

14.1.1 HTML – Semantic Structure

HTML is the simplest part of the application:


1 <div id = ” c l o c k −rim ”>
2 <div id = ” c l o c k −b a s e ”>
3 <div id = ” notch−c o n t a i n e r ”></ div>
4 <div id = ” brand ”>HTML<br/>c l o c k</ div>
5 <div id = ” hour ”></ div>
6 <div id = ” minute ”></ div>
7 <div id = ” s e c o n d ”></ div>
8 <div id = ” c e n t e r ”></ div>
9 </ div>
10 </ div>

14.1.2 CSS – Element Style

1 /∗ −− Outer a r e a o f t h e c l o c k −− ∗/
2 #c l o c k −rim {
3 display : block ;
4 position : relative ;
5 width : 300 px ;
6 h e i g h t : 300 px ;
7 background : l i n e a r −g r a d i e n t ( gray , b l a c k ) ;
8 border −r a d i u s : 150 px ;
9 }
10
11 /∗ −− I n n e r a r e a o f t h e c l o c k −− ∗/
12 #c l o c k −b a s e {
13 display : block ;

190
14 position : relative ;
15 width : 260 px ;
16 h e i g h t : 260 px ;
17 margin : 19 px auto ;
18 border −r a d i u s : 150 px ;
19 background : w h i t e ;
20 }
21
22 /∗ −− Seconds hand −− ∗/
23 #s ec o n d { p o s i t i o n : a b s o l u t e ; top : 123 px ; l e f t : 128 px ; width
: 100 px ; h e i g h t : 2px ; b o r d e r : 1px s o l i d t r a n s p a r e n t ;
border −r a d i u s : 5px ; t r a n s f o r m : u n s e t ; background : g r e e n ;
t r a n s f o r m −o r i g i n : 1px 1px ; }
24
25 /∗ −− Minutes hand −− ∗/
26 #minute { p o s i t i o n : a b s o l u t e ; top : 123 px ; l e f t : 128 px ; width
: 100 px ; h e i g h t : 4px ; b o r d e r : 1px s o l i d t r a n s p a r e n t ;
border −r a d i u s : 5px ; t r a n s f o r m : u n s e t ; background : r e d ;
t r a n s f o r m −o r i g i n : 2px 2px ; }
27
28 /∗ −− Hours hand −− ∗/
29 #hour { p o s i t i o n : a b s o l u t e ; top : 123 px ; l e f t : 128 px ; width :
50 px ; h e i g h t : 4px ; b o r d e r : 1px s o l i d t r a n s p a r e n t ; border −
r a d i u s : 5px ; t r a n s f o r m : u n s e t ; background : b l u e ;
t r a n s f o r m −o r i g i n : 2px 2px ; }
30
31 /∗ −− Center o f t h e c l o c k −− ∗/
32 #c e n t e r { p o s i t i o n : a b s o l u t e ; top : 118 px ; l e f t : 120 px ; width
: 16 px ; h e i g h t : 16 px ; background : w h i t e ; b o r d e r : 1px
s o l i d gray ; border −r a d i u s : 16 px ; }
33
34 /∗ −− The box t h a t s a y s ”HTML c l o c k ” −− ∗/
35 #brand { p o s i t i o n : a b s o l u t e ; top : 110 px ; l e f t : 165 px ; b o r d e r
: 1px s o l i d gray ; border −r a d i u s : 5px ; width : 50 px ; h e i g h t
: 40 px ; f o n t −f a m i l y : Verdana ; f o n t −s i z e : 11 px ; t e x t −a l i g n
: c e n t e r ; l i n e −h e i g h t : 20 px ; }
36
37 #notch−c o n t a i n e r {

191
38 width : 260 px ;
39 h e i g h t : 260 px
40 }
41
42 /∗ −− Thick notch ( h o u r s and minutes ) −− ∗/
43 . notch {
44 position : absolute ;
45 width : 10 px ;
46 h e i g h t : 2px ;
47 background : b l a c k ;
48 border −r a d i u s : 5px 5px 5px 5px ;
49 }
50
51 /∗ −− Thin notch ( s e c o n d s ) −− ∗/
52 . thin {
53 position : absolute ;
54 width : 10 px ;
55 h e i g h t : 1px ;
56 border −top : 1px s o l i d gray ;
57 }
58
59 d i v { b o r d e r : 1px s o l i d t r a n s p a r e n t ; }

14.1.3 JavaScript – Animating CSS Styles

Finally, this JavaScript will animate the clock’s hands.


The notable code here is the setInterval JavaScript function that runs the
code specified inside so-called ”arrow function” brackets ()=>{...}. A couple
of functions for converting vectors to angles and back are provided. These are
useful whenever you need to add custom-rotated elements to your design.
One other thing of interest you may find here:
1 var notch = document . c r e a t e E l e m e n t ( ” d i v ” ) ;

Notice how the JavaScript method document.createElement(”div”); dynami-


cally creates an HTML element to be implanted into the DOM (using
element.appendChild(notch ) function) alongside other existing elements.

192
In JavaScript, you can create HTML elements dynamically, without having
to write HTML code. This is a slightly advanced subject and it will require
additional material beyond the scope of this book.
Unfortunately I cannot go any deeper in detail here and I hope you can pick
up a good JavaScript book if you’re interested in further exploring the subject
of building interactive web applications.
1 /∗ −− This f u n c t i o n c o n v e r t s d e g r e e s t o r a d i a n s −− ∗/
2 f u n c t i o n deg2rad ( d )
3 {
4 r e t u r n ( 2 ∗ d / 3 6 0 ) ∗ Math . PI ;
5 }
6
7 let H = 0;
8 let M = 0;
9 let S = 0;
10
11 /∗ −− S t a r t u p d a t i n g t h e c l o c k a t an i n t e r v a l −− ∗/
12 s e t I n t e r v a l ( ( ) =>{
13
14 l e t minute = document . getElementById ( ” minute ” ) ;
15 l e t hour = document . getElementById ( ” hour ” ) ;
16 l e t s e c o n d = document . getElementById ( ” s e c o n d ” ) ;
17
18 S = new Date ( ) . g e t S e c o n d s ( ) ∗ 6 − 9 0 ;
19 M = new Date ( ) . g e t M i n u t e s ( ) ∗ 6 − 9 0 ;
20 H = new Date ( ) . getHours ( ) ∗ 30 − 9 0 ;
21
22 s e c on d . s t y l e . t r a n s f o r m = ’ r o t a t e ( ’ + S + ’ deg ) ’ ;
23 minute . s t y l e . t r a n s f o r m = ’ r o t a t e ( ’ + M + ’ deg ) ’ ;
24 hour . s t y l e . t r a n s f o r m = ’ r o t a t e ( ’ + H + ’ deg ) ’ ;
25
26 } , 10) ;
27
28 /∗ −− Convert 2D v e c t o r t o a n g l e −− ∗/
29 f u n c t i o n vec2ang ( x , y ) {
30 a n g l e I n R a d i a n s = Math . atan2 ( y , x ) ;
31 a n g l e I n D e g r e e s = ( a n g l e I n R a d i a n s / Math . PI ) ∗ 1 8 0 . 0 ;

193
32 return angleInDegrees ;
33 }
34
35 /∗ −− Convert a n g l e t o 2D v e c t o r −− ∗/
36 f u n c t i o n ang2vec ( a n g l e ) {
37 var r a d i a n s = a n g l e ∗ ( Math . PI / 1 8 0 . 0 ) ;
38 var x = Math . c o s ( r a d i a n s ) ;
39 var y = Math . s i n ( r a d i a n s ) ;
40 var a = new Segment ( 0 , 0 , x , y ) ;
41 var u = a . normal ( ) . u n i t ( ) ;
42 r e t u r n [ u . vecx , u . vecy ] ;
43 }
44
45 let nc = document . getElementById ( ” notch−c o n t a i n e r ” ) ;
46 let angle = 0;
47 let rotate x = 120;
48 let rotate y = 0;
49
50 /∗ −− Arrange t h i n s e c o n d n o t c h e s around t h e c l o c k ’ s f a c e −−
∗/
51 f o r ( l e t i = 0 ; i < 6 0 ; i ++) {
52 l e t t h i n = document . c r e a t e E l e m e n t ( ” d i v ” ) ;
53 l e t x = r o t a t e x ∗ Math . c o s ( a n g l e ) − r o t a t e y ∗ Math . c o s (
angle )
54 l e t y = r o t a t e y ∗ Math . c o s ( a n g l e ) + r o t a t e x ∗ Math . s i n (
angle )
55 l e t r = vec2ang ( x , y ) ;
56 t h i n . className = ” t h i n ” ;
57 t h i n . s t y l e . l e f t = 122 + x + ”px” ;
58 t h i n . s t y l e . top = 127 + y + ”px” ;
59 t h i n . s t y l e . t r a n s f o r m = ” r o t a t e ( ” + r + ” deg ) ” ;
60 nc . appendChild ( t h i n ) ;
61 a n g l e += ( Math . PI / 3 0 0 ) ∗ 1 0 ;
62 }
63
64 // r e s e t
65 a n g l e = 0 ;
66 r o t a t e x = 1 2 0 ;

194
67 r o t a t e y = 0 ;
68
69 /∗ −− Arrange t h i c k e r n o t c h e s around t h e c l o c k ’ s f a c e −− ∗/
70 for ( l e t i = 0 ; i < 1 2 ; i ++) {
71 l e t notch = document . c r e a t e E l e m e n t ( ” d i v ” ) ;
72 l e t x = r o t a t e x ∗ Math . c o s ( a n g l e ) − r o t a t e y ∗ Math . c o s (
angle )
73 l e t y = r o t a t e y ∗ Math . c o s ( a n g l e ) + r o t a t e x ∗ Math . s i n (
angle )
74 l e t r = vec2ang ( x , y ) ;
75 notch . className = ” notch ” ;
76 notch . s t y l e . l e f t = 122 + x + ”px” ;
77 notch . s t y l e . top = 127 + y + ”px” ;
78 notch . s t y l e . t r a n s f o r m = ” r o t a t e ( ” + r + ” deg ) ” ;
79 nc . appendChild ( notch ) ;
80 a n g l e += ( Math . PI / 6 0 ) ∗ 1 0 ;
81 }

We already discussed in the beginning of this book in section 2.19 Including


Inline, Internal and External CSS or JavaScript Code the placement of CSS
and JavaScript blocks in your HTML page. Head over there to see where
exactly each part of this web application should be entered in your source
code.

195
14.2 Calculator
In our previous example we created an animated clock. But it’s not really
an interactive application. Meaning, it does not offer the visitor a chance to
interact with it or take some sort of input.
In this chapter, let’s create another simple application that takes basic input
from the user. This calculator application should be interesting-enough to
demonstrate user input without having to deal with too much complexity.
First, let’s take a look at what we’re actually trying to build here:

Figure 168: Calculator application we will build in this section of the book.

Let’s begin by building out the HTML scaffold!

14.2.1 HTML – Application Scaffold

The HTML here is the simplest part of the entire application. We just need
to add the view and some buttons. Note that no id’s are necessary for most of
the buttons. This is because our JavaScript code will read the values directly
from the element’s content from the event.target object via the onClick
event.

196
1 <div id = ” frame ”>
2 <div id = ” c a l c u l a t o r ”>
3 <div id = ” h i s t o r y ”>0</ div>
4 <div id = ” view ”>0</ div>
5 <div id = ” b u t t o n s ”>
6 <div id = ” r e s e t ”>C</ div>
7 <div></ div>
8 <div></ div>
9 <div>/</ div>
10 <div>7</ div>
11 <div>8</ div>
12 <div>9</ div>
13 <div>∗</ div>
14 <div>4</ div>
15 <div>5</ div>
16 <div>6</ div>
17 <div>−</ div>
18 <div>1</ div>
19 <div>2</ div>
20 <div>3</ div>
21 <div>+</ div>
22 <div></ div>
23 <div>0</ div>
24 <div> .</ div>
25 <div id = ” e q u a l s ”>=</ div>
26 </ div>
27 </ div>
28 <div id = ”on”></ div>
29 </ div>
30 <div id = ” message ”></ div>
31 <div id = ” message2 ”></ div>

14.2.2 CSS – Cascading Style Sheets

1 ∗ { f o n t −f a m i l y : A r i a l , sans− s e r i f ; }
2
3 #frame {

197
4 position : relative ;
5 display : block ;
6 width : 500 px ;
7 h e i g h t : 244 px ;
8 padding : 16 px ;
9 background : gray ;
10 border −r a d i u s : 8px ;
11 background : l i n e a r −g r a d i e n t (#555 , #000) ;
12 }
13
14 #c a l c u l a t o r {
15 position : relative ;
16 display : block ;
17 width : 500 px ;
18 h e i g h t : 400 px ;
19 margin−top : 29 px ;
20 }
21
22 #h i s t o r y {
23 width : 100%;
24 h e i g h t : 16 px ;
25 background : #333;
26 c o l o r : #999;
27 t e x t −a l i g n : r i g h t ;
28 }
29
30 #view {
31 width : 100%;
32 h e i g h t : 28 px ;
33 background : #333;
34 c o l o r : #CCC;
35 t e x t −a l i g n : r i g h t ;
36 f o n t −s i z e : 20 px ;
37 }
38
39 #b u t t o n s {
40 display : grid ;
41 g r i d −template −columns : auto auto auto auto

198
42 }
43
44 #b u t t o n s ∗ {
45 cursor : pointer ;
46 background : w h i t e ;
47 t e x t −a l i g n : c e n t e r ;
48 h e i g h t : 32 px ;
49 l i n e −h e i g h t : 32 px ;
50 }
51
52 #b u t t o n s ∗ {
53 b o r d e r : 1px s o l i d #aaa ;
54 border −r i g h t : u n s e t ;
55 border −bottom : u n s e t ;
56 }
57
58 #b u t t o n s ∗ : hover {
59 background : l i m e ;
60 c o l o r : #333;
61 f o n t −w e i g h t : b o l d ;
62 }
63
64 #b u t t o n s ∗ {
65 −webkit−touch−c a l l o u t : none ; /∗ iOS S a f a r i ∗/
66 −webkit−u s e r −s e l e c t : none ; /∗ S a f a r i ∗/
67 −khtml−u s e r −s e l e c t : none ; /∗ Konqueror HTML ∗/
68 −moz−u s e r −s e l e c t : none ; /∗ F i r e f o x ∗/
69 −ms−u s e r −s e l e c t : none ; /∗ I n t e r n e t E x p l o r e r /Edge ∗/
70 u s e r −s e l e c t : none ; /∗ Non−p r e f i x e d v e r s i o n , c u r r e n t l y
71 s u p p o r t e d by Chrome and Opera ∗/
72 }
73
74 #b u t t o n s ∗ {
75 background : l i n e a r −g r a d i e n t (# f f f , #bbb ) ;
76 }
77
78 #r e s e t {
79 background : y e l l o w ;

199
80 }
81
82 #e q u a l s {
83 background : b l u e ;
84 c o l o r : white ;
85 }
86
87 #on {
88 position : absolute ;
89 top : 8px ;
90 r i g h t : 8px ;
91 width : 8px ;
92 h e i g h t : 8px ;
93 background : l i n e a r −g r a d i e n t ( lime , g r e e n ) ;
94 border −r a d i u s : 16 px ;
95 b o r d e r : 1px s o l i d #000;
96 }

14.2.3 JavaScript – Programming Interactivity

Below is the JavaScript listing that turns the HTML and CSS we constructed
so far into a fully functioning calculator!
1
2 var queue = new Array ( ) ;
3 var c u r r e n t n u m b e r = new Array ( ) ;
4 var g i d = document . getElementById ;
5 var tally = 0;
6
7 function print queue () {
8 document . getElementById ( ” message ” ) . innerHTML = JSON .
s t r i n g i f y ( queue ) ; }
9
10 function print current () {
11 document . getElementById ( ” message2 ” ) . innerHTML =
array to number ( current number ) ; }
12
13 f u n c t i o n a r r a y t o n u m b e r ( number ) {
14 r e t u r n number . t o S t r i n g ( ) . r e p l a c e ( / , / g i , ” ” ) ; }

200
15
16 function reset history () {
17 document . getElementById ( ” h i s t o r y ” ) . innerHTML = ” ” ; }
18
19 function update history () {
20 document . getElementById ( ” h i s t o r y ” ) . innerHTML = queue .
t o S t r i n g ( ) . r e p l a c e (/ ,/ gi , ”” ) ; }
21
22 let can use actions = false ;
23 l e t can us e di gi ts = true ;
24
25 Object . e n t r i e s ( document . q u e r y S e l e c t o r A l l ( ”#b u t t o n s d i v ” ) ) .
map ( ( e l e m e n t ) => {
26
27 element [ 1 ] . addEventListener ( ” c l i c k ” , f u n c t i o n ( event ) {
28
29 l e t v a l u e = e v e n t . t a r g e t . innerHTML ;
30
31 i f ( v a l u e == ” . ” && c u r r e n t n u m b e r . indexOf ( ” . ” ) == −1)
32 c u r r e n t n u m b e r . push ( ” . ” ) ;
33
34 // D i g i t was p r e s s e d −− but don ’ t p r o c e s s i t i f d i g i t s
cannot be used a t t h i s time
35 if ( can use digits ) {
36 i f ( ! isNaN ( v a l u e ) && v a l u e != ” ” ) {
37 c u r r e n t n u m b e r . push ( v a l u e ) ;
38 document . getElementById ( ” view ” ) . innerHTML =
array to number ( current number ) ;
39 print queue () ;
40 print current () ;
41 // At l e a s t one d i g i t was e n t e r e d , we can u s e a c t i o n s
again
42 can use actions = true ;
43 }
44 }
45
46 s w i t c h ( e v e n t . t a r g e t . innerHTML )
47 {

201
48 c a s e ’C ’ :
49 // Reset view
50 document . getElementById ( ” view ” ) . innerHTML = ” 0 ” ;
51 queue = new Array ( ) ;
52 c u r r e n t n u m b e r = new Array ( ) ;
53 can use actions = false ;
54 ca n us e di gi ts = true ;
55 break ;
56
57 case ’= ’:
58
59 // Reset view
60 var −c o m p l e t e = ( queue . t o S t r i n g ( ) + c u r r e n t n u m b e r ) .
r e p l a c e (/ ,/ gi , ”” ) ;
61 queue = new Array ( ) ;
62 c u r r e n t n u m b e r = new Array ( ) ;
63
64 // A s s i g n r e s u l t t o c u r r e n t number i n queue
65 var e v a l u a t e d = e v a l ( c o m p l e t e ) ;
66 document . getElementById ( ” view ” ) . innerHTML = e v a l u a t e d ;
67 current number [ 0 ] = evaluated ;
68 reset history () ;
69
70 // We j u s t c a l c u l a t e d r e s u l t ,
71 // This r e s u l t becomes t h e f i r s t number i n t h e queue
72 // D i s a b l e d i g i t s . . . and e n a b l e a c t i o n s (+−/∗)
73 can use actions = true ;
74 can use digits = false ;
75 break ;
76
77 case ’∗ ’:
78 i f ( can use actions ) {
79 queue . push ( a r r a y t o n u m b e r ( c u r r e n t n u m b e r ) ) ;
80 c u r r e n t n u m b e r = new Array ( ) ;
81 queue . push ( ”∗” ) ;
82 can use actions = false ;
83 ca n us e di gi ts = true ;
84 }

202
85 break ;
86
87 case ’/ ’:
88 i f ( can use actions ) {
89 queue . push ( a r r a y t o n u m b e r ( c u r r e n t n u m b e r ) ) ;
90 c u r r e n t n u m b e r = new Array ( ) ;
91 queue . push ( ” / ” ) ;
92 can use actions = false ;
93 ca n us e di gi ts = true ;
94 }
95 break ;
96
97 case ’+ ’:
98 i f ( can use actions ) {
99 queue . push ( a r r a y t o n u m b e r ( c u r r e n t n u m b e r ) ) ;
100 c u r r e n t n u m b e r = new Array ( ) ;
101 queue . push ( ”+” ) ;
102 can use actions = false ;
103 ca n us e di gi ts = true ;
104 }
105 break ;
106
107 c a s e ’ − ’:
108 i f ( can use actions ) {
109 queue . push ( a r r a y t o n u m b e r ( c u r r e n t n u m b e r ) ) ;
110 c u r r e n t n u m b e r = new Array ( ) ;
111 queue . push ( ”−” ) ;
112 can use actions = false ;
113 ca n us e di gi ts = true ;
114 }
115 break ;
116
117 default :
118 update history () ;
119 break ;
120 }
121
122 print queue () ;

203
123
124 }) ;
125
126 }) ;

See this app in action at https://jsfiddle.net/wx695acf/163/

15 Chapter XV: Creating Meaningful Web-


sites
Semantic structure of your HTML document helps search engines increase
the chance of correctly categorizing your website so that it is easily found by
people.
Web designers rarely think of semantic structure of their website, focusing
primarily on designing layouts visually and populating them with content and
media. But in addition, a semantically correct HTML document harbors fol-
lowing advantages:
1. Friendship with Search Engines. Even if Google changes their search
algorithm, a semantically correct website has better chance of keeping a higher
position in search results, compared to a similar website that does not imple-
ment a semantic strategy.
2. Social Media. Semantically-correct websites provide helpful hints that
improve experience with your site. For example, you can include special im-
ages, additional title and description apart from standard meta tags. This
provides ability to use different title and description for the specific case when
your page is shared social media websites, such as Facebook or Twitter.
3. Serving Wider Audience. Creating better experience for people with
disabilities, by – for example – specifying audible text describing visual ele-
ments for visitors with compromised vision.
You can improve semantic integrity of your website by using meta tags.

204
15.1 MetaTags
Meta tags provide additional information about your web page. They are used
in a wide variety of ways, some of which we’ll take a look at below.
All meta tags are required to be specified between the <head></head> pair in
your HTML document.
But your HTML document itself is not required to use any of the meta tags
at all. However, it is in your best interest to do so if you want to improve the
way in which search engines process and categorize your website.
Including a few meta tags is better than not including any at all. Some meta
tags have greater influence on different aspects of website readability by web
servers. While others are not significant at all.
Here is a collection of meta tags you will find yourself working with.
1 <meta name = ” l a n g u a g e ” content = ” E n g l i s h ”>

A meta tag to specify the default language of your web page.


1 <meta http−e q u i v = ” c o n t e n t −l a n g u a g e ” content=” en−US” />

Specify content language, this time in another format, usually more often used
by web servers.
1 <meta
2 http−e q u i v = ” Content−Type”
3 content = ” t e x t / html ; c h a r s e t=u t f −8”>

Let browser know the text formatting character set assumes UTF-8.
1 <meta name = ” v i e w p o r t ” content = ” width=d e v i c e −width ” />

A directive for mobile phones, to set width of the website to the width of the
device.
1 <meta name = ” d e s c r i p t i o n ”
2 content = ” This i s a t u t o r i a l l i b r a r y s i t e which c o n t a i n s
a c o l l e c t i o n o f u s e f u l React t u t o r i a l s . React i s a
J a v a S c r i p t l i b r a r y f o r d e v e l o p i n g web a p p l i c a t i o n s
e f f i c i e n t l y . ” />

205
The description meta tag provides a few paragraphs about the content of the
web page. Be as descriptive as possible.
1 <meta name = ” keywords ”
2 content = ” r e a c t , r e a c t j s , j s , docs , documentation , i n t r o , ui ,
n a t i v e , pdf , book , e−book , t u t o r i a l , f r e e , c o u r s e , f u t u r e
, 2 0 1 7 , p r o j e c t , j a v a s c r i p t , welcome , g e t t i n g , s t a r t e d , book ,
r e v i e w ” />

A series of single keywords describing your website. They can be separated by


comma or space character.
Please ensure that each keyword refers to content that actually exists on that
web page! It is not a good idea to bloat this meta tag with keywords in an
attempt to gain more attention from search engines. Artificial Intelligence
algorithms developed at Google are very apt at figuring out whether someone
is trying to play the system.
1 <meta name = ” a u t h o r ”
2 content = ” Greg S i d e l n i k o v ” />

Author of the content.


1 <meta name = ” s u b j e c t ”
2 content = ” React JS F u l l Stack Web Development ” />

Subject of this web page.


1 <meta name = ” c o p y r i g h t ”
2 content = ” L e a r n i n g Curve Books , LLC” />

Copyright information.
1 <meta name = ” web author ”
2 content = ” Greg S i d e l n i k o v ”>

Web author.
1 <meta name = ” r o b o t s ”
2 content = ” index , f o l l o w ” />

A hint for search engines (spider robot software that ”crawls” the web) on how
you wish your content to be treated.

206
The index directive means you want Google or other search engines to index
your website in their search engine. In other words store it in their database
used for showing search results – which opens doors to driving more traffic
and potentially targeted visitors to the content of your site.
The follow directive suggests to the spider to also visit all hyperlinks on your
website for potential inclusion in web search.
You can specify a value of noindex, nofollow if you want to prevent search
engines from indexing your web page, or following any hyperlinks. However,
you can also set this value to follow if you don’t want the page to be indexed,
but wish for the search engines to follow through to any of the pages specified
in hyperlinks on that page.
1 <meta name = ” a b s t r a c t ”
2 content = ” quick , s t a r t , guide , b e g i n n e r s , t u t o r i a l ” />

An abstract idea of your web page specified using a list of keywords separated
by comma or space. Similar to keywords meta tag.
1 <meta name = ” r e v i s i t −a f t e r ” content = ” 3 days ” />

A hint for search engines about how often you wish them to re-visit your page.
This is often ignored by search engines. It is unknown whether this meta tag
is taken seriously by any of the modern search engines, as they are keen on
deciding on these types of rules on their own.
1 <meta name = ” c o n t a c t ”
2 content = ” g r e g . s i d e l n i k o v @ g m a i l . com” />

Physical address, P.O. Box or an e-mail address the author of this web page
wants its visitors to refer to when contacting them.
1 <meta name = ” d i s t r i b u t i o n ” content = ” g l o b a l ” />

Specify global distribution.


1 <meta name = ” news keywords ”
2 content = ” Online , ReactJS , React , JS , T u t o r i a l , Guide ,
Quick , S t a r t , I n t r o d u c t i o n , B e g i n n e r s ” />

207
Keywords used in news stories referring to your page. This tag is also not used
very much, but with advent of the recent battle on ”fake news,” web designers
might want to take greater care at thinking up of a list of keywords that talks
about the web page in the context of a news story.
1 <meta name = ” r a t i n g ” content = ” g e n e r a l ” />
2 <meta name = ” r a t i n g ” content = ” s a f e f o r k i d s ” />

A tag used to rate how appropriate the content of your web page is for a
specific audience. When used, it is used to let younger audience know that
the content may or may not be appropriate for them.
This is not a common meta tag by any degree and carries no practical influence
on your website. But it’s nice to know that it exists, because as the web
matures, features like these might become more important with time.
1 <meta name = ” v e r i f y −v1 ” content = ” 123 ” />

The verify-v1 tag is often used by Google and some other service providers, to
verify that the website belongs to its owner.
The content value is usually given by the service provider, for you to paste
into your site. Because this step requires logging into your web server Google
or other companies can be sure that you are the web site’s owner.
Once that is determined, those companies will allow access to various features
regarding the domain name of your site that are otherwise not available. This
adds a great deal of security, limiting certain permissions to actual owners of
the website.
1 <meta name = ” g o o g l e −s i t e −v e r i f i c a t i o n ” content = ” 567 ” />

Another way to verify ownership of a website by a Google service, for example,


Google Webmasters (http://www.google.com/webmasters)

15.1.1 Facebook Post Preview

1 <meta p r o p e r t y=” og : t i t l e ” content=” React . j s T u t o r i a l s ” />


2 <meta p r o p e r t y=” og : type ” content=” a r t i c l e ” />
3 <meta p r o p e r t y=” og : u r l ” content=” h t t p : / /www. example . n e t / ” />

208
4 <meta p r o p e r t y=” og : s i t e n a m e ” content=” React JS T u t o r i a l s ” />
5 <meta p r o p e r t y=” og : image ”
6 content=” h t t p : / /www. example . n e t / r e a c t −l o g o . png” />

A series of meta tags developed by Facebook to provide images and titles when
sharing on social media websites.
15.1.2 Twitter Cards

1 <meta name=” t w i t t e r : c a r d ” content=”summary” />


2 <meta name=” t w i t t e r : s i t e ” content=” @ r e a c t j s t e a c h e r ” />
3 <meta name=” t w i t t e r : t i t l e ” content=” React . j s T u t o r i a l s ” />
4 <meta name=” t w i t t e r : d e s c r i p t i o n ”
5 content=” Learn React . j s with t h i s Free Course−l i k e
t u t o r i a l w e b s i t e . Nothing but Free Premium−Q u a l i t y
t u t o r i a l s . ” />
6 <meta name=” t w i t t e r : image ”
7 content=” h t t p : / /www. r e a c t j s t u t o r i a l . n e t / r e a c t −l o g o . png” /
>

If you want your tweet to include specific image, title and description when
sharing on Twitter, you can use a series of meta tag names developed by Twit-
ter. When a Tweet is posted this information will be automatically scraped
from your HTML source code by Twitter.
Twitter will then implement this information in order to construct a better-
looking tweet message, using the so-called Twitter Cards. Without these meta
tags a tweet would simply convert your URL to a clickable link. It is rec-
ommended to use this if your content is tailored to being shared on social
media.
It is not required to use any of the meta tags. But they certainly help. There
are a few other meta tags available in HTML. However, the ones we’ve talked
about in this chapter were carefully chosen for having the greatest practical
impact.

209
16 Thank You
Looks like you’ve reached the end of this book. Thank you for reading!

And please don’t forget to send feedback. When a Learning Curve receives
enough constructive criticism, we make our best to fix issues in the next edi-
tion of the book. Our e-mail address is [email protected]

2018
c – 2020 Learning Curve Books, LLC.

210

You might also like