Cover - HowToCodeInHTMLAndCSS
Cover - HowToCodeInHTMLAndCSS
We live in a time when websites have become part o our everyday lives, competing
with traditional newspapers and books, and ofering users a whole range o new
opportunities. You probably visit at least a ew o your avorite places on the Web
every day, whether it's or shopping, sending messages, playing games, checking the
news or looking at pictures o your riends. With the help o websites, you can have
un, make a living, and even get to know other people.
So it seems that the ability to create websites would be extremely valuable. The
Internet provides us with many opportunities or development, and knowledge
about how the Internet is built allows us to understand the changes taking place in
modern society and economy.
But have you ever wondered how to create your own website?
I you have, I invite you to take a journey with me. We will look at websites that you
know and visit every day. By analyzing them, we'll use comparisons and analogies
that will help you better understand how they are built. I've been a web developer
and working on the web proessionally or several years and I am condent that at
the end o our adventure together, we will create your rst website.
Thanks to Kvba or design help; Peter Mierzejewski, Paul Czerski and Greg Kaliciak
or prooreading.
2
CHAPTER 1
3
At rst glance, there's nothing complicated. Let's have some un and highlight (or
block out) each element, as though we were dealing with Lego parts.
4
5
In total, we've got ve pieces, arranged one on top o the other.
You might remember rom your childhood that in order to build something specic,
you need a lot o diferent blocks that are useul or diferent things. Each o them
has a certain unction. For example, when building a house, one type is useul or
walls, and the other more useul or oors. There is no single, universal block or
element rom which you can make anything that comes to mind. See the gure
below? This is what a large selection o lego choices should look like, right?
The same is true with websites. When you build a website, you use the diferent
elements according to their ideal destination. In the Verge example, it seems that we
6
are dealing with various objects (or blocks), so doing something like applying the
same color or style to each block would be counterintuitive. Ater all, the title is not
the same as the date, or content o the paragraph. They each perorm completely
diferent unctions.
This is much more interesting. We now have a ew diferent types o "building
blocks". Only two blocks are o the same type, specically the two paragraphs below
7
the picture. This is no diferent than organizing legos. We're going to keep together
similar ragments o text that belong in the same group. As a ormality, we'll name
each o the sections based on their unction in the context o the article.
So we've marked each element according to their semantic meaning. This is exactly
the kind o behavior and logic that we can expect to see rom a web browser. It's our
job to tell the browser, in a way that it can understand, what each o these elements
8
mean and how they t together semantically. I this is not done, then our site will
appear as a clump o single text.
You might have created such pages or articles using a text editor program like
Microsot Word or Pages. In text editors, achieving efects like "header styles" is a
matter o clicking a ew buttons. In other words, when we select text in a word editor
and press "Header 1" we are assigning a bunch o diferent eatures in the
background that tell the editor to display stuf in a specic way.
9
CHAPTER 2
10
Beore creating any kind o web page, it's a good idea to divide the content into
smaller components by their importance. Let's now try to identiy and highlight each
element o this job posting, just as we did in the example rom The Verge.
A brie analysis will help us to better understand which areas o the text should
stand out in the job posting. Red indicates the headline text. Green indicates the
accompanying image. And purple marks the two paragraphs (or "body") o the job
posting.
11
Let's return or a moment to the analogy o word processors and text editing
programs where web pages could be created in regular text documents. Perhaps
Open, Notepad, or Word, would contain the text o the announcement, and then
save as a text le. It should work right?
12
However, this doesn't look like what we designed, does it? It's just a mass o text and
doesn't display a picture. What now? Maybe we should try to create this post in
Word or Photoshop? We don't exactly want to do this. We've made an error here
that we'll soon x. The key problem is that we've created a website with only plain
text.
A web browser cannot understand how to display a page properly with only plain
text — it doesn't know which part o the text should be the title or which part should
be a picture. In order to display the page properly, we need to dene each element
by the unction o the text and pass this inormation to the browser. We've partly
done it. Let's do a little denition work and use proper syntax so browser will also
understand it:
13
As you can see, there are special markings within the text. We'll get to these later.
For now, it's best to simply try to copy them exactly as they are, rom top to bottom,
as i you were building with blocks, one by one.
Next, save the HTML le. By the way: I recommend you Sublime Text Editor which is
one o the best code editors out there.
14
Now let's try the new le in a web browser.
15
It looks a bit better. Each section o the text is now ormatted diferently, and the
picture is also displayed. This is not the nal version though. The lack o color, bold
text and style doesn't quite match up yet. But beore we work on that, let's keep our
ocus on the structure o the page.
First, let's compare the plain text document version o the posting, and the one
presented in HTML:
16
As a result o surrounding specic text ragments with special tags, we've created a
completely diferent document, which can be understood by the browsers. Way to
go!
This is called HTML, or Hypertext Markup Language, and is the primary markup
language or displaying inormation or a web browser. In simpler terms, it's a
language that uses "tags" (like <this>) to mark text, so that you can describe the text
to your browser. This also includes search engines and a ew other programs which
we'll cover later on. HTML tags are like grammar orms in verbal communication,
without them, you cannot build a coherent website, much like you cannot orm
correct sentences or paragraphs without grammar.
In our case, we used only a ew simple tags, and below is a list o the unctions that
each tag perorms:
So, i you have a website with a ew paragraphs o text, you surround each
paragraph with the <p> tag. I the text is the main headline, then surround the text
with <h1>, and so on and so orth.
17
All tag constructions are extremely simple and look like this:
<tagname>content</tagname>
You might have noticed that the second tag is diferent. This is because each tag
must "close," as the saying goes in HTML jargon. The orward-slash appears in the
closing tag to tell the browser that this marks the end o an element. For example, all
paragraph elements end in </p>, while a Header 1 ends in </h1>.
There are also tags which do not need to be enclosed. For example image tags,
<img>, which are used to insert pictures. In our example above, we used it as
ollows:
<img src="images/white-cat.jpg">
There are several more tags that do not need to to be "closed", which you will learn
about later in this book.
One important realization to make about HTML tags is that, like dictionaries contain
the vocabulary o a language, so too does HTML have a kind o dictionary that
denes tags and describes when and where to use them. At the moment we have
covered only a ew, but there are many more. The international organization known
as The World Wide Web Consortium (W3C) together with a group named WHATWG
encourage best practices, standards, and compatibility across the web. You can view
their denition o HTML elements here: https://html.spec.whatwg.org/#toc-
semantics.
Returning to our example, it should look like the ollowing in HTML code:
18
<h1>We're looking for an HTML and CSS developer</h1>
<img src="images/white-cat.jpg">
<p>Don't wait, apply now! Our crazy team is waiting for you
rightmeow!</p>
Notice that it contains two paragraphs o text, marked within <p></p> tags:
<p>Don't wait, apply now! Our crazy team is waiting for you
rightmeow!</p>
Suppose that we want the reader o our ad to pay particular attention to a certain
part in a paragraph. Let's say that we wanted to mark the part o the text that says
"we need a skilled web developer in HTML and CSS." How would an HTML tag let the
browser know? The answer is the <strong> element, which will surround parts o
text that should represent a strong importance or its contents.
<p>Don't wait, apply now! Our crazy team is waiting for you
right meow!</p>
19
Note that the <strong> tag surrounds the text, and also sits within the <p> tag. In
programming terms, we would say that the <strong> tag is a "child" element within
<p> because it nests within the parent. There are many tags that can nest within
other tags, while many others cannot. Each tag has a specic list o possible HTML
elements which it can contain (or be contained by), and you will need to check
whether a certain tag is allowed or not. You can think o it like smaller blocks
combining to make a bigger block piece (in this case the <strong> block is a
component o <p>, which is in turn a block o the whole text).
Take note that a web browser we used above displayed the ragment in bold, but
this is not always a rule. It's very common that <strong> makes text bold, but
sometimes it will be ignored. The reason or using this HTML tag in this text is a good
example o how nesting works, but visual efects (like bold) can be better achieved
through a language called CSS, which we will learn more about in a moment.
20
CHAPTER 3
Let's begin with the code we have so ar, with all o the elements we've learned
about:
At the very top o any sel-respecting HTML page, there should be an indication o
the document type. This is the doctype:
<!DOCTYPE html>
<h1>We're looking for an HTML and CSS developer.</h1>
<img src="images/white-cat.jpg">
<p>For our client, The Cat Factory, <strong>we need a skilled
web developer in HTML and CSS</strong>. We offer a competitive
salary, a bag of cat food, and toys.</p>
<p>Don't wait, apply now! Our crazy team is waiting for you
right meow!</p>
21
The highlighted section above "tells" the browser that the page is an HTML
document, and the page's code should be treated according to the established
standards or the language. This inorms the browser o several rules, which will
guide how our website is viewed. Among other things, it helps the browser to know
which tags may be allowed or not allowed. It helps the browser better interpret our
code.
<!DOCTYPE html>
<html>
<h1>We're looking for an HTML and CSS developer.</h1>
<img src="images/white-cat.jpg">
<p>For our client, The Cat Factory, <strong>we need a skilled
web developer in HTML and CSS</strong>. We offer a competitive
salary, a bag of cat food, and toys.</p>
<p>Don't wait, apply now! Our crazy team is waiting for you
right meow!</p>
</html>
Note that this tag needs to be closed, so we want to be sure to add </html> at the
end:
<!DOCTYPE html>
<html>
code
</html>
As a result, everything that belongs to our website is contained under the tag
<html>. When writing HTML, it only makes sense that the code should be enclosed
by </html>.
22
However, the <html> tag is not yet complete. We want to add more inormation
about the language o our site. Since this is an English example, let's designate it as
such:
<!DOCTYPE html>
<html lang="en">
<h1>We're looking for an HTML and CSS developer.</h1>
<img src="images/white-cat.jpg">
<p>For our client, The Cat Factory, <strong>we need a skilled
web developer in HTML and CSS</strong>. We offer a competitive
salary, a bag of cat food, and toys.</p>
<p>Don't wait, apply now! Our crazy team is waiting for you
right meow!</p>
</html>
Notice the highlighted section has modied the <html> tag. This is called an
"attribute." Attributes are modiers in HTML, and are always written next to the tag,
between the <> enclosure. Attributes have the ollowing template when writing
code.
tag attribute="value"
As a HTML developer grows, he/she will come across many diferent attributes. In
addition to "lang" there are a large variety. Here are just a ew examples.
• <div id="sidebar"></div> - the name o the attribute is "id", and the value is "sidebar"
• <p class="landscape"></p> - the name o the attribute is "class" and the value is
"landscape"
• <input type="text"> - the name o the attribute is "type", and the value is "text"
We use attributes because in many HTML tags (or example <html>) do not contain
all the necessary inormation. With attributes, we can modiy the tags we use and
add even more useul inormation to them. In this case, we have let the browser
23
known that our HTML document is written in English, so we've modied the <html>
tag with the attribute "lang" and given it a value or "en" (English).
Multiple attributes can even occur in a single tag. Here are a ew examples:
It's important to note that attributes are also part o HTML standards, just like
nesting tags, and lists o these attributes, along with the tags that they can modiy,
can be ound on the web.
In act, we've already used an attribute when we were rst building our web page!
Remember the image code? You placed it in an HTML document with the ollowing
line:
<img src="images/white-cat.jpg">
In this case, the <img> tag was modied with the attribute src with the value o
images/white-cat.jpg.
The tag by itsel is only <img>, so i we simply let it alone, the browser would have
no way to retrieve the source o inormation to display. When we dene a "src," we
tell the browser, "Hey, load inormation rom this source." The browser then knows
it should look or the older "images" and the le "white-cat.jpg." We can also pass a
link to any resource on the web (i it's not restricted), or instance
http://4.bp.blogspot.com/-z4sMggeD4dg/UO2TB9INuFI/AAAAAAAAdwc/
Kg5dqlKKHrQ/s1600/unny-cat-pictures-032-025.jpg.
24
This is the gist o how attributes work. Thanks to attributes, we can add rich and
valuable inormation that is helpul or HTML tags.
Now let's return to our document and add in more necessary components. We'll be
looking at the tag <head>, which contains elements that are not necessarily helpul
to your page's content, but essential or search engines, browser tabs, and so on.
For example, the title on a web page helps search engines nd your content.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<h1>We're looking for an HTML and CSS developer.</h1>
<img src="images/white-cat.jpg">
<p>For our client, The Cat Factory, <strong>we need a skilled
web developer in HTML and CSS</strong>. We offer a competitive
salary, a bag of cat food, and toys.</p>
<p>Don't wait, apply now! Our crazy team is waiting for you
right meow!</p>
</html>
At the moment, our head tag is empty, but usually this is the location you want to
put all meta inormation like the title o the whole document. As we create the page
with our job ofer, let's say that we decide on a title "Job Ofer: HTML and CSS
developer." Let's go ahead an add it!
25
<!DOCTYPE html>
<html lang="en">
<head>
<title>Job Offer: HTML and CSS Developer</title>
</head>
<h1>We're looking for an HTML and CSS developer.</h1>
<img src="images/white-cat.jpg">
<p>For our client, The Cat Factory, <strong>we need a skilled
web developer in HTML and CSS</strong>. We offer a competitive
salary, a bag of cat food, and toys.</p>
<p>Don't wait, apply now! Our crazy team is waiting for you
right meow!</p>
</html>
As you might have noticed, we added the title between the tag <title>. What's the
diference, and why did we do it that way? The below image explains what happens
where we don't have a <title> tag (let), and our page that has the <title> tag (right).
With title, our websites are more usable or browser user and navigating among
many tabs is much easier.
26
As you can see, this is a very important to consider when coding your site. Without it,
the site would be without a name, which would leave a bad impression on visitors.
Personally, I wouldn't trust a page that doesn't even have a title.
We need to do one more thing ater adding a head, and that is to add the <body>
tag. This separates the content o the entire page rom the head. Everything
displayed on your web page will be placed within <body>.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Job Offer: HTML and CSS Developer</title>
</head>
<body>
<h1>We're looking for an HTML and CSS developer.</h1>
<img src="images/white-cat.jpg">
<p>For our client, The Cat Factory, <strong>we need a
skilled web developer in HTML and CSS</strong>. We offer a
competitive salary, a bag of cat food, and toys.</p>
<p>Don't wait, apply now! Our crazy team is waiting for you
right meow!</p>
</body>
</html>
27
Hooray! It looks like the end o our eforts and it seems that everything is correct. As
a novice coder, it's probably a good idea to check i everything is OK (e.g. nested
tags, good attributes, etc.). But not everyone has riends among advanced HTML
developers, who may be asked or consultation. Luckily, there is a special tool we
can use to check i our code is correct. The W3C organization, the same group that
denes the standards and upholds best practices o HTML documents, has made a
tool to check code. The tool is simply called an HTML validator, and is available at
http://validator.w3.org.
Let's use the tool and check to see i our code is correct.
28
...Woops! We have one error and 3 warnings. Let's take a look at them.
The single error that the validator reported has to do with our image. Let's take a
look at the content o the error:
An img element must have an alt attribute, except under certain conditions. For details,
consult guidance on providing text alternatives or images.
It turns out that the <img> tag in your document must always have the "alt" attribute
that will be used in case the browser cannot load the image. It will then display the
value o this alternate attribute instead (it's better than an empty space, right?).
Beore we choose the value or the attribute "alt," let's look at the HTML specication
to make sure that we do it correctly:
“Gives the allback content or the image. The requirements on the alt attribute's value
are described in the next section.”
It then urther distinguishes several scenarios, or when and how to use the alt
attribute. In our case, we are dealing with an image that has been placed or
decoration o the post and does not contain any content, plot, or other inormation
to the reader. In this case, we should leave the alternate attribute empty, says the
specication:
29
“However, a decorative image that isn't discussed by the surrounding text but still has
some relevance can be included in a page using the img element. Such images are
decorative, but still orm part o the content. In these cases, the alt attribute must be
present but its value must be the empty string.”
In other cases, we would want to choose a text string that might replace what is on
the picture. Detailed guidelines or several distinguished cases can be ound at the
specication or the <img> tag here: http://www.w3.org/wiki/HTML/Elements/img.
But we still have the 3 warnings. The most important o them is as ollows:
“No character encoding inormation was ound within the document, either in an HTML
meta element or an XML declaration. It is oten recommended to declare the character
encoding in the document itsel, especially i there is a chance that the document will
be read rom or saved to disk, CD, etc.”
30
But not to worry, this is a simple warning. Beore we try to understand it, let's
examine the ollowing example which will allow us to better understand the
problem.
It's important to realize that your website may be visited by people rom diferent
countries like Spain, China or Sweden not to mention others. I you allow it, they can
leave a comment or a message that might be displayed next to your articles. It's
important to note though, that diferent countries use diferent languages with their
own diacritical marks. In Swedish it can be ä or ö, while Chinese ofer you a whole
range o them like 汉语拼音方案. In the global web it's crucial to let diferent
languages display correctly on the same page. Let's examine what would happen, i
we used Chinese language in our post:
<p>PS 再见</p>
31
Note the last line where, instead o a proper Chinese sentence, we can see some
odd signs that don't make sense at all in any o modern languages. Don't panic, it's
related to the warning that we have received in the HTML validator. It turns out that
we haven't inserted a special line, that would allow other languages to display
properly. In computers world, it's called Character encoding. I we passed this
inormation to the HTML page, it would "tell" the browser that it's ready to display a
wide range o characters including all diferent diacritical marks.
32
Let's do this!
<!DOCTYPE html>
<html lang="en">
<head>
<title>Job Offer: HTML and CSS Developer</title>
<meta charset="utf-8">
</head>
<body>
<h1>We're looking for an HTML and CSS developer.</h1>
<img src="images/white-cat.jpg">
<p>For our client, The Cat Factory, <strong>we need a
skilled web developer in HTML and CSS</strong>. We offer a
competitive salary, a bag of cat food, and toys.</p>
<p>Don't wait, apply now! Our crazy team is waiting for you
right meow!</p>
</body>
</html>
This time we have had to use a special tag <meta> with the attribute charset and
given it a value or "ut-8". ut-8 means a special character set that incorporating
those rom a majority o languages around the world, i not all o them.
And that's it! You have just built your rst website ever! Congratulations!
33
CHAPTER 4
34
Note that here we have one header or the article. In addition, inormation about the
author, as well as a photo and a "quote" paragraph. It is worth noting that as a ront-
end web developer, you will oten receive graphic designs (like the one shown
above) and have to recreate everything in HTML.
Let's begin with the elements which will always be xed and do not change. As we
did earlier, we want the doctype tag, <html>, the <head> and <body>. Note that in
35
our <head> we'll want to make sure we have character encoding or "ut-8" so that
we can display special characters on our site.
Our starting template or the code will look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Justin Beaver fascinated by HTML</title>
</head>
<body>
</body>
</html>
At this point, we've nished the template which will now serve as the basis or the
contents o the article.
I we save the le as article.html, and then open in a browser, we will see nothing at
all because the <body> tag has no content.
We generally start rom the most general content, ollowed by more specic,
detailed content as we progress. Let's analyze our pieces:
36
1. In the article, the most important inormation would probably be the header inormation
which contains the title: "Justin Beaver: Ever since I learned HTML, my lie has made a
complete 180."
2. The next most important inormation is about the author, "authored by Damian Wielgosik."
3. The rst paragraph o text comes next, then a place or a photo and its description.
4. Finally, the last paragraph, which contains a quote, "I will probably have a song about HTML
on my next album".
And those are our pieces. This type o analysis where we look at the pieces helps us
visualize how the HTML code will look. The hierarchy starts rom the most general
element (the parent), and then continues to elements which a parent contains
(children), which are more specic, detailed elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Justin Beaver fascinated by HTML</title>
</head>
<body>
<article>
</article>
</body>
</html>
You might have noticed that we used the <article> element which is contained within
the <body> parent. Articles consist o a header and content, so all tags representing
heading and paragraphs will naturally be children o <article>.
37
Adding to our list o elements that we've discovered so ar, we're going to now use
an element that marks headers, the <header> tag.
We can add the <header> code as a child o <article>. As we move rom top to
bottom in the code (in terms o importance), note that we also move rightwards with
indentations to show that an element is lower on the hierarchy than its above
component. In the example below, <header> is not only below <article>, but also
indented to show where it is on the hierarchy.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Justin Beaver fascinated by HTML</title>
</head>
<body>
<article>
<header>
</header>
</article>
</body>
</html>
Our header section is now ready, but what should go inside the <header>? Well, we
discussed earlier that we have a title and author. We'll use the tag <h1> or the title
o the text, and <p> or the author. There is no specic HTML tag or author, so in
this case we're using <p> as a general container or a text.
In the code below, we've added <h1> and <p> tags to the header element:
38
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Justin Beaver fascinated by HTML</title>
</head>
<body>
<article>
<header>
<h1>Justin Beaver: Ever since I learned HTML, my life
has made a complete 180</h1>
<p>Posted by: Damian Wielgosik</p>
</header>
</article>
</body>
</html>
By the way, you should note that in addition to <h1>, there are lower levels o the
HTML headers that look like this:
• <h2>
• <h3>
• <h4>
• <h5>
• <h6>
These elements help to map the logical structure o headings and subheadings. So
or example, i we were writing in book ormat, its title would be contained between
the element <h1>. Then, the names o the chapters will be tagged with <h2>, and
subsections <h3>.
Note that you shouldn't simply denote a header as <h4> on a whim. Headers must
be nested under a higher priority header, so i you have <h4>, <h3> must occur
beore it, and <h2> must occur beore that, and so on.
39
For example, this book could look like this:
<h1>Simple HTML</h1>
<h2>My first website</h2>
<h3>W3C Validator</h3>
<h2>Meet CSS</h2>
<h3>Selectors in CSS</h3>
Let's move on to coding the rst paragraph o text. We want to avoid nesting the
paragraph under the <header>. It makes sense that the paragraph should be part o
the <article>. So, we'll add the rst <p> within <article>, with the same priority as
<header>, but underneath it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Justin Beaver fascinated by HTML</title>
</head>
<body>
<article>
<header>
<h1>Justin Beaver: Ever since I learned HTML, my life
has made a complete 180</h1>
<p>Posted by: Damian Wielgosik</p>
</header>
<p>Justin Beaver confessed something that even his
greatest fans would have never expected of the skilled musicians
and lyricist. The young rock-and-roller admitted that since he
typed his first title tag, his life became easier. It has been
reported by those surrounding the Canadian that Beaver's private
mentors, Ryan Loseling and Nicolas Crate, often walk around Los
Angeles disputing what a great tool the HTML validator is.</p>
</article>
</body>
</html>
40
Next we'll add the photo plus a description. For this type o content, and thereore
all related to the entire document such as photos, charts or maps, we'll use the
<gure> tag. It is worth noting that the <gure> condition o use is important into
that you can use the extra element <gcaption>, which puts a description o the
image beneath it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Justin Beaver fascinated by HTML</title>
</head>
<body>
<article>
<header>
<h1>Justin Beaver: Ever since I learned HTML, my life
has made a complete 180</h1>
<p>Posted by: Damian Wielgosik</p>
</header>
<p>Justin Beaver confessed something that even his
greatest fans would have never expected of the skilled musicians
and lyricist. The young rock-and-roller admitted that since he
typed his first title tag, his life became easier. It has been
reported by those surrounding the Canadian that Beaver's private
mentors, Ryan Loseling and Nicolas Crate, often walk around Los
Angeles disputing what a great tool the HTML validator is.</p>
<figure>
<img src="cat.jpg" alt="Justin Beaver's cat is pleased">
<figcaption>Justin Beaver's happy cat</figcaption>
</figure>
</article>
</body>
</html>
Ater we've added the image, we just have one more paragraph to add to the article.
Note that this paragraph has a quote, "I will probably have a song about HTML on
my next album." We can annotate this quote so that our code has a greater
41
semantic value. Perhaps in the uture, someone will look or quotes rom Justin
Beaver, and this designation will help them nd the quote aster. Otherwise, search
engines would always have to deal with one huge chunk o text.
In order to indicate that a section o text is a quote, we're going to use the <q> tag
within the new paragraph:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Justin Beaver fascinated by HTML</title>
</head>
<body>
<article>
<header>
<h1>Justin Beaver: Ever since I learned HTML, my life
has made a complete 180</h1>
<p>Posted by: Damian Wielgosik</p>
</header>
<p>Justin Beaver confessed something that even his
greatest fans would have never expected of the skilled musicians
and lyricist. The young rock-and-roller admitted that since he
typed his first title tag, his life became easier. It has been
reported by those surrounding the Canadian that Beaver's private
mentors, Ryan Loseling and Nicolas Crate, often walk around Los
Angeles disputing what a great tool the HTML validator is.</p>
<figure>
<img src="cat.jpg" alt="Justin Beaver's cat is pleased">
<figcaption>Justin Beaver's happy cat</figcaption>
</figure>
<p>Beaver has already created some websites and does not
intend to stop there.
<q>I will probably have a song about HTML on my next
album,</q> - the artist added.
</p>
</article>
</body>
</html>
42
Now, let's save the code to a le with the extension .html and display it in the
browser.
You have now completed your second page. Great! This is another step to becoming
a proessional web developer.
43
CHAPTER 5
In the previous sections, we used HTML to describe the content o the site, and
divide it into ragments according to their importance. CSS will be responsible or
the appearance o our web sites. CSS code can be placed in a separate le with the
extension .css and inserted via a special HTML tag. You can also put it directly into
the HTML document.
Imagine or a moment, in this abstract example, that we want to construct a house
with CSS code, where we choose items such as windows, doors, roong, walls,
gutters and so on. We would want to buy windows o specic sizes, and paint or
each o the necessary parts. I we built this house in CSS, one o the many solutions
to this task might look like this:
44
roof {
background-color: green;
}
doors {
background-color: yellow;
width: 100px;
height: 300px;
}
windows {
border: 5px solid brown;
width: 150px;
}
Let's analyze the "roo" block o this code rom top to bottom (note that top-to-
bottom reading is a rule when reading all types o code, not just HTML and CSS).
roof {
background-color: green;
}
I we translate the code above into normal English, we have chosen an element
called "roo" and set the background color to green.
windows {
border: 5px solid brown;
width: 150px;
}
The code above says, "or all windows, set the ollowing: a rame (border) with a
width o 5 pixels (5px), marked by a continuous line (solid) color (brown). Also, the
window itsel should have a (width) o 150 pixels (150px).
45
You might have noticed a recurring pattern in the code. On the rst line, we write
the name o the element (termed "selector"), and then dene the appearance o that
element between bracket.
selector {
property_name: property:value;
}
This type o construction is a typical CSS rule. The rule consists in turn o a selector
(everything beore the rst bracket) ollowed by a list o properties that you write
between the brackets.
There are various way to speciy exactly what we want to design. Let's say that we
only wanted to speciy design or windows on the ground oor. What then? We
could write something like:
The result is that only the selector has changed. Instead o "window {" we have
specied "ground oor window {"
This code reads rom let to right like "nd the ground oor, and then nd its
window and set the ollowing values." I we put a sub-selector under "ground oor
windows" like:
46
Then we're telling the browser: "nd the ground oor window, windows next to it,
and ll them with the ollowing values," and so on. I you remember the analogy in
which we talked about nested HTML tags as the children and parents, this is the
same concept, elements nested within other elements.
Unortunately a browser can't quite build a house, but our example tells us how CSS
works. This analogy is useul because as we code, we're not always able to see the
changes. But we can think o paragraphs (<p>) as windows, and doors as the header
(<h1>), etc.
p {
}
h1 {
}
Let's apply what we've learned in this analogy to our example and use the same
ideas to add a little color and lie to the Justin Beaver article.
47
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Justin Beaver fascinated by HTML</title>
</head>
<body>
<article>
<header>
<h1>Justin Beaver: Ever since I learned HTML, my life
has made a complete 180</h1>
<p>Posted by: Damian Wielgosik</p>
</header>
<p>Justin Beaver confessed something that even his
greatest fans would have never expected of the skilled musicians
and lyricist. The young rock-and-roller admitted that since he
typed his first title tag, his life became easier. It has been
reported by those surrounding the Canadian that Beaver's private
mentors, Ryan Loseling and Nicolas Crate, often walk around Los
Angeles disputing what a great tool the HTML validator is.</p>
<figure>
<img src="cat.jpg" alt="Justin Beaver's cat is pleased">
<figcaption>Justin Beaver's happy cat</figcaption>
</figure>
<p>Beaver has already created some websites and does not
intend to stop there. <q>I will probably have a song about HTML
on my next album,</q> - the artist added.
</p>
</article>
</body>
</html>
Recall the analogy o building a house. Instead o building doors, windows, etc., we
are dealing with elements like <article>, <p>, <header>, <body>, <gcaption> and so
on. These tags build the page and now CSS will help to give them style.
I've prepared a screenshot on the next page so you can see how our modications
will change the resulting website.
48
As you can see, much has changed. We've added simple colors, backgrounds,
changed the ont style and so on. Let's proceed step-by-step or how to accomplish
the efects in the image above.
The rst step is to save the entire HTML code into a separate le. For me it's called
article.html. Then create a separate le in which we keep our CSS rules. Let it be
main.css.
49
The les look like this on my computer:
We can now try to open article.html in a browser and the main.css le using a text
editor. I recommend Sublime Text Editor or TextMate. Ater each change made in
main.css, we can reresh the browser the page in order to update its appearance.
We now need to open the article.html in a browser, and load code rom the main.css
le. This is done through the tag <link> in the <head> in the HTML code. Just add a
tag like this in the head:
The "hre" attribute indicates where the le is located. "Stylesheet" tells us that it is a
CSS style sheet.
Okay, to start making changes to visual appearance in CSS, let's try to nd the right
selector or the heading, similar to the code or windows and walls.
h1 {
}
Here we are! It is here that we can tell the browser "or all elements in <h1>, apply
the ollowing appearances." Note that the braces are currently empty. Let's try to tell
it that we want the heading text to be green. We'll apply the property "color" and set
it to "green."
50
h1 {
color: green;
}
Let's check out how our page looks ater the changes!
51
Now we want to address the next section with inormation about the author. Let's
say we want the text in white with a red background as shown a ew pages ago. This
is the current HTML code:
<article>
<header>
<h1>Justin Beaver: Ever since I learned HTML, my life has
made a complete 180.</h1>
<p>Posted by: Damian Wielgosik</p>
</header>
Let's use CSS, and nd the appropriate selector ("p {" ) and try to give it a
background red color and a white color text:
p {
background-color: red;
color: white;
}
h1 {
color: green;
}
p {
background-color: red;
color: white;
}
As you can see, we add a rule one under the other. Time to see how it looks now our
website...
52
Oops, that's not quite right. It seems all the other paragraphs have also been
changed to have the new background and text color. It's a problem with our code,
because we used the ollowing:
p {
background-color: red;
color: white;
}
What we actually told the browser is to "nd all <p> elements and apply changes."
However, we only wanted to change the paragraph in the header line o the article.
We now need to modiy the code so that the above selector to only apply to the <p>
in <header>, which is a "child" o the <article>. The code should reect this
hierarchy:
article header p {
background-color: red;
color: white;
}
53
Much better! It seems we were able to target the correct paragraph. But how did this
happen? Well, we used the above code to tell the browser to know which tags the
CSS selector should target. We do this by examining the HTML code and nding all
the tags which should match the selector. In our case, we had nested tags o
<article>, <header>, and <p>, so the CSS selector "article header p" let's us speciy
exactly where the changes will be applied.
The dimensions o this article, let's say, should be 600 pixels wide. And remember
that our corresponding HTML tag or the image is <gure>. Let's speciy our CSS
code to reect this:
article figure {
width: 600px;
}
With this code, every <gure> in the <article> tag will have a width o 600 pixels.
Note that the "article" distinction would be helpul i we had multiple images
throughout the blog post and wanted to speciy diferent criteria or each. But since
we only have one image, let's move on to the border code:
article figure {
width: 600px;
border: 3px solid black;
}
Here we've added a property called "border." Ater the colon, we speciy the width o
the border (3 pixels), and the style o the border "solid" with the color "black."
54
It looks like we have a problem. While the border is displayed with the correct style
and color, the image displays beyond our 600 pixels. This is because we established
the width o the element <gure>, but the <img> tag does not have any xed width
and thus keeps its original size. It would be nice i the image took 100% o the width
o its parent <gure>. This is coded very simply:
55
It would be nice to add some "padding" or space between the border and image. We
do this by adding the property "padding." We can modiy the code as ollows:
article figure {
width: 600px;
border: 3px solid black;
padding: 5px;
}
The result:
56
You can try yoursel to modiy the value o the "padding" and see how the white gap
changes between the picture and the border.
Our page is looking good now, but we're not yet nished. The current paragraph text
extends almost the entire width o the browser window which isn't very readable.
Perhaps it would be tting to somehow reduce the width o the text? Maybe limit it
to 800 pixels?
article {
width: 800px;
}
57
That's better.
Now what about ont? I you look at the original image o our site, we have a slightly
diferent ont. Just as you can edit ont styles in Microsot Word, you can edit them in
CSS too. In order to speciy ont, you want to add this property to the highest tag so
that it applies to all text within that tag. For example, we'll set the ont as a property
or <body>, so that every element below <body> will have this setting. In the picture,
I used a ont called Verdana.
body {
font-family: Verdana;
}
You can see the diferences by deleting this line or changing the ont-amily to a
diferent style. For the header, paragraphs, etc. the browser will display everything in
Verdana.
Finally, our code in the main.css le should look like this:
58
body {
font-family: Verdana;
}
article {
width: 800px;
}
article header h1 {
color: green;
}
article header p {
background-color: red;
color: white;
}
article figure {
width: 600px;
border: 3px solid black;
padding: 5px;
}
In general, it's good practice to start your code with the most general selectors and
move into more complex ones. I started rom body, ollowed by article, and so on,
going rom top to bottom. The higher the detail, the lower it sits in the list.
59
CHAPTER 6
Menu, Please!
Another popular part o websites is menu. Basically, it's a list o items which are
oten just simple links pointing to other places on the site. Let's implement it! We will
start with the ollowing HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Menu</title>
<link rel="stylesheet" href="main.css" media="screen">
</head>
<body>
<nav>
<ul>
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="training.html">Training</a>
</li>
<li>
<a href="conferences.html">Conferences</a>
</li>
<li>
<a href="about.html">About us</a>
</li>
</ul>
</nav>
</body>
</html>
60
• Home
• Training
• Conerences
• About us
You might notice that under the <body> tag, we've added the new tags <nav>, <ul>,
and <li>.
<nav> is used or speciying all kinds o navigation unctions on websites that
contain links to internal or external inormation. So putting <nav> into the code says
"everything inside <nav> will be used to navigate around the website."
Within <nav>, we place the <ul> tag ollowed by several <li> tags. The tag <ul>
represents an "unordered list" (like a bullet list) and the <li> tags represent each
individual component o that list (single bullet). When creating websites, it's common
that an unordered list will be the most reasonable choice when it comes to mapping
61
menu pages. In act, the menu is kind o a list o links that has been created without
a predetermined rule as to the order o its elements.
With just the code above that is still unnished, our list should be displayed as
ollows:
You might have seen something similar, even when creating a text document on a
word processor, when you want to create a list with bullets. Without CSS <ul>,
however, our list would simply begin with a ".". In contrast, our menu can be much
more complex. We can give it a border, color, background, etc. Each link is by deault
displayed in blue as seen in the image above.
Let's now try to produce a more stylized menu in our CSS code.
Normally, we start rom the most general tag in the HTML code, right? In this case,
that top-most code begins with <nav> since this is responsible or our navigation
menu. Within this tag, there is not much to do since this tag does not deal directly
with the changes o appearances or the bullet list.
62
The next tag is then <ul>, which begins the unordered list. We want our list to be
displayed slightly diferently than the deault. The most important thing is to have a
new background:
nav ul {
background-color: PaleVioletRed;
}
For the background color we chose the name PaleVioletRed. Reloading the page
shows our changes as a result o adding this code.
Indeed, we've applied the color cyan as the background or the entire element o
<ul>. This is because we applies it to <nav> and <ul> tags, as per the ollowing
selector.
nav ul {}
Now we want to get rid o the black, round dots in this list to make it look more like a
menu. We can hide it, thanks to the property "list-style" as shown below:
63
nav ul {
background-color: PaleVioletRed;
list-style: none;
}
The large swath o color is surprisingly big. We're going to trim it down a bit using
the same exercise as the image border earlier (e.g. padding).
nav ul {
background-color: PaleVioletRed;
list-style: none;
padding: 0;
}
As you can see below, it looks much better now, slowly approaching a nice orm:
64
Now it's time to work on the dimensions. Our navigation has to be 200 pixels wide:
nav ul {
background-color: PaleVioletRed;
list-style: none;
padding: 0;
width: 200px;
}
At the end, we'll add a border to the list exactly like the image. It will be expressed as
a solid line, with a 1 pixel width, and a "light blue" color:
nav ul {
background-color: PaleVioletRed;
list-style: none;
padding: 0;
width: 200px;
border: 1px solid MediumVioletRed;
}
So there is our beautiul outer rame. Time to rame each individual item in the list,
which can be addressed using the ollowing CSS selector:
nav ul li {}
65
And so this code looks at <nav>, <ul> and then <li>. What seems to be of is that
each item in the list needs its own border:
nav ul li {
border-bottom: 1px solid MediumVioletRed;
}
With this code, we've added a border-bottom, so every <li> item now has the same
border type as the outer border, on the bottom portion o the text.
We now have two problems. The rst is the let-side spacing between the border
and the elements list. Let's change it using our riend "padding":
nav ul li {
border-bottom: 1px solid MediumVioletRed;
padding: 5px;
}
It's much better, right? We've added a 5 pixel wide padding between the text and the
borders.
66
Our second problem is less visible, but still exists as a double-line at the bottom o
our menu. This is because our border code or the menu is adding to our border
code or the last item when we added a "bottom-border." Remember that we used
the code in <ul> o <nav> to speciy a border:
nav ul {
background-color: PaleVioletRed;
list-style: none;
padding: 0;
width: 200px;
border: 1px solid MediumVioletRed;
}
And also remember that we set the list-style to "none" so that bullets or any others
signs don't appear:
list-style: none;
So by setting "none" as a value we will sort o disable a property so it won't have any
graphical efect.
67
Let's do the same thing, only using the property "bottom-border" and setting the
value to "none." However, we want to target only the last item in the menu, so that
its bottom border does not conict with the larger bottom border.
nav ul li:last-child {
border-bottom: none;
}
nav ul li:last-child {}
68
"Look at <nav>, then <ul>, and apply all changes to the 'last' <li> element."
The last thing we need to do is to adjust the text in the links. You create links in
HTML as ollows:
We're using the <a> tag along with the attribute hre. The value or this attribute
should be the address to which you want to move the user i he or she clicks on the
link. In our example, we have our links. One o them looks like this:
<a href="training.html">Training</a>
This means that the browser will show the word "Training" which can be clicked on
and then sends the browser to the page that has been saved in the le
"training.html."
Knowing that this tag is a part o HTML code, we can create a special CSS selector
that looks specically or this tag:
nav ul li a {}
Voilà!
Let's add new properties to our new selector. First o all, let's change the ont color
to white.
nav ul li a {
color: white;
}
69
Rereshing the browser shows our new changes:
Great! We now have white color links. Now let's change some emphasis marks. The
browser is set to highlight all links in the orm o "text-decoration: underline" in CSS.
We want to change this value, just like we did beore by using the value "none."
nav ul li a {
color: white;
text-decoration: none;
}
70
Beautiul! We have completed the menu that we wanted.
As a side note, i you are working with many links, you might remember that on
many pages when you hover over a link, the text becomes emphasized somehow.
When a mouse hovers over this link, something interesting happens that many
internet users know well—the text becomes emphasized, or in this case, underlined:
71
Let's try to do something similar in our menu that will allow a link to be highlighted
or emphasized whenever we hover over it. We'll use a pseudo-selector called
"hover":
nav ul li a:hover {
text-decoration: underline;
}
This time we added it to the links <a>. This means when you mouse over a link, the
efect will be applied. This applies to hovering over other elements as well:
div:hover
li:hover
img:hover
The efect is seen below when we hover over the "Conerences" link.
72
In summary, the nal CSS code should look like this:
nav ul {
background-color: PaleVioletRed;
list-style: none;
padding: 0;
width: 200px;
border: 1px solid MediumVioletRed;
}
nav ul li {
border-bottom: 1px solid MediumVioletRed;
padding: 5px;
}
nav ul li:last-child {
border-bottom: 0;
}
nav ul li a {
color: white;
text-decoration: none;
}
nav ul li a:hover {
text-decoration: underline;
}
The newly emerged pseudo-selectors (last-child and hover) will be useul in the
uture.
By the way, in this chapter you have learned how to use links and put them into
HTML documents. At this point, we have used only addresses pointing to the local
les (like training.html) saved on your computer, however you can also use links
reerring to external websites living on the web like this:
73
The above code in the browser will be displayed as My Book. Note that the address
contains "http://" or "https://" at the very begininng. It's a rule to learn that every link
you used in a HTML document that points to another website, must be prexed by
"http://" or "https://". Otherwise, your links won't redirect users to the places they
should.
74
CHAPTER 7
With this change, we run the risk o errors in the display. To minimize this risk, we
use CSS classes and IDs.
Every HTML element may have a special attribute named "class," where we can
provide one or more class names. Here are a ew examples o how you can add this
attribute:
75
And so on. Note that class names are arbitrary, and must be single words or
"clusters" using dashes like in the example o "my-item" or underscores like
"special_item".
You can also add multiple class names or a single tag:
You might be wondering what this means and why classes are useul. Suppose that
we create a page with inormation on sports news. Let us assume that we have a list
o news and we want to highlight one item (I've highlighted one line o our list
below). The code would look something like this:
<article><p>normal news</p></article>
<article><p>special news</p></article>
<article><p>normal news</p></article>
<article><p>normal news</p></article>
<article><p>normal news</p></article>
I we wanted to write CSS code that distinguishes a special background or only the
eatures news, we have a problem. Our expertise so ar allows us to "style" all the
elements in <article> in the orm o the selector:
article {}
But this will look or all <article> elements. CSS classes allow us to avoid this
conusion. Let's describe each o the <article> elements with a class that
corresponds to its importance or the entire site. So, let's call the important news
"main-news" and the rest "normal-news" as shown in the HTML code below:
76
<article class="normal-news"><p>normal news</p></article>
<article class="main-news"><p>special news</p></article>
<article class="normal-news"><p>normal news</p></article>
<article class="normal-news"><p>normal news</p></article>
<article class="normal-news"><p>normal news</p></article>
.main-news {
background-color: LightBlue;
}
.normal-news {
background-color: LightYellow;
}
For each class, note that they begin with a dot "." ollowed by the class name. So we
can use this construction to target selector elements o the same class in HTML. The
"main news" will now have a background color o light blue, while a normal news is
coloured in LightYellow.
77
Thanks to CSS classes, we can denote characteristics or specic elements on the
page, that allows us to simultaneously target and ignore elements with the same
tags. I we ever wanted to change <article> tag to something else, let's say <p>, we
wouldn't need to modiy our CSS code as well. That's a huge benet.
78
In addition to classes, we also have identiers. We use the attribute called "id" and
give it a value, very similar to how classes work. An example o an ID in HTML might
look like this:
<p id="main-content"></p>
#main-content {
background-color: red;
}
Instead o a "." beore the element, we use a hashtag "#" or identiers, ollowed by
the element name. The code above species that elements with the ID "main-
content" should have a red background.
79
It's very important to remember that identiers are unique, so the identier can only
be used once in an HTML document
document. The use o the attribute "id" should be
preceded by careul planning and analysis. It's also good practice to not abuse "id"
usage, as it is rare that good sites consists o several unique elements.
With our new knowledge o classes and identiers, let's rewrite our menu code to
make it more robust against changes in the HTML le. Perhaps in the uture we
decide that we would like to make it using other tags than <ul> and <li>. I we use
the appropriate classes, then we can sleep peaceully without having to worry about
changing the CSS code in parallel.
Let's start by modiying our HTML. Currently, our code or the navigation menu
currently looks like this:
80
<nav>
<ul>
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="training.html">Training</a>
</li>
<li>
<a href="conferences.html">Conferences</a>
</li>
<li>
<a href="about.html">About us</a>
</li>
</ul>
</nav>
Let's introduce a class. We'll give the entire container o the menu (tag <ul>) a class,
and each item under it (tag <li>) a "child" class.
<nav>
<ul class="site-nav">
<li class="site-nav-item">
<a href="index.html">Home</a>
</li>
<li class="site-nav-item">
<a href="training.html">Training</a>
</li>
<li class="site-nav-item">
<a href="conferences.html">Conferences</a>
</li>
<li class="site-nav-item">
<a href="about.html">About us</a>
</li>
</ul>
</nav>
For this menu, I've given the unordered list <ul> the "site-nav" class, while each <li>
item has the class "site-nav-item."
81
Time to customize the CSS code:
.site-nav {
background-color: PaleVioletRed;
list-style: none;
padding: 0;
width: 200px;
border: 1px solid MediumVioletRed;
}
.site-nav .site-nav-item {
border-bottom: 1px solid MediumVioletRed;
padding: 5px;
}
.site-nav .site-nav-item:last-child {
border-bottom: 0;
}
.site-nav .site-nav-item a {
color: white;
text-decoration: none;
}
To better understand what has changed, look at the comparison o the old and new
CSS code:
82
Try to compare each selector. As you can see, we traded the tag names or class
names, which gives us much more exibility in writing code. Note that they are
shortened by removing the redundant "nav" tag.
It's important to try to use class names as selectors instead o tags, unless it is
obvious like <a> or addresses. This cannot be replaced with any other HTML tag.
Identiers are only used when the item is unique in the page. In this cause, it could
be just the menu, but otentimes navigation appears several times on a website (or
example at the bottom and top).
The operation and denition o classes and IDs are summarized in the ollowing
diagram:
83
84
CHAPTER 8
Summary Time!
Time to rest a moment and reect on what we’ve learned so ar. By now, you’ve met
many o the basic concepts required to create web pages.
We began by understanding how websites are built, with plain text that describes
how individual parts work and compared them to how blocks are stacked one on
top o the other.
With this analogy, we ound that blocks correspond to HTML tags. All HTML tags are
predened and denitions, best uses, and synergies between other elements are
standardized by the W3C organization. For example, i we need a paragraph o text,
we use the <p> block. I we need an article, we use the <article> block. I we’re
dealing with headers, we use hierarchies o <h1>, <h2>, <h3>, <h4>, <h5> or <h6>
depending on the context. We know that the entire list o HTML tags can be ound
on the HTML specication.
We ound that tags can be nested within one another. For example, the article or
our page that consisted o a title, image, and paragraphs. These elements were
denoted by <header>, <h1>, <gure> and <p>, which were then nested under the
"parent" tag <article>. In HTML we try to think hierarchically. We build large blocks
with smaller blocks and always put the most important blocks higher in the code
than the less important blocks.
Then we ound that websites with only this HTML code are visually unattractive. With
CSS, we learned that we can target HTML tags and decorate them with special
85
selectors. We know that i we wanted to get "all the paragraphs in an <article>, our
CSS selector should be written as with properties and values that we want within the
brackets.
article p {}
<article class="news">...</article>
.news {}
In this way, we have learned the most important undamentals o HTML and CSS.
When building web pages, we always divide content into smaller parts and
determine the unction o elements. We try to be as specic as possible or even the
smallest element, being able to code and describe things like menus, articles, titles,
dates, paragraphs, quotes and pictures.
Always remember that HTML is a data layer while CSS is a presentation layer. It
means, that HTML stores data inormation described by the use o proper tags,
when CSS code has to visualize this data adding colors, onts, borders and so on.
86
At this point you have probably asked yoursel how one can publish a page on the
web so your riends can see it. Being more precise, how does it happen that ater
typing unctionite.com in a browser address bar, you actually see a website? It's
simple. First of, you need to buy a domain which will be a virtual address o your
own website. In above example, I had to register unctionite.com. There are a lot o
companies that make this process easy. All you need to know is a unique domain
name that will be pointing to your website. Ater you have a unique id where your
website is going to be available at, you need a web server to where you will upload
your complete website. All images, CSS, HTML and other les must be rst uploaded
to that server, which is actually a special computer connected to the internet, that
makes your website be accessible rom any place in the world. Again, the web
servers business is a huge market and you will certainly nd a decent company that
you can purchase a server space rom. There are also companies that ofer easy
deals so you can purchase a domain and a web server access at once.
87
CHAPTER 9
Forms in HTML
So ar, we've managed to create a ew interesting versions o the website. We
haven't yet covered the orms or which users can enter data. Forms are used across
the Internet everywhere; search engines like Google or Bing, Facebook status elds,
or Gmail email editors allow you to type or send inormation.
Let's make a simple orm to allow users comment on our article. We want the orm
to look something like the ollowing image:
88
Let's now select the individual components that make up the orm. We will use the
same selection colors or elements that perorm a similar unction:
As you can see, blue indicates names or description or each o the elds. Green
elements show places where you can enter one-liner text. The orange area lets you
enter longer chunks o text, and purple is used or a button to send the orm. For
each group, we'll use the same tag.
For names we'll use <label>. For shorter elds – <input type="text">. The longer texts
will use <textarea>. Buttons are made with <input type="submit">. These are the
most popular elements o HTML, that are used to build orms on websites. As
always, we start with a blank HTML template page and add then add more elements.
89
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Form</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
</body>
</html>
We need to use the appropriate tag that tells the browser, "Hey, the orm starts
here!" This is very similar to the tag <article> or indicating where an article element
starts). In HTML, we use the <orm> tag or indicating a orm element
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Form</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<form>
</form>
</body>
</html>
Now, we want to add the rst description name: "Your nickname." From here on,
we'll examine the code ragments that are contained under <orm>, because the
rest o the HTML is already well known to you.
<form>
<label for="nickname">Your nickname:</label>
<input type="text" id="nickname" name="nickname">
</form>
90
Here we have two <label> elements which give the description name, and the
<input> elements or text input. The <input> tag has three attributes: input type with
a "text" value, name with "nickname" value and id also with "nickname" value. The
"type" attribute's value means that it's a short text eld.
You'll use <input type="text"> in your code to indicate that a user can type within the
eld. Note that text elds can be styled using CSS. We can change its border, width,
or distance between any text and a text eld border. A rough example is shown
below:
The "name" attribute is used to name each o the elds. This is useul when you
send the orm to the server. It helps to identiy which value comes rom which eld.
Note also the correlation between the value o the "id" and the value o "or"
attribute in <label>:
In the "or" attribute, you should use the id o the eld described by the <label>
element.
91
<form>
<label for="nickname">Your nickname:</label>
<input type="text" id="nickname" name="nickname">
<label for="user-email">Your e-mail:</label>
<input type="email" id="user-email" name="user-email">
</form>
The only diference here is that the "type" attribute has an "email" value. The
meaning is, o course, so that the user can enter their email. Note that anything
typed within the "email" eld will have to be validated as a correct e-mail address. I
it's not a valid email, the browser will display an error message and will not send the
orm.
Another eld we need to add is a place or the comment. For longer texts, we use
the <textarea> tag:
<form>
<label for="nickname">Your nickname:</label>
<input type="text" id="nickname" name="nickname">
<label for="user-email">Your e-mail:</label>
<input type="email" id="user-email" name="user-email">
<label for="content">Content:</label>
<textarea rows="10" cols="50" id="content" name="content"
></textarea>
</form>
Note that we used two new attributes: rows and cols. The "rows" attribute is used
or the number o text lines that can be entered into the eld until a scrollbar
appears. "cols" is used or the number o character in each line. Try changing the
values or yoursel and see how the entire eld expands or contracts accordingly.
The last thing we need to add is a button or sending the orm.
92
<form>
<label for="nickname">Your nickname:</label>
<input type="text" id="nickname" name="nickname">
<label for="user-email">Your e-mail:</label>
<input type="email" id="user-email" name="user-email">
<label for="content">Content:</label>
<textarea rows="10" cols="50" id="content" name="content"
></textarea>
<input type="submit" value="Add">
</form>
The element <input> has the attribute type equal to submit. Whatever is typed into
the value attribute will display as text on our website button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Formularz</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<form>
<label for="nickname">Your nickname:</label>
<input type="text" id="nickname" name="nickname">
<label for="user-email">Your e-mail:</label>
<input type="email" id="user-email" name="user-email">
<label for="content">Content:</label>
<textarea rows="10" cols="50" id="content" name="content"
></textarea>
<input type="submit" value="Add">
</form>
</body>
</html>
93
It doesn't look nice. In the next chapter we will gure out how to x it.
94
CHAPTER 10
First, let's gure out how one makes elements display one ater the other vertically.
We basically need to tell the browser, "Hey, we want a container which can be
vertically stacked". Fortunately, this container tag is known as <div>, and will sort o
"break" content to new lines (like page breaks or line breaks in word processors).
To see how the <div> elements work, let's use three o these and let's set them
width, height, and background.
Under the assumptions given above, the HTML will look like this:
<div class="container"></div>
<div class="container"></div>
<div class="container"></div>
In CSS, we write the class ".container" when reerring to the <div> tag.
95
.container {
width: 200px;
height: 200px;
background-color: blue;
}
Looks like a one big rectangle. What about separating <div> tags 10 pixels rom the
bottom?
.container {
width: 200px;
height: 200px;
background-color: blue;
margin-bottom: 10px;
}
96
Great! The browser displays these "blocks" one by one, in contrast to our previous
example o a web orm where the elements appeared on the same line.
Why is this diferent? When it comes to the display o tags, the browser recognizes
three groups o elements:
• inline
• block-level
• inline block-level
Inline elements do not cause transitions to a new line, but will be displayed one next
to the other horizontally. Block elements are set like blocks that stack on top o each
other and will never display next to one another horizontally, unless we use magic
tricks in CSS (which we'll learn in the next chapter). Inline blocks will act as inline
elements (elements are displayed next to each other), but difer in that they can be
or instance resized. For example, the <textarea> eld can be displayed as a large
rectangle, but it can take up space beyond a single line o text.
97
Let me share with you some examples o items that can be classied according to
one o the three groups.
By deault, inline elements have CSS display property set to inline. For block-level
elements, its value is "block", and or inline block elements it's "inline-block". So you
can explain that <span> tag doesn't cause breaking the text to the new line, because
it's an inline element which means in CSS it has a property "display" set to "inline".
So, considering the below code:
However, it's possible to change this behavior by adding one line o CSS:
span {
display: block;
}
Now, our <span> tags display diferently, each one in a new line, since we have set
their display property to block:
one
two
three
98
For this example, we use <div>. You may wonder what this tag describes within the
document. The short answer is nothing. We use the <div> tag in cases where all
other tags do not nd a use or what we've put in the document. It is common,
thereore, that the <div> tag (in conjunction with other classes) is used to achieve
diferent visual efects, as a result o it having no unction or describing content. For
example, i you want to make three vertical columns on our website, we might need
an item that can separate some elements o inline or inline block elements.
In general, it's a good idea to not overuse the <div> tag i possible.
With our new ound knowledge o blocks, let's make up our orm code so that the
orm elds and their descriptions are displayed nicely one on top o the other:
<form>
<div>
<label for="nickname">Your nickname:</label>
</div>
<div>
<input type="text" id="nickname" name="nickname">
</div>
<div>
<label for="user-email">Your e-mail:</label>
</div>
<div>
<input type="email" id="user-email" name="user-email">
</div>
<div>
<label for="content">Content:</label>
</div>
<div>
<textarea rows="10" cols="50" id="content" name="content"
></textarea>
</div>
<div>
<input type="submit" value="Add">
</div>
</form>
99
It looks a bit more complicated, but the only thing we've done here is add <div> tags
to surround each o the elements on the orm.
Once again, let's look at a code comparison o our new code (let) against the old
one (right):
And now see how the new code displays in your browser!
100
Our orm looks excellent now!
101
CHAPTER 11
Form Extras
I have a ew more surprises in store or you. We can now use a number o attributes
that will help make our orm more attractive. One o them is a placeholder text. Let's
add it to one o the orm elds, <textarea>:
The efect?
As you can see, in the middle o <textarea>, text has appeared with an additional
description o this eld, which corresponds to what we put in the attribute
"placeholder". Peace o mind, when you click this text will disappear and you will be
able to enter your own content. I you leave the eld blank is also nothing will
102
happen - the contents o the "placeholder" will not be sent away, it serves only to
hint to the user. This attribute can also use elements <input>.
Another very useul attribute is required, which is added to the orm elements
without any value. For example, an e-mail will look like this:
Now, when we leave the eld blank, when you send the orm we will see the error:
There is plenty o useul attributes you can use together with orm elements. Let's
consider Google search input or a moment:
103
It's encoded per the ollowing (as o April 2015):
As you can see, the element input has a bit more than the usual attributes we used.
Try or yoursel to nd the HTML specications or each o them. Even Google will
help you here :).
Attributes are also useul or transmitting elements rom CSS. For example, each
element input with the attribute "type" equal to "text", as shown below:
input[type="text"] {
border: 1px solid blue;
}
In the example above, each element input has the attribute "type" equal to "text"
with the value o a blue rame:
104
Similarly, we can use the same or the email eld:
input[type="text"] {
border: 1px solid blue;
}
input[type="email"] {
border: 1px solid blue;
}
105
As you can see, we've created two selectors in CSS which give the same value,
specically or "border." I we wanted to use something like this or a larger number
o elements, we would probably copy one o those selectors and modiy it slightly.
As a result, we would have more independent selectors doing the same thing (i.e.
setting borders). In CSS, you can shorten the operation, listing selectors ater a
comma to orm a group.
input[type="text"],
input[type="email"] {
border: 1px solid blue;
}
106
You can see that we saved space and simplied our code to have better clarity.
Using our previous example, all combinations are possible selectors that we want to
group:
.news-item,
article p,
#main header h1 {
padding: 5px;
margin: 5px;
}
Always keep in mind grouping selectors allows you to repeat certain values or
several elements. This way, you have one piece o code or multiple elements in the
HTML, and you won't have to look too ar in the CSS le to make modications.
107
CHAPTER 12
Multi-Column Layout
In the previous example, we learned, among other things, the <div> tag. You know
that they have no semantic meaning and serve primarily as a container or other
blocks. Usually you add them to apply various visual changes through CSS or larger
parts o the website that resemble boxes or rectangles.
So ar, we have managed to get a view o the article, create a menu, and a comment
orm. Let's put them all together in a 3-column layout with the menu on the let,
article and comment orms in the middle, and a list o materials related to the article
on the right. Let's assume that the whole o this page is 960 pixels wide, centered.
108
Let's try again to identiy what we see in the graphic, unctional parts, which are
mapped by HTML. We have the let column which contains the menu. The central
column contains the main content o the page. The right column contains a short
text.
Let's start rom the container that holds these three columns. As we noted earlier,
we want all o them to be contained within a space no wider than 960 pixels. HTML
does not have social tags or such a circumstance, we we'll use our old riend, the
<div> tag.
<div class="main-container"></div>
109
We have just given <div> the class main-container which says that this is the main
container or other item on our website.
Now to add the place or menu. It will be included in <div class="site-menu">:
<div class="main-container">
<nav class="site-menu"></nav>
</div>
Moving orward, we place the container or the main content in the middle o the
column:
<div class="main-container">
<nav class="site-menu"></nav>
<div class="main-content"></div>
</div>
<div class="main-container">
<nav class="site-menu"></nav>
<div class="main-content"></div>
<aside class="sidebar"></aside>
</div>
Now let's analyze our next step based on the picture. What content should the let-
column contain? As the name suggests, this should be our menu rom the previous
exercises:
110
<div class="main-container">
<nav class="site-menu">
insert menu code here
</nav>
<div class="main-content"></div>
<aside class="sidebar"></aside>
</div>
I've put placeholder text inside o the <nav> tag or the menu code to preserve
readability. When we are ready to publish our website, we will simply copy the code
rom our menu and paste it between <nav> and </nav>.
The middle column will contain the article and comment orm:
<div class="main-container">
<nav class="site-menu">
insert menu code here
</nav>
<div class="main-content">
<article>insert article code here</article>
<form>insert form code here</form>
</div>
<aside class="sidebar"></aside>
</div>
For the right column, we'll put a side item unrelated to the main content, using the
tag <aside>:
111
<div class="main-container">
<nav class="site-menu">
insert menu code here
</nav>
<div class="main-content">
<article>insert article code here</article>
<form>insert form code here</form>
</div>
<aside class="sidebar">
<div>insert sidebar code here</div>
</aside>
</div>
Ok, our HTML is ready. Now it's time or CSS. Our rst task is to set the maximum
width or the main container with class "main container":
.main-container {
max-width: 960px;
}
We've given it the property max-width, so whatever happens, the width o the entire
container named with a class main-container will never be wider than 960 pixels.
.main-container {
max-width: 960px;
margin: auto;
}
With this code, the browser will take up all ree space around .main-container and
distribute the space equally between the two margins.
112
We now have all the code responsible or the main container. Let's proceed to code
our three columns. Let the container o the menu have 20% o the available width.
This is done simply by speciying a percentage value:
.site-menu {
width: 20%;
}
.sidebar {
width: 20%;
}
Since the let and right column have the same properties, we can group them with a
comma:
.site-menu,
.sidebar {
width: 20%;
}
Now let's get to the middle column. It will take the remaining width (60%), as the two
side columns occupy a total o 40%.
.main-content {
width: 60%;
}
Unortunately, our containers still appear in a block (one above the other). To set
them next to each other, we need to give them a special CSS oat property. We use
it to tell the browser that we want X item closer to the let or right edge o the
container in which it is placed. When one container has elements "oated" to the let
113
edge, they will set up next to each other and we can cleverly take advantage o this
mechanic.
This is because the let-hand column "sticks" to the let edge o the main container.
Beore we get to use CSS oat, however, I want to show you the most common use
case o this property. Imagine that you have an image set directly within text:
114
This happens because the tag <img> is is a "line" component, so it was inserted at
the beginning o the line and the text will simply ollow it.
However, i we set the image to "oat" to the "right" we will see something much
better:
img {
float: right;
}
115
The picture is now "oating" on the right edge o the text in which it was placed. In
this case, the edges o the paragraph <p>.
116
As you can see, the picture is now "oating" to the let edge o the paragraph, and
the text wrapped around it on the right side.
Returning to our columns, we can do the same thing with to all columns that we
want to position "let" at the edge o the container. Notice that we're about to oat
all containers as grouped with commas:
.site-menu,
.main-content,
.sidebar {
float: left;
}
117
Bingo! See how our browser now displays the elements:
Let's analyze what happened ater we "oated let." Each element will attempt to
oat let in terms o their priority in the list. So in this case, .site-nav took the
letmost edge, and .main-content was next in line to ll in the let-most space.
Finally, the .sidebar lled in the last "let" edge, completing the arrangement.
.main-content {
width: 60%;
background-color: LightPink;
}
.site-menu {
background-color: LightGoldenRodYellow;
}
.sidebar {
background-color: LightSteelBlue;
}
The efect is satisactory. The ollowing result shows that we managed to divide the
main container columns correctly:
118
.main-container {
max-width: 960px;
margin: auto;
}
.site-menu,
.main-content,
.sidebar {
float: left;
}
.site-menu,
.sidebar {
width: 20%;
}
.main-content {
width: 60%;
background-color: LightPink;
}
.site-menu {
background-color: LightGoldenRodYellow;
}
.sidebar {
background-color: LightSteelBlue;
}
With this code, we've created a simply layout with three columns. Now, you just
need to paste the remaining HTML and CSS code rom our previous exercises and
our job is done!
119
CHAPTER 13
What's Next?
Congratulations on building your rst ull-edged website. You skillully created a
page with three columns, a menu, and a comment orm.
The next steps you perorm as a developer are up to you, and there are endless
possibilities. Perhaps you're wondering what you should do next? I have a ew tips
that might help!
Then, choose your avorite website and try to play around and write the code rom
scratch. Find the sites' individual parts and identiy their unctionality. First create
the HTML code, then apply the CSS (always in that order). Ater you nish, check it
against the original and ask yoursel what there is let to learn. That would be a
perect way to start!
PATTERNS
For the urther development, it's crucial to realize that ront-end programming (as a
name or coding the user interaces, in a web context it's mainly writing code in
HTML, CSS and JavaScript) is a job based on well-known repeatable steps. Each time
you work on a new website you will have to prepare a semantic HTML markup and
then write CSS code to get efects that reect the website design you have been
assigned to. The god is in the details though and that's why ront-end is an
interesting eld.
As you learn more, you will quickly nd out that there are usually many diferent
ways to solve a problem and it's up to you to choose the most suitable. Even a
120
simple circle can be displayed on the website in various ways. You can use an image,
HTML5 canvas, SVG markup or CSS border-radius property. Remember our multi-
column project? This can be also done in a ew ways at least (try to Google or
"inline-block layout", "ex-box column layout"). You need to gure out what ts your
project needs best.
REALITY
The reality o the website programming is that modern browsers constantly improve
by adding new CSS and HTML eatures. Week by week you get a browser update
with tons o new eatures. As a developer, you need to incorporate all o them and
leverage the most proper one based on diferent circumstances. You will have to
answer questions like what browsers my projects aim to support and so on. You will
have to decide i you care about a certain number o people using "X" browser.
Then, more questions appear. "X" browser might be supporting rounded corners in
CSS, while others not. I you wanted to support both browsers, you'd need to nd a
suitable workaround or this problem. It's one o the ront-end developer's
responsibilities – you will be selecting tools and techniques that will work in every
browser your project is supposed to support.
HISTORY
Thus, it's important to learn a history o HTML and CSS development. It's been a
crazy ride over last twenty years and some o the side-efects o this are still present.
We have been constantly learning new things and while we have been trying to nd
answers, we have introduced new questions as well. You will be learning about them
while approaching these problems. It's what the process o sel-development looks
like.
121
MAKE MISTAKES
GOOD NEWS
However, the good news is that even though we are bombarded by a lot o new
things each day, all o them are built on the oundations known or years. HTML and
CSS don't drastically change their orms or a way you write in them. No. These
languages remain more or less the same. Year ater year we just have more answers
to certain problems.
You might ask a question though. What is trending right now? What I need to be
aware o?
ACCESSIBILITY
285 million people are estimated to be visually impaired worldwide: 39 million are blind
and 246 have low vision. WHO
Many new concepts have come alive in recent years that will continue to grow in
importance into the uture. One o them is web accessibility.
Web accessibility reers to the inclusive practice o removing barriers that prevent
interaction with, or access to websites, by people with disabilities. When sites are
correctly designed, developed and edited, all users have equal access to inormation
and unctionality.
122
A responsible developer just can't orget about it. I trully recommend you Web
Accessibility: Web Standards and Regulatory Compliance and Apps For All: Coding
Accessible Web Applications to get started on this important subject.
Another recent web development technique is Responsive Web Design. In short, it's
about how we design websites to appear nicely and readable on diferent devices
including mobile phones, tablets and TVs. It actually makes sense to think a bit over
why it makes a diference. In order to deliver a successul user experience (or
example in your e-commerce business), you can't provide the same website layout
or mobile phones and laptops. Well, actually you can, but it might turn out
inefective. Having a limited screen space on mobile, it might make sense to
reconsider the website layout and accomodate the available space diferently. And
that's where RWD becomes handul. Thanks to it, you can set a specic bunch o CSS
rules only or a certain screen resolutions so your website will look diferent on
mobile devices whereas on laptops it can remain the same. Here's a simple example
or setting a specic CSS rules only or devices wider than 320px:
We used "media queries" here. In above snippet, every .news element in your code
will be hidden or screen resolutions wider than 320px (because we set display:
none).
123
There are o course more trending topics you will learn soon as you continue
learning. In 2015, as web developers we build parallax websites, tell interactive
stories using HTML video and audio or let people draw literally in the browser. Take
a look at the ollowing list to get a better sense o what modern web development is
about:
• Species in Pieces – is an interactive exhibition turned study into 30 o the world's most
interesting but unortunately endangered species — their survivals laying literally, in pieces.
All species are presented as CSS polygons.
• Apple MacBook – interesting animation o olding in/out the Macbook using HTML5 video
• Echoes o Tsunami – a terric story o 2004's Tsunami and its efects. 10 years ater the
catastrophe, Action against Hunger commemorates the tsunami.
• Interactive Resume
Try more new concepts. The ollowing are very attractive topics:
• box model
• progressive enhancement
• mobile rst
• grid systems
124
• CSS Grid
• CSS Flexbox
• css rameworks
• semantic web
• accessibility
• WAI-ARIA
• JS For Cats
• CSS Tricks
• Smashing Magazine
• WebPlatorm Daily
• JavaScript Weekly
Check also:
Other than that, try to constantly learn new HTML5 tags and play with new things
around CSS3. I you are not sure whether a eature you want to use is widely
supported, go to Caniuse.com and check. I you look or a decent documentation,
please visit Mozilla Developer Network. Moreover, experiment at codepen.io. Check
JSBin or JSFiddle, where you can write code and get an auto preview o your work.
No need to save les locally!
125
And most importantly: Love One Another!
126